Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 832e5fa048 | |||
| c6c6dfa5bc | |||
| ece049c993 | |||
| f4648b3c06 | |||
| cda7d72e44 | |||
| 13d6b917bb | |||
| 9fa502c500 | |||
| be45be9eab | |||
| 6ab4789a70 | |||
| df332a06ba | |||
| 111fa8e367 | |||
| 231403c1d5 | |||
| e98cb7abd7 | |||
| e0eb3c2d1b | |||
| 6dee318976 | |||
| b16c0fd526 | |||
| 3c99ff547b | |||
| e11886bde9 | |||
| 77f469c1dd | |||
| d6ce4a0fb0 | |||
| d2f7ce112c | |||
| a02d2abe49 | |||
| d5c89e9602 | |||
| 6205c85b61 | |||
| 157dad9192 | |||
| 8124150e34 | |||
| 78595be2a2 | |||
| 5ec53b87bc | |||
| f5749947e1 |
@@ -0,0 +1,53 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Lint (ruff)
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python 3.12
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.12"
|
||||||
|
|
||||||
|
- name: Install ruff
|
||||||
|
run: pip install ruff
|
||||||
|
|
||||||
|
- name: ruff check
|
||||||
|
run: ruff check .
|
||||||
|
|
||||||
|
- name: ruff format --check
|
||||||
|
run: ruff format --check .
|
||||||
|
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Tests (py${{ matrix.python }})
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
python: ["3.10", "3.12"]
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python ${{ matrix.python }}
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: ${{ matrix.python }}
|
||||||
|
|
||||||
|
# bcc_core has no GUI imports, so the test suite needs no PySide6 —
|
||||||
|
# keeps CI fast and avoids Qt system-library headaches on the runner.
|
||||||
|
- name: Install test dependencies
|
||||||
|
run: pip install pytest
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: python -m pytest -v
|
||||||
@@ -5,6 +5,12 @@ __pycache__/
|
|||||||
.venv/
|
.venv/
|
||||||
venv/
|
venv/
|
||||||
|
|
||||||
|
# Test / lint caches
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
# PyInstaller / build
|
# PyInstaller / build
|
||||||
build/
|
build/
|
||||||
dist/
|
dist/
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Install once with: pip install pre-commit && pre-commit install
|
||||||
|
repos:
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
rev: v0.8.4
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args: [--fix]
|
||||||
|
- id: ruff-format
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v5.0.0
|
||||||
|
hooks:
|
||||||
|
- id: trailing-whitespace
|
||||||
|
- id: end-of-file-fixer
|
||||||
|
- id: check-yaml
|
||||||
|
- id: check-json
|
||||||
@@ -8,10 +8,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
# Install runtime dependency
|
# Install runtime dependency
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
python bcc.py # run the GUI
|
python bcc.py # run the GUI
|
||||||
python test_core.py # run unit tests (23 tests, no GUI needed)
|
|
||||||
|
# Test & lint (no GUI / PySide6 needed — tests only exercise bcc_core)
|
||||||
|
pip install -r requirements-dev.txt
|
||||||
|
python -m pytest # unit tests in tests/
|
||||||
|
ruff check . # lint
|
||||||
|
ruff format . # format (CI enforces ruff format --check)
|
||||||
|
|
||||||
# Build a self-contained binary
|
# Build a self-contained binary
|
||||||
pip install -r requirements-dev.txt
|
|
||||||
python scripts/build_icons.py # regenerate icons/app.icns + icons/app.ico if needed
|
python scripts/build_icons.py # regenerate icons/app.icns + icons/app.ico if needed
|
||||||
pyinstaller bcc.spec
|
pyinstaller bcc.spec
|
||||||
# macOS → dist/BetterClaudeConfig.app
|
# macOS → dist/BetterClaudeConfig.app
|
||||||
@@ -19,7 +23,7 @@ pyinstaller bcc.spec
|
|||||||
# Linux → dist/BetterClaudeConfig
|
# Linux → dist/BetterClaudeConfig
|
||||||
```
|
```
|
||||||
|
|
||||||
Requires Python 3.10+. Runtime dependency: `PySide6>=6.6`. Build-time: `pyinstaller>=6.0`, `pillow>=10.0`.
|
Requires Python 3.10+. Runtime dependency: `PySide6>=6.6`. Tooling config (ruff, pytest, project metadata) lives in `pyproject.toml`. CI (`.github/workflows/ci.yml`) runs lint + tests on every push/PR; releases build on tag push (`release.yml`).
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -27,9 +31,9 @@ The codebase is split into two layers:
|
|||||||
|
|
||||||
**`bcc_core.py`** — All logic with no GUI imports. Contains:
|
**`bcc_core.py`** — All logic with no GUI imports. Contains:
|
||||||
- `Profile` / `ServerEntry` dataclasses (the data model)
|
- `Profile` / `ServerEntry` dataclasses (the data model)
|
||||||
- `discover_profiles()` — scans the platform's app-support directory for `Claude*` folders (Claude Desktop) **and** always adds `~/.claude/settings.json` (Claude Code, cross-platform)
|
- `discover_profiles()` — scans the platform's app-support directory for `Claude*` folders (Claude Desktop) **and** always adds `~/.claude.json` (Claude Code user scope — what `claude mcp add` writes). `~/.claude/settings.json` is NOT a server config (it rejects `mcpServers` with a schema error) and is only surfaced, labelled legacy, if servers are found parked in it. Project-scope `.mcp.json` files can be opened via Add config…
|
||||||
- `load_config` / `extract_servers` / `apply_servers` / `write_config` — the read/write pipeline; writes are atomic with rotating timestamped backups in `.bcc_backups/`
|
- `load_config` / `extract_servers` / `apply_servers` / `write_config` — the read/write pipeline; writes are atomic with rotating timestamped backups in `.bcc_backups/`
|
||||||
- `parse_pasted_json()` — accepts three JSON shapes (full config, inner map, or bare server object)
|
- `parse_pasted_json()` / `parse_pasted_json_verbose()` — accepts three JSON shapes (full config, inner map, or bare server object). Input does not have to be valid JSON: `repair_json_text()` auto-fixes markdown fences, surrounding prose, `//` `/* */` `#` comments, trailing/missing commas, smart quotes, single quotes, unquoted keys, Python/JS literals, and unclosed braces. The verbose variant also returns human-readable notes describing every repair applied (shown live in the paste dialog)
|
||||||
- `check_dependency()` / `diagnostics_text()` / `pin_command_path()` — PATH resolution logic; distinguishes "found on normal PATH" (ok) vs "found only on augmented PATH" (warn) vs "not found" (missing). Uses an `lru_cache`-memoized `augmented_path()` that extends the inherited PATH with common runtime locations (nvm, homebrew, cargo, volta, etc.)
|
- `check_dependency()` / `diagnostics_text()` / `pin_command_path()` — PATH resolution logic; distinguishes "found on normal PATH" (ok) vs "found only on augmented PATH" (warn) vs "not found" (missing). Uses an `lru_cache`-memoized `augmented_path()` that extends the inherited PATH with common runtime locations (nvm, homebrew, cargo, volta, etc.)
|
||||||
- `test_remote()` — synchronous HTTP reachability check, intended to run off the UI thread
|
- `test_remote()` — synchronous HTTP reachability check, intended to run off the UI thread
|
||||||
|
|
||||||
|
|||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
# HANDOFF — BCC feature backlog implementation
|
||||||
|
|
||||||
|
For the Claude Code agent working in this repo. Read this whole file, then
|
||||||
|
CLAUDE.md, before touching code. A supervising Claude session watches this
|
||||||
|
project through the Gitea MCP (issues, PRs, CI runs on git.avezzano.io), so
|
||||||
|
keep all state in Gitea where it can be seen: issues for work items, PRs for
|
||||||
|
changes, comments for decisions.
|
||||||
|
|
||||||
|
## Step 0 — sync state
|
||||||
|
|
||||||
|
`main` may contain local commits that aren't on origin yet (the previous
|
||||||
|
session couldn't push). Run `git status` / `git log origin/main..main`; if
|
||||||
|
there are unpushed commits, **push them first** and confirm CI goes green
|
||||||
|
before starting anything.
|
||||||
|
|
||||||
|
## Step 1 — file the backlog as issues
|
||||||
|
|
||||||
|
Create one Gitea issue per item in the backlog table below (`tea` CLI or the
|
||||||
|
API — you have full credentials). Prefix titles with the ID (e.g.
|
||||||
|
"[#2] Stdio server spawn-test"). Create labels P0/P1/P2 first if they don't
|
||||||
|
exist. Copy each item's full section from `../bcc-feature-requests.md`
|
||||||
|
(sibling of this repo folder) into the issue body — it has problem statements,
|
||||||
|
evidence, proposed fixes, and acceptance criteria.
|
||||||
|
|
||||||
|
**Corrections to that document — do not re-implement:**
|
||||||
|
- "Doc correction: README Claude Code path" — DONE (commit `b16c0fd`).
|
||||||
|
- Item 1 (secret masking) — MOSTLY DONE (commit `6dee318`): env/header values
|
||||||
|
masked via delegate + Show-secrets toggle, Add-dialog password echo,
|
||||||
|
diagnostics args redaction (`redact_args`). **Only remainder:** the warning
|
||||||
|
badge when a secret-shaped value sits in `args` instead of `env`. File the
|
||||||
|
issue scoped to just that.
|
||||||
|
|
||||||
|
## Step 2 — work the backlog
|
||||||
|
|
||||||
|
| Order | ID | Item | Priority | Notes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 | 2 | Stdio server spawn-test | P0 | Spawn with timeout, capture stderr; core logic in bcc_core (GUI-free, testable) |
|
||||||
|
| 2 | 3 | Backup restore UI | P0 | List `.bcc_backups/`, preview/diff, restore through normal atomic-write path |
|
||||||
|
| 3 | 4 | Stale-file protection | P0 | mtime/hash at load, re-check before write, prompt on conflict |
|
||||||
|
| 4 | 1r | Secret-in-args warning badge | P0 | Remainder of item 1; `is_secret_key`/`_is_secret_value` already exist in bcc_core |
|
||||||
|
| 5 | 8 | Duplicate-name conflict on paste/import | P1 | VERIFY FIRST: check `paste_json`/`dropEvent` in bcc.py for silent overwrite; file findings on the issue before coding |
|
||||||
|
| 6 | 5 | Cross-client support (Cursor/Windsurf/VS Code) | P1 | VS Code uses `servers` not `mcpServers` — needs a read/write adapter, not just paths |
|
||||||
|
| 7 | 6 | In-app MCP log viewer | P1 | Platform log paths in the doc |
|
||||||
|
| 8 | 7 | Windows MSIX path detection | P1 | Can't test locally on macOS — unit-test the detection logic, note that in the PR |
|
||||||
|
| 9 | 9 | Restart Claude Desktop button | P1 | Platform-specific process handling; scope to Desktop only |
|
||||||
|
| 10 | 10 | Server catalog / one-click add | P2 | Design pass first — post a proposal as an issue comment before building |
|
||||||
|
|
||||||
|
## Workflow rules
|
||||||
|
|
||||||
|
- **Branch per issue** off `main`: `feat/<issue-number>-short-slug` (or
|
||||||
|
`fix/`). One issue per PR. Reference the issue in the PR description
|
||||||
|
(`Closes #N`).
|
||||||
|
- **Before every commit:** `python -m pytest` (all green), `ruff check .`,
|
||||||
|
`ruff format .`. CI enforces all three.
|
||||||
|
- **Conventional commits** (`feat:`, `fix:`, `test:`, `docs:`, `chore:`) —
|
||||||
|
match the existing history's style: body explains the why.
|
||||||
|
- **Merge only with green CI.** If the supervising session has flagged
|
||||||
|
something on the PR, resolve it before merging.
|
||||||
|
|
||||||
|
## Architecture guardrails (violating these fails review)
|
||||||
|
|
||||||
|
1. **The cardinal rule:** config writes only ever touch `mcpServers` and
|
||||||
|
`_disabledMcpServers`. Every other key is preserved verbatim, in order.
|
||||||
|
This matters extra for `~/.claude.json`, which holds conversation history
|
||||||
|
and project state.
|
||||||
|
2. **Core/GUI split:** all logic in `bcc_core.py` (no GUI imports, unit-
|
||||||
|
testable); `bcc.py` stays a thin PySide6 shell. New logic gets tests in
|
||||||
|
`tests/` — they run without PySide6, keep it that way.
|
||||||
|
3. **No new runtime dependencies** without posting the justification on the
|
||||||
|
issue first. PySide6 is currently the only one.
|
||||||
|
4. **Writes are atomic + backed up** — route any new disk writes through
|
||||||
|
`write_config()`.
|
||||||
|
5. Secrets never appear in diagnostics output or logs — use `redact_args`/
|
||||||
|
`is_secret_key` from bcc_core.
|
||||||
|
|
||||||
|
## Current state (as of this handoff)
|
||||||
|
|
||||||
|
- **92 tests** in `tests/test_core.py`, ruff clean, CI = lint + pytest (py3.10/3.12).
|
||||||
|
- `main` = `ece049c` (PR #16 merged). No unpushed commits.
|
||||||
|
- **Completed items:** #2 (spawn-test, PR #11), #3 (backup restore UI, PR #14),
|
||||||
|
#4 (stale-file protection, PR #15), #1r (secret-in-args warning, PR #16).
|
||||||
|
- **Next item:** #8 — duplicate-name conflict handling. **VERIFY FIRST:** read
|
||||||
|
`paste_json` and `dropEvent` in `bcc.py` to check whether pasting/dropping a
|
||||||
|
server with a name that already exists silently overwrites it; file your
|
||||||
|
findings as a comment on issue #8 before writing any code.
|
||||||
|
- Recent features you should know exist: lenient JSON repair
|
||||||
|
(`repair_json_text`, `parse_pasted_json_verbose`, `repair_config_file` +
|
||||||
|
RepairDialog), ArgsEdit numbered gutter + `split_suspicious_args`,
|
||||||
|
resizable splitters with QSettings persistence, secret masking, Claude Code
|
||||||
|
profile at `~/.claude.json` (settings.json only as "legacy" when it holds
|
||||||
|
parked servers), backup restore UI (RestoreDialog, `list_backups`,
|
||||||
|
`backup_diff`, `restore_backup`), stale-file protection (StaleDialog,
|
||||||
|
`config_mtime`, `external_change_summary`).
|
||||||
|
- GUI can't be smoke-tested in CI; note in each PR whether you ran
|
||||||
|
`python bcc.py` locally and what you checked.
|
||||||
@@ -32,12 +32,17 @@ python bcc.py
|
|||||||
|
|
||||||
- **Auto-discovers installs** — scans the platform's app-support folder for any
|
- **Auto-discovers installs** — scans the platform's app-support folder for any
|
||||||
`Claude*` directory (so `Claude` and `Claude-Work` both show up) **and** finds
|
`Claude*` directory (so `Claude` and `Claude-Work` both show up) **and** finds
|
||||||
Claude Code at `~/.claude/settings.json`. Use **Add config…** to point at any
|
Claude Code's user-scope config at `~/.claude.json` (the file `claude mcp add`
|
||||||
other file manually.
|
writes). Use **Add config…** to point at any other file manually — e.g. a
|
||||||
|
project's `.mcp.json`.
|
||||||
- **Form-based editing** — name, command, args (one per line), env vars, or for
|
- **Form-based editing** — name, command, args (one per line), env vars, or for
|
||||||
remote servers: URL, transport, and headers. No raw JSON.
|
remote servers: URL, transport, and headers. No raw JSON.
|
||||||
- **Paste JSON** — drop in any snippet from an MCP doc (full `mcpServers` block,
|
- **Paste JSON — even broken JSON** — drop in any snippet from an MCP doc (full
|
||||||
inner map, or a single bare server object); it's parsed and merged.
|
`mcpServers` block, inner map, or a single bare server object); it's parsed
|
||||||
|
and merged. The paste box parses as you type and auto-repairs the stuff docs
|
||||||
|
and chat windows love to break: markdown fences, surrounding prose, comments,
|
||||||
|
trailing or missing commas, smart quotes, single quotes, unquoted keys, and
|
||||||
|
unclosed braces — and tells you exactly what it fixed before you commit.
|
||||||
- **Drag & drop** a `.json` file onto the window to import servers from it.
|
- **Drag & drop** a `.json` file onto the window to import servers from it.
|
||||||
- **Copy to ▸** — copy the selected server straight into your *other* install.
|
- **Copy to ▸** — copy the selected server straight into your *other* install.
|
||||||
- **Active / Disabled sections** — servers are shown in two labelled lists with
|
- **Active / Disabled sections** — servers are shown in two labelled lists with
|
||||||
@@ -76,7 +81,9 @@ After saving, **restart that Claude install** for changes to take effect.
|
|||||||
| Windows | `%APPDATA%` |
|
| Windows | `%APPDATA%` |
|
||||||
| Linux | `~/.config` |
|
| Linux | `~/.config` |
|
||||||
|
|
||||||
**Claude Code** (all platforms): `~/.claude/settings.json`
|
**Claude Code** (all platforms): `~/.claude.json` (user scope). If servers are
|
||||||
|
found parked in `~/.claude/settings.json` — where Claude Code ignores them — that
|
||||||
|
file is also listed, marked *legacy*, so you can copy them over.
|
||||||
|
|
||||||
## Files
|
## Files
|
||||||
|
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ else:
|
|||||||
debug=False,
|
debug=False,
|
||||||
bootloader_ignore_signals=False,
|
bootloader_ignore_signals=False,
|
||||||
strip=False,
|
strip=False,
|
||||||
upx=True,
|
upx=False, # UPX can strip icon resources from the PE on Windows
|
||||||
upx_exclude=[],
|
upx_exclude=[],
|
||||||
runtime_tmpdir=None,
|
runtime_tmpdir=None,
|
||||||
console=False,
|
console=False,
|
||||||
|
|||||||
+892
-57
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 113 KiB |
@@ -0,0 +1,57 @@
|
|||||||
|
[project]
|
||||||
|
name = "better-claude-config"
|
||||||
|
version = "1.1.0"
|
||||||
|
description = "Cross-platform GUI for editing the mcpServers block of Claude Desktop and Claude Code configs"
|
||||||
|
readme = "README.md"
|
||||||
|
license = { file = "LICENSE" }
|
||||||
|
requires-python = ">=3.10"
|
||||||
|
dependencies = [
|
||||||
|
"PySide6>=6.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.0",
|
||||||
|
"ruff>=0.6",
|
||||||
|
"pre-commit>=3.5",
|
||||||
|
]
|
||||||
|
build = [
|
||||||
|
"pyinstaller>=6.0",
|
||||||
|
"pillow>=10.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Repository = "https://git.avezzano.io/the_og/better-claude-config"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Tooling
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
addopts = "-q"
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = [
|
||||||
|
"E", # pycodestyle errors
|
||||||
|
"W", # pycodestyle warnings
|
||||||
|
"F", # pyflakes
|
||||||
|
"I", # isort
|
||||||
|
"UP", # pyupgrade
|
||||||
|
"B", # bugbear
|
||||||
|
"SIM", # simplify
|
||||||
|
"RUF", # ruff-specific
|
||||||
|
]
|
||||||
|
ignore = [
|
||||||
|
"E501", # line length handled pragmatically; GUI strings run long
|
||||||
|
"SIM108", # ternary rewrites hurt readability in places
|
||||||
|
"RUF001", # UI strings intentionally use typographic glyphs (−, →, ↳)
|
||||||
|
"RUF002",
|
||||||
|
"RUF003",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"bcc.py" = ["F405", "F403"] # Qt star-import style if ever used
|
||||||
@@ -4,3 +4,7 @@ PySide6>=6.6
|
|||||||
# Build / packaging
|
# Build / packaging
|
||||||
pyinstaller>=6.0
|
pyinstaller>=6.0
|
||||||
pillow>=10.0 # generates icons/app.ico during CI (Windows build)
|
pillow>=10.0 # generates icons/app.ico during CI (Windows build)
|
||||||
|
|
||||||
|
# Test / lint
|
||||||
|
pytest>=8.0
|
||||||
|
ruff>=0.6
|
||||||
|
|||||||
+73
-14
@@ -10,13 +10,11 @@ Requirements:
|
|||||||
pip install pillow # for .ico
|
pip install pillow # for .ico
|
||||||
iconutil # built into macOS; for .icns
|
iconutil # built into macOS; for .icns
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
|
||||||
import platform
|
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
import tempfile
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -32,22 +30,83 @@ def build_ico():
|
|||||||
print("Pillow not installed — skipping .ico generation (pip install pillow)")
|
print("Pillow not installed — skipping .ico generation (pip install pillow)")
|
||||||
return
|
return
|
||||||
|
|
||||||
sizes = [16, 32, 48, 64, 128, 256]
|
import io
|
||||||
imgs = []
|
import struct
|
||||||
|
|
||||||
|
sizes = [16, 24, 32, 48, 64, 128, 256]
|
||||||
|
images: list[tuple[int, object]] = []
|
||||||
for s in sizes:
|
for s in sizes:
|
||||||
p = SRC / f"icon-{s}.png"
|
p = SRC / f"icon-{s}.png"
|
||||||
if not p.exists():
|
if not p.exists():
|
||||||
print(f" Missing {p.name}, skipping")
|
print(f" Missing {p.name}, skipping")
|
||||||
continue
|
continue
|
||||||
imgs.append(Image.open(p).convert("RGBA"))
|
images.append((s, Image.open(p).convert("RGBA")))
|
||||||
|
|
||||||
if not imgs:
|
if not images:
|
||||||
print(" No source PNGs found — cannot build .ico")
|
print(" No source PNGs found — cannot build .ico")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Write the ICO manually so that entries ≤ 128 px use uncompressed BMP DIB
|
||||||
|
# and the 256 px entry uses PNG. Pillow's ICO saver stores all sizes as
|
||||||
|
# PNG-compressed ("Vista icon" format), which PyInstaller's Windows
|
||||||
|
# resource-updater cannot embed — it silently falls back to its default icon.
|
||||||
|
|
||||||
|
def bmp_dib(img: object) -> bytes:
|
||||||
|
"""Return a BMP DIB (BITMAPINFOHEADER + BGRA rows + AND mask)."""
|
||||||
|
w, h = img.size
|
||||||
|
# biHeight is doubled: top half = XOR mask (color), bottom = AND mask
|
||||||
|
hdr = struct.pack(
|
||||||
|
"<IiiHHIIiiII",
|
||||||
|
40, # biSize
|
||||||
|
w,
|
||||||
|
h * 2, # biHeight (doubled per ICO convention)
|
||||||
|
1, # biPlanes
|
||||||
|
32, # biBitCount
|
||||||
|
0, # biCompression (BI_RGB)
|
||||||
|
0, # biSizeImage (0 ok for BI_RGB)
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
pix = img.load()
|
||||||
|
rows = bytearray()
|
||||||
|
for y in range(h - 1, -1, -1): # bottom-up
|
||||||
|
for x in range(w):
|
||||||
|
r, g, b, a = pix[x, y]
|
||||||
|
rows += bytes([b, g, r, a])
|
||||||
|
# AND mask: 1 bit/pixel, rows padded to 32-bit boundary, all 0 (use alpha)
|
||||||
|
mask_row = ((w + 31) // 32) * 4
|
||||||
|
and_mask = bytes(mask_row * h)
|
||||||
|
return hdr + bytes(rows) + and_mask
|
||||||
|
|
||||||
|
def png_bytes(img: object) -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
img.save(buf, format="PNG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
blobs: list[tuple[int, bytes]] = []
|
||||||
|
for s, img in images:
|
||||||
|
blobs.append((s, bmp_dib(img) if s < 256 else png_bytes(img)))
|
||||||
|
|
||||||
|
n = len(blobs)
|
||||||
|
dir_offset = 6 + n * 16 # ICONDIR (6) + n × ICONDIRENTRY (16)
|
||||||
|
|
||||||
|
out = bytearray()
|
||||||
|
out += struct.pack("<HHH", 0, 1, n) # ICONDIR
|
||||||
|
|
||||||
|
cur = dir_offset
|
||||||
|
for s, blob in blobs:
|
||||||
|
w = h = s % 256 # 256 is stored as 0 in the byte field
|
||||||
|
out += struct.pack("<BBBBHHII", w, h, 0, 0, 1, 32, len(blob), cur)
|
||||||
|
cur += len(blob)
|
||||||
|
|
||||||
|
for _, blob in blobs:
|
||||||
|
out += blob
|
||||||
|
|
||||||
dest = OUT / "app.ico"
|
dest = OUT / "app.ico"
|
||||||
imgs[-1].save(dest, format="ICO", append_images=imgs[:-1])
|
dest.write_bytes(out)
|
||||||
print(f" Generated {dest.relative_to(ROOT)} ({dest.stat().st_size // 1024 + 1} KB)")
|
print(f" Generated {dest.relative_to(ROOT)} ({len(out) // 1024 + 1} KB)")
|
||||||
|
|
||||||
|
|
||||||
def build_icns():
|
def build_icns():
|
||||||
@@ -58,15 +117,15 @@ def build_icns():
|
|||||||
iconset = Path(tempfile.mkdtemp()) / "app.iconset"
|
iconset = Path(tempfile.mkdtemp()) / "app.iconset"
|
||||||
iconset.mkdir()
|
iconset.mkdir()
|
||||||
mapping = {
|
mapping = {
|
||||||
"icon_16x16.png": "icon-16.png",
|
"icon_16x16.png": "icon-16.png",
|
||||||
"icon_16x16@2x.png": "icon-32.png",
|
"icon_16x16@2x.png": "icon-32.png",
|
||||||
"icon_32x32.png": "icon-32.png",
|
"icon_32x32.png": "icon-32.png",
|
||||||
"icon_32x32@2x.png": "icon-64.png",
|
"icon_32x32@2x.png": "icon-64.png",
|
||||||
"icon_128x128.png": "icon-128.png",
|
"icon_128x128.png": "icon-128.png",
|
||||||
"icon_128x128@2x.png": "icon-256.png",
|
"icon_128x128@2x.png": "icon-256.png",
|
||||||
"icon_256x256.png": "icon-256.png",
|
"icon_256x256.png": "icon-256.png",
|
||||||
"icon_256x256@2x.png": "icon-512.png",
|
"icon_256x256@2x.png": "icon-512.png",
|
||||||
"icon_512x512.png": "icon-512.png",
|
"icon_512x512.png": "icon-512.png",
|
||||||
"icon_512x512@2x.png": "icon-1024.png",
|
"icon_512x512@2x.png": "icon-1024.png",
|
||||||
}
|
}
|
||||||
for dst_name, src_name in mapping.items():
|
for dst_name, src_name in mapping.items():
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
import json, tempfile, shutil
|
|
||||||
from pathlib import Path
|
|
||||||
import bcc_core as c
|
|
||||||
|
|
||||||
tmp = Path(tempfile.mkdtemp())
|
|
||||||
ok = []
|
|
||||||
|
|
||||||
def check(name, cond):
|
|
||||||
ok.append(cond)
|
|
||||||
print(("PASS" if cond else "FAIL"), "-", name)
|
|
||||||
|
|
||||||
# ---- 1. discovery (monkeypatch the base dir) ----
|
|
||||||
base = tmp / "AppSupport"
|
|
||||||
for d in ("Claude", "Claude-Work", "NotClaude"):
|
|
||||||
(base / d).mkdir(parents=True)
|
|
||||||
(base / "Claude" / c.CONFIG_FILENAME).write_text("{}")
|
|
||||||
# Claude-Work has no config yet; NotClaude shouldn't match
|
|
||||||
c.app_support_base = lambda: base
|
|
||||||
profs = c.discover_profiles()
|
|
||||||
labels = sorted(p.label for p in profs)
|
|
||||||
check("discovers Claude + Claude-Work, not NotClaude",
|
|
||||||
"Claude" in labels and "Claude-Work" in labels and "NotClaude" not in labels)
|
|
||||||
check("flags missing config file", any(p.label=="Claude-Work" and not p.config_exists for p in profs))
|
|
||||||
|
|
||||||
# ---- 2. write preserves OTHER keys + order, only touches mcpServers ----
|
|
||||||
cfgpath = tmp / "real.json"
|
|
||||||
original = {
|
|
||||||
"globalShortcut": "Cmd+Shift+Space",
|
|
||||||
"mcpServers": {"old": {"command": "node", "args": ["x.js"]}},
|
|
||||||
"someOtherTool": {"keep": True},
|
|
||||||
}
|
|
||||||
cfgpath.write_text(json.dumps(original, indent=2))
|
|
||||||
cfg = c.load_config(cfgpath)
|
|
||||||
servers = c.extract_servers(cfg)
|
|
||||||
# add a new one, disable the old one
|
|
||||||
servers.append(c.ServerEntry("brave", {"command": "npx", "args": ["-y", "@x/brave"]}, True))
|
|
||||||
servers[0].enabled = False
|
|
||||||
c.apply_servers(cfg, servers)
|
|
||||||
c.write_config(cfgpath, cfg)
|
|
||||||
written = json.loads(cfgpath.read_text())
|
|
||||||
keys = list(written.keys())
|
|
||||||
check("preserved globalShortcut", written.get("globalShortcut") == "Cmd+Shift+Space")
|
|
||||||
check("preserved someOtherTool", written.get("someOtherTool") == {"keep": True})
|
|
||||||
check("disabled server parked in _disabledMcpServers", "old" in written.get("_disabledMcpServers", {}))
|
|
||||||
check("enabled server in mcpServers", "brave" in written.get("mcpServers", {}))
|
|
||||||
check("old not in active mcpServers", "old" not in written.get("mcpServers", {}))
|
|
||||||
check("key order kept (globalShortcut before mcpServers)", keys.index("globalShortcut") < keys.index("mcpServers"))
|
|
||||||
check("backup created", (cfgpath.parent / c.BACKUP_DIRNAME).is_dir() and any((cfgpath.parent / c.BACKUP_DIRNAME).iterdir()))
|
|
||||||
|
|
||||||
# ---- 3. paste parser, all shapes ----
|
|
||||||
full = '{"mcpServers": {"a": {"command": "node", "args": ["a.js"]}}}'
|
|
||||||
check("parse full config shape", list(c.parse_pasted_json(full)) == ["a"])
|
|
||||||
inner = '{"b": {"command": "uvx", "args": ["mcp-server-git"]}}'
|
|
||||||
check("parse inner block shape", list(c.parse_pasted_json(inner)) == ["b"])
|
|
||||||
bare = '{"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]}'
|
|
||||||
parsed = c.parse_pasted_json(bare)
|
|
||||||
check("parse bare server + suggests name 'filesystem'", "filesystem" in parsed)
|
|
||||||
remote = '{"url": "https://mcp.asana.com/sse"}'
|
|
||||||
check("parse remote, suggests host name", "mcp" in c.parse_pasted_json(remote))
|
|
||||||
try:
|
|
||||||
c.parse_pasted_json('{"junk": 5}')
|
|
||||||
check("rejects junk", False)
|
|
||||||
except ValueError:
|
|
||||||
check("rejects junk", True)
|
|
||||||
|
|
||||||
# ---- 4. validation ----
|
|
||||||
bad = [c.ServerEntry("", {"command": "x"}, True),
|
|
||||||
c.ServerEntry("dup", {"command": "x"}, True),
|
|
||||||
c.ServerEntry("dup", {"command": "x"}, True),
|
|
||||||
c.ServerEntry("r", {"url": ""}, True),
|
|
||||||
c.ServerEntry("nocmd", {"command": ""}, True)]
|
|
||||||
probs = c.validate_servers(bad)
|
|
||||||
check("validation catches empty name", any("empty name" in p for p in probs))
|
|
||||||
check("validation catches duplicate", any("Duplicate" in p for p in probs))
|
|
||||||
check("validation catches missing url", any("no URL" in p for p in probs))
|
|
||||||
check("validation catches missing command", any("no command" in p for p in probs))
|
|
||||||
check("valid set passes clean", c.validate_servers([c.ServerEntry("good", {"command":"node"}, True)]) == [])
|
|
||||||
|
|
||||||
# ---- 5. dependency check (python3 exists; bogusxyz does not) ----
|
|
||||||
r_ok = c.check_dependency({"command": "python3"})
|
|
||||||
check("dep check finds python3", r_ok["status"] == "ok")
|
|
||||||
r_missing = c.check_dependency({"command": "definitely-not-real-binary-xyz"})
|
|
||||||
check("dep check flags missing", r_missing["status"] == "missing")
|
|
||||||
r_remote = c.check_dependency({"url": "https://example.com/mcp"})
|
|
||||||
check("dep check marks remote", r_remote["status"] == "remote")
|
|
||||||
# windows-style wrapper: cmd /c npx ... -> should look past cmd to npx
|
|
||||||
r_wrap = c.check_dependency({"command": "cmd", "args": ["/c", "definitely-not-real-xyz", "foo"]})
|
|
||||||
check("dep check sees through shell wrapper", "definitely-not-real-xyz" in r_wrap["label"])
|
|
||||||
|
|
||||||
print()
|
|
||||||
print(f"{sum(ok)}/{len(ok)} passed")
|
|
||||||
shutil.rmtree(tmp)
|
|
||||||
@@ -0,0 +1,640 @@
|
|||||||
|
"""Pytest port of the original test_core.py script (same 23 behaviours, now
|
||||||
|
proper test functions with tmp_path/monkeypatch fixtures)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import bcc_core as c
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 1. Discovery
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_base(tmp_path, monkeypatch):
|
||||||
|
base = tmp_path / "AppSupport"
|
||||||
|
for d in ("Claude", "Claude-Work", "NotClaude"):
|
||||||
|
(base / d).mkdir(parents=True)
|
||||||
|
(base / "Claude" / c.CONFIG_FILENAME).write_text("{}")
|
||||||
|
monkeypatch.setattr(c, "app_support_base", lambda: base)
|
||||||
|
return base
|
||||||
|
|
||||||
|
|
||||||
|
def test_discovers_claude_dirs_not_others(fake_base):
|
||||||
|
labels = sorted(p.label for p in c.discover_profiles())
|
||||||
|
assert "Claude" in labels
|
||||||
|
assert "Claude-Work" in labels
|
||||||
|
assert "NotClaude" not in labels
|
||||||
|
|
||||||
|
|
||||||
|
def test_flags_missing_config_file(fake_base):
|
||||||
|
profs = c.discover_profiles()
|
||||||
|
assert any(p.label == "Claude-Work" and not p.config_exists for p in profs)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_home(tmp_path, monkeypatch, fake_base):
|
||||||
|
home = tmp_path / "home"
|
||||||
|
(home / ".claude").mkdir(parents=True)
|
||||||
|
monkeypatch.setattr(c.Path, "home", lambda: home)
|
||||||
|
return home
|
||||||
|
|
||||||
|
|
||||||
|
def test_claude_code_uses_dot_claude_json(fake_home):
|
||||||
|
(fake_home / ".claude.json").write_text('{"mcpServers": {"x": {"command": "npx"}}}')
|
||||||
|
profs = c.discover_profiles()
|
||||||
|
cc = [p for p in profs if p.label == "Claude Code"]
|
||||||
|
assert len(cc) == 1
|
||||||
|
assert cc[0].path == fake_home / ".claude.json"
|
||||||
|
assert cc[0].config_exists
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_settings_json_surfaced_only_with_servers(fake_home):
|
||||||
|
# settings.json without mcpServers -> not listed
|
||||||
|
(fake_home / ".claude" / "settings.json").write_text('{"permissions": {}}')
|
||||||
|
assert not any("legacy" in p.label for p in c.discover_profiles())
|
||||||
|
# settings.json WITH parked mcpServers -> listed so the user can migrate
|
||||||
|
(fake_home / ".claude" / "settings.json").write_text(
|
||||||
|
'{"mcpServers": {"old": {"command": "npx"}}}'
|
||||||
|
)
|
||||||
|
assert any("legacy" in p.label for p in c.discover_profiles())
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 2. Write pipeline: preserves other keys + order, only touches mcpServers
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@pytest.fixture
|
||||||
|
def written_config(tmp_path):
|
||||||
|
cfgpath = tmp_path / "real.json"
|
||||||
|
original = {
|
||||||
|
"globalShortcut": "Cmd+Shift+Space",
|
||||||
|
"mcpServers": {"old": {"command": "node", "args": ["x.js"]}},
|
||||||
|
"someOtherTool": {"keep": True},
|
||||||
|
}
|
||||||
|
cfgpath.write_text(json.dumps(original, indent=2))
|
||||||
|
cfg = c.load_config(cfgpath)
|
||||||
|
servers = c.extract_servers(cfg)
|
||||||
|
servers.append(c.ServerEntry("brave", {"command": "npx", "args": ["-y", "@x/brave"]}, True))
|
||||||
|
servers[0].enabled = False
|
||||||
|
c.apply_servers(cfg, servers)
|
||||||
|
c.write_config(cfgpath, cfg)
|
||||||
|
return cfgpath, json.loads(cfgpath.read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def test_preserves_unrelated_keys(written_config):
|
||||||
|
_, written = written_config
|
||||||
|
assert written.get("globalShortcut") == "Cmd+Shift+Space"
|
||||||
|
assert written.get("someOtherTool") == {"keep": True}
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_server_parked(written_config):
|
||||||
|
_, written = written_config
|
||||||
|
assert "old" in written.get(c.DISABLED_KEY, {})
|
||||||
|
assert "old" not in written.get("mcpServers", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_enabled_server_active(written_config):
|
||||||
|
_, written = written_config
|
||||||
|
assert "brave" in written.get("mcpServers", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_key_order_kept(written_config):
|
||||||
|
_, written = written_config
|
||||||
|
keys = list(written.keys())
|
||||||
|
assert keys.index("globalShortcut") < keys.index("mcpServers")
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_created(written_config):
|
||||||
|
cfgpath, _ = written_config
|
||||||
|
bdir = cfgpath.parent / c.BACKUP_DIRNAME
|
||||||
|
assert bdir.is_dir()
|
||||||
|
assert any(bdir.iterdir())
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 3. Paste parser — all accepted shapes
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_parse_full_config_shape():
|
||||||
|
full = '{"mcpServers": {"a": {"command": "node", "args": ["a.js"]}}}'
|
||||||
|
assert list(c.parse_pasted_json(full)) == ["a"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_inner_block_shape():
|
||||||
|
inner = '{"b": {"command": "uvx", "args": ["mcp-server-git"]}}'
|
||||||
|
assert list(c.parse_pasted_json(inner)) == ["b"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_bare_server_suggests_name():
|
||||||
|
bare = '{"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]}'
|
||||||
|
assert "filesystem" in c.parse_pasted_json(bare)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_remote_suggests_host_name():
|
||||||
|
remote = '{"url": "https://mcp.asana.com/sse"}'
|
||||||
|
assert "mcp" in c.parse_pasted_json(remote)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_junk():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
c.parse_pasted_json('{"junk": 5}')
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 4. Validation
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@pytest.fixture
|
||||||
|
def problems():
|
||||||
|
bad = [
|
||||||
|
c.ServerEntry("", {"command": "x"}, True),
|
||||||
|
c.ServerEntry("dup", {"command": "x"}, True),
|
||||||
|
c.ServerEntry("dup", {"command": "x"}, True),
|
||||||
|
c.ServerEntry("r", {"url": ""}, True),
|
||||||
|
c.ServerEntry("nocmd", {"command": ""}, True),
|
||||||
|
]
|
||||||
|
return c.validate_servers(bad)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_catches_empty_name(problems):
|
||||||
|
assert any("empty name" in p for p in problems)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_catches_duplicate(problems):
|
||||||
|
assert any("Duplicate" in p for p in problems)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_catches_missing_url(problems):
|
||||||
|
assert any("no URL" in p for p in problems)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_catches_missing_command(problems):
|
||||||
|
assert any("no command" in p for p in problems)
|
||||||
|
|
||||||
|
|
||||||
|
def test_valid_set_passes_clean():
|
||||||
|
assert c.validate_servers([c.ServerEntry("good", {"command": "node"}, True)]) == []
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 5. Secrets: detection + redaction
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_is_secret_key_positives():
|
||||||
|
for k in (
|
||||||
|
"BRAVE_API_KEY",
|
||||||
|
"BEARER_TOKEN",
|
||||||
|
"password",
|
||||||
|
"GH_TOKEN",
|
||||||
|
"Authorization",
|
||||||
|
"client_secret",
|
||||||
|
"PRIVATE_KEY",
|
||||||
|
"aws_access_key_id",
|
||||||
|
):
|
||||||
|
assert c.is_secret_key(k), k
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_secret_key_negatives():
|
||||||
|
for k in ("JOOMLA_BASE_URL", "PORT", "HOME", "PATH", "debug", "TIMEOUT"):
|
||||||
|
assert not c.is_secret_key(k), k
|
||||||
|
|
||||||
|
|
||||||
|
def test_redact_args_flag_value():
|
||||||
|
assert c.redact_args(["--token", "abc123", "run"]) == ["--token", c.MASK, "run"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_redact_args_inline_flag():
|
||||||
|
assert c.redact_args(["--api-key=abc123"]) == [f"--api-key={c.MASK}"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_redact_args_known_prefix():
|
||||||
|
assert c.redact_args(["ghp_abcdef123456"]) == [c.MASK]
|
||||||
|
|
||||||
|
|
||||||
|
def test_redact_args_leaves_normal_args():
|
||||||
|
args = ["--directory", "/path/to/server", "run", "main.py", "-y"]
|
||||||
|
assert c.redact_args(args) == args
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnostics_redacts_token_args():
|
||||||
|
txt = c.diagnostics_text("t", {"command": "npx", "args": ["--token", "s3cret-value"]})
|
||||||
|
assert "s3cret-value" not in txt
|
||||||
|
assert c.MASK in txt
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 6. Dependency / PATH checking
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_dep_check_finds_python3():
|
||||||
|
assert c.check_dependency({"command": "python3"})["status"] == "ok"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dep_check_flags_missing():
|
||||||
|
assert c.check_dependency({"command": "definitely-not-real-binary-xyz"})["status"] == "missing"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dep_check_marks_remote():
|
||||||
|
assert c.check_dependency({"url": "https://example.com/mcp"})["status"] == "remote"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dep_check_sees_through_shell_wrapper():
|
||||||
|
r = c.check_dependency({"command": "cmd", "args": ["/c", "definitely-not-real-xyz", "foo"]})
|
||||||
|
assert "definitely-not-real-xyz" in r["label"]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 7. Spawn test
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_ok_still_running():
|
||||||
|
# A process that sleeps longer than the timeout → "ok" (server started)
|
||||||
|
r = c.spawn_test(
|
||||||
|
{"command": sys.executable, "args": ["-c", "import time; time.sleep(60)"]}, timeout=0.3
|
||||||
|
)
|
||||||
|
assert r["outcome"] == "ok"
|
||||||
|
assert r["returncode"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_crashed():
|
||||||
|
# A process that exits with a non-zero code immediately.
|
||||||
|
# Timeout is generous (not 0.3s) so a slow CI runner's interpreter startup
|
||||||
|
# can't outlast it and misclassify the crash as "ok" (still running). See #12.
|
||||||
|
r = c.spawn_test(
|
||||||
|
{"command": sys.executable, "args": ["-c", "raise SystemExit(1)"]}, timeout=2.0
|
||||||
|
)
|
||||||
|
assert r["outcome"] == "crashed"
|
||||||
|
assert r["returncode"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_exited_cleanly():
|
||||||
|
# A process that exits 0 before timeout (unusual for a server).
|
||||||
|
# Generous timeout so slow-runner startup can't flip this to "ok". See #12.
|
||||||
|
r = c.spawn_test({"command": sys.executable, "args": ["-c", "pass"]}, timeout=2.0)
|
||||||
|
assert r["outcome"] == "exited"
|
||||||
|
assert r["returncode"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_not_found():
|
||||||
|
r = c.spawn_test({"command": "definitely-not-a-real-binary-xyz"}, timeout=0.3)
|
||||||
|
assert r["outcome"] == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_remote_not_applicable():
|
||||||
|
r = c.spawn_test({"url": "https://example.com/mcp"}, timeout=0.3)
|
||||||
|
assert r["outcome"] == "not_applicable"
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_stderr_captured():
|
||||||
|
# A process that writes to stderr before crashing
|
||||||
|
r = c.spawn_test(
|
||||||
|
{
|
||||||
|
"command": sys.executable,
|
||||||
|
"args": ["-c", "import sys; sys.stderr.write('test-err\\n'); sys.exit(2)"],
|
||||||
|
},
|
||||||
|
timeout=2.0,
|
||||||
|
)
|
||||||
|
assert r["outcome"] == "crashed"
|
||||||
|
assert "test-err" in r["stderr"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_stdin_not_closed():
|
||||||
|
# A process that blocks reading stdin should stay alive (outcome=ok), not exit 0.
|
||||||
|
# This guards against the regression where stdin=DEVNULL sends EOF and a server
|
||||||
|
# that reads stdin exits cleanly, being misclassified as "exited" instead of "ok".
|
||||||
|
r = c.spawn_test(
|
||||||
|
{"command": sys.executable, "args": ["-c", "import sys; sys.stdin.read()"]},
|
||||||
|
timeout=0.3,
|
||||||
|
)
|
||||||
|
assert r["outcome"] == "ok", f"expected ok (blocking on stdin), got {r['outcome']}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_test_large_stderr_does_not_deadlock():
|
||||||
|
# A process that writes >4 KB (pipe buffer territory) to stderr then exits non-zero.
|
||||||
|
# Without EOF-draining, the subprocess blocks on a full pipe and is wrongly
|
||||||
|
# classified as "ok" (still running) instead of "crashed".
|
||||||
|
script = "import sys; sys.stderr.write('x' * 65536); sys.stderr.flush(); sys.exit(3)"
|
||||||
|
r = c.spawn_test(
|
||||||
|
{"command": sys.executable, "args": ["-c", script]},
|
||||||
|
timeout=2.0,
|
||||||
|
)
|
||||||
|
assert r["outcome"] == "crashed", f"expected crashed, got {r['outcome']}"
|
||||||
|
assert r["returncode"] == 3
|
||||||
|
# stderr is capped, not the full 64 KB
|
||||||
|
assert len(r["stderr"]) <= c._STDERR_CAP
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 8. Backup restore
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
@pytest.fixture
|
||||||
|
def config_with_backup(tmp_path):
|
||||||
|
"""A config file with two backups already present."""
|
||||||
|
cfgpath = tmp_path / "claude_desktop_config.json"
|
||||||
|
original = {
|
||||||
|
"globalShortcut": "Cmd+Shift+Space",
|
||||||
|
"mcpServers": {"server-v1": {"command": "node", "args": ["v1.js"]}},
|
||||||
|
}
|
||||||
|
cfgpath.write_text(json.dumps(original, indent=2))
|
||||||
|
|
||||||
|
# Create first backup (v1 state) by writing a new version
|
||||||
|
cfg = c.load_config(cfgpath)
|
||||||
|
servers = c.extract_servers(cfg)
|
||||||
|
servers[0] = c.ServerEntry("server-v2", {"command": "node", "args": ["v2.js"]}, True)
|
||||||
|
c.apply_servers(cfg, servers)
|
||||||
|
c.write_config(cfgpath, cfg)
|
||||||
|
|
||||||
|
return cfgpath
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_backups_returns_newest_first(config_with_backup):
|
||||||
|
backups = c.list_backups(config_with_backup)
|
||||||
|
assert len(backups) >= 1
|
||||||
|
# Sorted newest-first means descending lexicographic order on timestamps
|
||||||
|
names = [b.name for b in backups]
|
||||||
|
assert names == sorted(names, reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_backups_empty_when_no_bdir(tmp_path):
|
||||||
|
cfgpath = tmp_path / "claude_desktop_config.json"
|
||||||
|
cfgpath.write_text("{}")
|
||||||
|
assert c.list_backups(cfgpath) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_label_parses_timestamp(config_with_backup):
|
||||||
|
backup = c.list_backups(config_with_backup)[0]
|
||||||
|
label = c.backup_label(backup)
|
||||||
|
# label should look like "2026-07-02 00:41:24" (date + time, separated by two spaces)
|
||||||
|
assert "-" in label and ":" in label
|
||||||
|
assert len(label) == 20 # "YYYY-MM-DD HH:MM:SS" = 10 + 2 + 8
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_diff_shows_server_change(config_with_backup):
|
||||||
|
backup = c.list_backups(config_with_backup)[0]
|
||||||
|
diff = c.backup_diff(config_with_backup, backup)
|
||||||
|
# The diff should show the transition back to v1 servers
|
||||||
|
assert "server-v1" in diff or "server-v2" in diff
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_diff_no_diff_when_identical(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
content = {"mcpServers": {"s": {"command": "node"}}}
|
||||||
|
cfgpath.write_text(json.dumps(content, indent=2))
|
||||||
|
bdir = cfgpath.parent / c.BACKUP_DIRNAME
|
||||||
|
bdir.mkdir(exist_ok=True)
|
||||||
|
import time as _time
|
||||||
|
|
||||||
|
stamp = _time.strftime("%Y%m%d-%H%M%S")
|
||||||
|
backup_path = bdir / f"cfg.{stamp}.json"
|
||||||
|
backup_path.write_text(json.dumps(content, indent=2))
|
||||||
|
diff = c.backup_diff(cfgpath, backup_path)
|
||||||
|
assert "(no differences" in diff
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_backup_replaces_servers(config_with_backup):
|
||||||
|
# Get the v1 backup (only backup we have)
|
||||||
|
backups = c.list_backups(config_with_backup)
|
||||||
|
assert len(backups) >= 1
|
||||||
|
v1_backup = backups[0]
|
||||||
|
|
||||||
|
# Current file has server-v2; restore should bring back server-v1
|
||||||
|
c.restore_backup(config_with_backup, v1_backup)
|
||||||
|
|
||||||
|
restored = json.loads(config_with_backup.read_text())
|
||||||
|
assert "server-v1" in restored.get("mcpServers", {})
|
||||||
|
assert "server-v2" not in restored.get("mcpServers", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_preserves_non_server_keys(config_with_backup):
|
||||||
|
backups = c.list_backups(config_with_backup)
|
||||||
|
c.restore_backup(config_with_backup, backups[0])
|
||||||
|
|
||||||
|
restored = json.loads(config_with_backup.read_text())
|
||||||
|
# Non-server key must survive
|
||||||
|
assert restored.get("globalShortcut") == "Cmd+Shift+Space"
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_creates_pre_restore_backup(config_with_backup):
|
||||||
|
before_count = len(c.list_backups(config_with_backup))
|
||||||
|
backups = c.list_backups(config_with_backup)
|
||||||
|
c.restore_backup(config_with_backup, backups[0])
|
||||||
|
after_count = len(c.list_backups(config_with_backup))
|
||||||
|
# restore_backup goes through write_config which makes a backup first
|
||||||
|
assert after_count == before_count + 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_with_current_cfg_passed(config_with_backup):
|
||||||
|
# When current_cfg is passed in (the GUI's in-memory config), it should be
|
||||||
|
# used instead of re-reading from disk.
|
||||||
|
backups = c.list_backups(config_with_backup)
|
||||||
|
# Simulate the GUI passing a repaired in-memory version
|
||||||
|
in_memory_cfg = {
|
||||||
|
"globalShortcut": "Cmd+Shift+Space",
|
||||||
|
"extraKey": "preserved",
|
||||||
|
"mcpServers": {"server-v2": {"command": "node", "args": ["v2.js"]}},
|
||||||
|
}
|
||||||
|
c.restore_backup(config_with_backup, backups[0], current_cfg=in_memory_cfg)
|
||||||
|
restored = json.loads(config_with_backup.read_text())
|
||||||
|
assert restored.get("extraKey") == "preserved"
|
||||||
|
assert "server-v1" in restored.get("mcpServers", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_diff_masks_secrets(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
current = {
|
||||||
|
"mcpServers": {
|
||||||
|
"s": {
|
||||||
|
"command": "node",
|
||||||
|
"args": ["--token", "super-secret"],
|
||||||
|
"env": {"API_KEY": "my-api-key-value"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfgpath.write_text(json.dumps(current, indent=2))
|
||||||
|
bdir = cfgpath.parent / c.BACKUP_DIRNAME
|
||||||
|
bdir.mkdir()
|
||||||
|
import time as _t
|
||||||
|
|
||||||
|
bp = bdir / f"cfg.{_t.strftime('%Y%m%d-%H%M%S')}.json"
|
||||||
|
bp.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"s2": {
|
||||||
|
"command": "python",
|
||||||
|
"args": ["--api-key", "another-secret"],
|
||||||
|
"env": {"SECRET_KEY": "backup-secret-value"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
indent=2,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
diff = c.backup_diff(cfgpath, bp)
|
||||||
|
# Raw secret values must not appear in the diff
|
||||||
|
assert "super-secret" not in diff
|
||||||
|
assert "my-api-key-value" not in diff
|
||||||
|
assert "another-secret" not in diff
|
||||||
|
assert "backup-secret-value" not in diff
|
||||||
|
# The mask placeholder must appear (secrets were present in both sides)
|
||||||
|
assert c.MASK in diff
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_backup_restores_disabled_servers(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
original = {
|
||||||
|
"mcpServers": {"active": {"command": "node"}},
|
||||||
|
c.DISABLED_KEY: {"parked": {"command": "python"}},
|
||||||
|
}
|
||||||
|
cfgpath.write_text(json.dumps(original, indent=2))
|
||||||
|
|
||||||
|
# Overwrite: add new server, drop the disabled one
|
||||||
|
cfg = c.load_config(cfgpath)
|
||||||
|
servers = c.extract_servers(cfg)
|
||||||
|
servers = [s for s in servers if s.name != "parked"]
|
||||||
|
servers.append(c.ServerEntry("newcomer", {"command": "uvx"}, True))
|
||||||
|
c.apply_servers(cfg, servers)
|
||||||
|
c.write_config(cfgpath, cfg)
|
||||||
|
|
||||||
|
# Restore from the v1 backup
|
||||||
|
backups = c.list_backups(cfgpath)
|
||||||
|
c.restore_backup(cfgpath, backups[0])
|
||||||
|
restored = json.loads(cfgpath.read_text())
|
||||||
|
|
||||||
|
assert "parked" in restored.get(c.DISABLED_KEY, {})
|
||||||
|
assert "active" in restored.get("mcpServers", {})
|
||||||
|
assert "newcomer" not in restored.get("mcpServers", {})
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 9 — Stale-file protection
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_mtime_returns_float_for_existing_file(tmp_path):
|
||||||
|
f = tmp_path / "cfg.json"
|
||||||
|
f.write_text("{}")
|
||||||
|
assert isinstance(c.config_mtime(f), float)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_mtime_returns_none_for_missing_file(tmp_path):
|
||||||
|
assert c.config_mtime(tmp_path / "nonexistent.json") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_external_change_summary_detects_non_server_key_change(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
original = {"numStartups": 1, "mcpServers": {"s": {"command": "node"}}}
|
||||||
|
cfgpath.write_text(json.dumps({"numStartups": 2, "mcpServers": {"s": {"command": "node"}}}))
|
||||||
|
changed_keys, server_diff = c.external_change_summary(original, cfgpath)
|
||||||
|
assert "numStartups" in changed_keys
|
||||||
|
assert server_diff == "" # server sections unchanged
|
||||||
|
|
||||||
|
|
||||||
|
def test_external_change_summary_detects_server_section_change(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
original = {"mcpServers": {"s1": {"command": "node"}}}
|
||||||
|
cfgpath.write_text(json.dumps({"mcpServers": {"s2": {"command": "python"}}}))
|
||||||
|
changed_keys, server_diff = c.external_change_summary(original, cfgpath)
|
||||||
|
assert "mcpServers" in changed_keys
|
||||||
|
assert "s1" in server_diff or "s2" in server_diff
|
||||||
|
|
||||||
|
|
||||||
|
def test_external_change_summary_server_diff_masks_secrets(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
original = {"mcpServers": {"a": {"command": "node", "env": {"SECRET_KEY": "s3cr3t"}}}}
|
||||||
|
# command changes (visible in diff) AND secret value changes (both sides masked →
|
||||||
|
# MASK appears in context lines, raw secret never appears)
|
||||||
|
cfgpath.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{"mcpServers": {"a": {"command": "python", "env": {"SECRET_KEY": "n3w_s3cr3t"}}}}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
changed_keys, server_diff = c.external_change_summary(original, cfgpath)
|
||||||
|
assert "mcpServers" in changed_keys
|
||||||
|
assert "s3cr3t" not in server_diff
|
||||||
|
assert "n3w_s3cr3t" not in server_diff
|
||||||
|
assert c.MASK in server_diff # appears in context for the masked env value
|
||||||
|
|
||||||
|
|
||||||
|
def test_external_change_summary_empty_when_unchanged(tmp_path):
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
cfg = {"mcpServers": {"s": {"command": "node"}}}
|
||||||
|
cfgpath.write_text(json.dumps(cfg))
|
||||||
|
changed_keys, server_diff = c.external_change_summary(cfg, cfgpath)
|
||||||
|
assert changed_keys == []
|
||||||
|
assert server_diff == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_and_reapply_preserves_both_edits(tmp_path):
|
||||||
|
"""AC test: external non-server change + in-memory server edit both survive merge."""
|
||||||
|
cfgpath = tmp_path / "cfg.json"
|
||||||
|
original = {"numStartups": 1, "mcpServers": {"s1": {"command": "node"}}}
|
||||||
|
cfgpath.write_text(json.dumps(original, indent=2))
|
||||||
|
|
||||||
|
user_servers = [c.ServerEntry("s2", {"command": "python"}, True)]
|
||||||
|
|
||||||
|
# External process bumps numStartups without touching servers
|
||||||
|
disk_changed = dict(original)
|
||||||
|
disk_changed["numStartups"] = 42
|
||||||
|
cfgpath.write_text(json.dumps(disk_changed, indent=2))
|
||||||
|
|
||||||
|
# Merge: load fresh from disk, apply user's server edits, write back
|
||||||
|
fresh = c.load_config(cfgpath)
|
||||||
|
c.apply_servers(fresh, user_servers)
|
||||||
|
c.write_config(cfgpath, fresh)
|
||||||
|
|
||||||
|
result = json.loads(cfgpath.read_text())
|
||||||
|
assert result["numStartups"] == 42 # external change preserved
|
||||||
|
assert "s2" in result["mcpServers"] # user's server edit preserved
|
||||||
|
assert "s1" not in result["mcpServers"] # old server replaced
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# 10 — Secret-in-args warning
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_embedded_url_creds():
|
||||||
|
"""AC case: postgres://user:pass@host triggers a warning."""
|
||||||
|
data = {"args": ["--connection", "postgres://user:pass@host/db"]}
|
||||||
|
assert c.args_secret_warning(data) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_token_prefix_positional():
|
||||||
|
"""A bare ghp_… token as a positional arg triggers a warning."""
|
||||||
|
data = {"args": ["ghp_abc123def456"]}
|
||||||
|
assert c.args_secret_warning(data) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_secret_flag_value_pair():
|
||||||
|
"""Value following a secret-named flag triggers a warning."""
|
||||||
|
data = {"args": ["--token", "supersecret"]}
|
||||||
|
assert c.args_secret_warning(data) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_benign_url_no_password():
|
||||||
|
"""https:// URL without user:pass should NOT warn."""
|
||||||
|
data = {"args": ["--endpoint", "https://mcp.example.com/sse"]}
|
||||||
|
assert c.args_secret_warning(data) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_user_at_host_no_password():
|
||||||
|
"""ssh://user@host without a password should NOT warn."""
|
||||||
|
data = {"args": ["ssh://git@github.com"]}
|
||||||
|
assert c.args_secret_warning(data) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_inline_flag_value_skipped():
|
||||||
|
"""--flag=value inline pairs are self-documenting and should NOT warn."""
|
||||||
|
data = {"args": ["--api-key=sk-abc123"]}
|
||||||
|
assert c.args_secret_warning(data) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_env_not_triggered():
|
||||||
|
"""Secrets in env (not args) must not trigger args warning, even with benign args present."""
|
||||||
|
data = {"args": ["--verbose"], "env": {"DATABASE_URL": "postgres://user:pass@host/db"}}
|
||||||
|
assert c.args_secret_warning(data) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_args_secret_warning_empty():
|
||||||
|
assert c.args_secret_warning({}) is None
|
||||||
|
assert c.args_secret_warning({"args": []}) is None
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
"""Tests for the lenient JSON repair pipeline (repair_json_text +
|
||||||
|
parse_pasted_json_verbose). Every case here is a shape people actually paste
|
||||||
|
from MCP docs, blog posts, and chat windows."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import bcc_core as c
|
||||||
|
|
||||||
|
GOOD = {"command": "npx", "args": ["-y", "@x/brave"]}
|
||||||
|
|
||||||
|
|
||||||
|
def assert_brave(servers):
|
||||||
|
assert "brave" in servers
|
||||||
|
assert servers["brave"]["command"] == "npx"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Valid JSON passes through untouched
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_strict_json_no_notes():
|
||||||
|
servers, notes = c.parse_pasted_json_verbose('{"brave": {"command": "npx", "args": []}}')
|
||||||
|
assert_brave(servers)
|
||||||
|
assert notes == []
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Markdown / prose wrappers
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_markdown_fence():
|
||||||
|
text = 'Add this to your config:\n```json\n{"brave": {"command": "npx"}}\n```\nThen restart.'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("fence" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fence_without_language_tag():
|
||||||
|
text = '```\n{"brave": {"command": "npx"}}\n```'
|
||||||
|
servers, _ = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
|
||||||
|
|
||||||
|
def test_prose_around_bare_json():
|
||||||
|
text = 'Paste the following: {"brave": {"command": "npx"}} and restart Claude.'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("before" in n or "after" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Comments
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_line_comments():
|
||||||
|
text = '{\n // the search server\n "brave": {"command": "npx"}\n}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("//" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_block_comments():
|
||||||
|
text = '{ /* config */ "brave": {"command": "npx"} }'
|
||||||
|
servers, _ = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
|
||||||
|
|
||||||
|
def test_url_with_double_slash_is_not_a_comment():
|
||||||
|
text = '{"remote": {"url": "https://mcp.example.com/sse"}}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert servers["remote"]["url"] == "https://mcp.example.com/sse"
|
||||||
|
assert notes == []
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Commas
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_trailing_comma_object():
|
||||||
|
text = '{"brave": {"command": "npx", "args": ["-y"],},}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("trailing" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_comma_between_servers():
|
||||||
|
text = '{"brave": {"command": "npx"}\n"git": {"command": "uvx"}}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert "brave" in servers and "git" in servers
|
||||||
|
assert any("missing comma" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_comma_between_string_fields():
|
||||||
|
text = '{"brave": {"command": "npx"\n"args": ["-y"]}}'
|
||||||
|
servers, _ = c.parse_pasted_json_verbose(text)
|
||||||
|
assert servers["brave"]["args"] == ["-y"]
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Quotes
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_smart_quotes():
|
||||||
|
text = "{“brave”: {“command”: “npx”}}"
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("smart quotes" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_quotes():
|
||||||
|
text = "{'brave': {'command': 'npx', 'args': ['-y']}}"
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("single-quoted" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_quotes_with_inner_double():
|
||||||
|
text = """{'brave': {'command': 'npx', 'env': {'NOTE': 'say "hi"'}}}"""
|
||||||
|
servers, _ = c.parse_pasted_json_verbose(text)
|
||||||
|
assert servers["brave"]["env"]["NOTE"] == 'say "hi"'
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# JS-style laxness
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_unquoted_keys():
|
||||||
|
text = '{brave: {command: "npx", args: ["-y"]}}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("bare object keys" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_python_literals():
|
||||||
|
text = '{"brave": {"command": "npx", "enabled": True, "extra": None}}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert servers["brave"]["enabled"] is True
|
||||||
|
assert servers["brave"]["extra"] is None
|
||||||
|
assert any("literals" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Structure damage
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_braceless_fragment():
|
||||||
|
text = '"brave": {"command": "npx", "args": ["-y"]}'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("wrapped" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_closing_braces():
|
||||||
|
text = '{"mcpServers": {"brave": {"command": "npx", "args": ["-y"]'
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert any("unclosed" in n for n in notes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_kitchen_sink():
|
||||||
|
# fence + comment + single quotes + unquoted key + trailing comma + prose
|
||||||
|
text = (
|
||||||
|
"Here's the config you need:\n"
|
||||||
|
"```json\n"
|
||||||
|
"{\n"
|
||||||
|
" // brave search\n"
|
||||||
|
" brave: {\n"
|
||||||
|
" 'command': 'npx',\n"
|
||||||
|
" 'args': ['-y', '@x/brave',],\n"
|
||||||
|
" },\n"
|
||||||
|
"}\n"
|
||||||
|
"```\n"
|
||||||
|
)
|
||||||
|
servers, notes = c.parse_pasted_json_verbose(text)
|
||||||
|
assert_brave(servers)
|
||||||
|
assert servers["brave"]["args"] == ["-y", "@x/brave"]
|
||||||
|
assert len(notes) >= 4
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Suspicious-args detection (several argv tokens typed on one line)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_split_flag_and_value_on_one_line():
|
||||||
|
fixed, notes = c.split_suspicious_args(["--directory /path/to/server", "run", "main.py"])
|
||||||
|
assert fixed == ["--directory", "/path/to/server", "run", "main.py"]
|
||||||
|
assert len(notes) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_full_option_string():
|
||||||
|
fixed, notes = c.split_suspicious_args(["-y @pkg/server --port 8080"])
|
||||||
|
assert fixed == ["-y", "@pkg/server", "--port", "8080"]
|
||||||
|
assert notes
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_respects_quotes():
|
||||||
|
fixed, _ = c.split_suspicious_args(['--name "My Server"'])
|
||||||
|
assert fixed == ["--name", "My Server"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_leaves_legit_spaces_alone():
|
||||||
|
args = ["/Users/me/My Documents", "hello world", "run"]
|
||||||
|
fixed, notes = c.split_suspicious_args(args)
|
||||||
|
assert fixed == args
|
||||||
|
assert notes == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_leaves_clean_args_alone():
|
||||||
|
args = ["--directory", "/path/to/server", "run", "main.py"]
|
||||||
|
fixed, notes = c.split_suspicious_args(args)
|
||||||
|
assert fixed == args
|
||||||
|
assert notes == []
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Config-file repair (load-time)
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_repair_config_file_fixes_and_reports(tmp_path):
|
||||||
|
p = tmp_path / "claude_desktop_config.json"
|
||||||
|
p.write_text(
|
||||||
|
'{\n "globalShortcut": "Cmd+Space",\n'
|
||||||
|
" // my servers\n"
|
||||||
|
' "mcpServers": {\n'
|
||||||
|
' "brave": {"command": "npx", "args": ["-y"],},\n'
|
||||||
|
" },\n}"
|
||||||
|
)
|
||||||
|
cfg, notes, preview = c.repair_config_file(p)
|
||||||
|
assert cfg["mcpServers"]["brave"]["command"] == "npx"
|
||||||
|
assert cfg["globalShortcut"] == "Cmd+Space" # unrelated keys survive
|
||||||
|
assert any("comment" in n for n in notes)
|
||||||
|
assert any("trailing" in n for n in notes)
|
||||||
|
assert json.loads(preview) == cfg
|
||||||
|
# nothing was written to disk
|
||||||
|
assert "//" in p.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
def test_repair_config_file_hopeless_raises(tmp_path):
|
||||||
|
p = tmp_path / "claude_desktop_config.json"
|
||||||
|
p.write_text("total nonsense, no braces at all")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
c.repair_config_file(p)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Still fails cleanly on hopeless input
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def test_hopeless_input_raises_value_error():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
c.parse_pasted_json_verbose("this is just prose with no json at all")
|
||||||
|
|
||||||
|
|
||||||
|
def test_junk_object_still_rejected():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
c.parse_pasted_json_verbose('{"junk": 5}')
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_raises():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
c.parse_pasted_json_verbose(" ")
|
||||||
Reference in New Issue
Block a user