mcp_config.py¶
clew/mcp_config.py
Locate, merge and write the MCP client configs `clew init` registers in.
_classify
str clew.mcp_config._classify(bool file_existed, dict[str, Any]|None existing, dict[str, Any] entry)
Classify what writing this entry would do.
Source · 11 lines
def _classify(file_existed: bool, existing: dict[str, Any] | None, entry: dict[str, Any]) -> str:
"""@brief Decide the merge action for a target file.
@return `create`, `add`, `unchanged` or `update`.
@version 1
"""
if existing is None:
return INIT_ACTION_CREATE if not file_existed else INIT_ACTION_ADD
return INIT_ACTION_UNCHANGED if existing == entry else INIT_ACTION_UPDATE
Activity · 3 steps
Flows
_entry_diff
str clew.mcp_config._entry_diff(dict[str, Any]|None existing, dict[str, Any] entry)
Unified diff between the existing entry and the proposed one.
Source · 18 lines
def _entry_diff(existing: dict[str, Any] | None, entry: dict[str, Any]) -> str:
"""Rendered over pretty-printed JSON rather than the raw file text: the point
is to show the user WHAT would change about this one server, not where the
bytes moved.
@brief Diff an existing server entry against the proposed one.
@return Unified diff text ("" when the entry is new or identical).
@version 1
"""
if existing is None or existing == entry:
return ""
before = json.dumps(existing, indent=2, sort_keys=True).splitlines()
after = json.dumps(entry, indent=2, sort_keys=True).splitlines()
return "\n".join(
difflib.unified_diff(before, after, fromfile="current", tofile="proposed", lineterm="")
)
Activity · 5 steps
Flows
_indent_of
int | str clew.mcp_config._indent_of(str raw)
Indentation to re-serialise with, taken from the file itself.
Source · 13 lines
def _indent_of(raw: str) -> int | str:
"""Reuses whatever the file already used, so registering a server does not
reformat a config the user maintains by hand (and does not produce a diff
that is 90% whitespace).
@brief Detect a config file's existing indentation.
@return The detected indent string, or DEFAULT_INDENT.
@version 1
"""
match = re.search(r'^([ \t]+)"', raw, re.MULTILINE)
return match.group(1) if match else DEFAULT_INDENT
Activity · 2 steps
Flows
_locate_script
tuple[Path | None, bool] clew.mcp_config._locate_script(Any which, Path bindir)
Locate the MCP server console script.
Source · 17 lines
def _locate_script(which: Any, bindir: Path) -> tuple[Path | None, bool]:
"""PATH first, because that is what a `pip install clew` user has.
The interpreter's own `bin/` second, which is the developer-checkout case:
running `.venv/bin/clew init` without activating the venv means the
script is real and usable but invisible to `which`.
@brief Find the server console script.
@return (script path or None, found-on-PATH flag).
@version 1
"""
found = which(CONSOLE_SCRIPT)
if found:
return Path(found), True
candidate = bindir / CONSOLE_SCRIPT
return (candidate, False) if candidate.is_file() else (None, False)
Activity · 5 steps
Flows
_path_or_name
CommandResolution clew.mcp_config._path_or_name(Path path, bool on_path)
Choose between the bare console-script name and an absolute path.
Source · 15 lines
def _path_or_name(path: Path, on_path: bool) -> CommandResolution:
"""@brief Prefer the PATH-resolvable name; fall back to an absolute path.
@return CommandResolution for a script outside the target repo.
@version 1
"""
if on_path:
return CommandResolution(CONSOLE_SCRIPT, f"console script on PATH ({path})", True)
return CommandResolution(
str(path),
f"absolute path to {path} — not on PATH, so the bare name would not launch",
False,
)
Activity · 3 steps
Flows
_repo_relative
str | None clew.mcp_config._repo_relative(Path path, Path repo_root)
Express a path relative to a repo root, when it is inside it.
Source · 12 lines
def _repo_relative(path: Path, repo_root: Path) -> str | None:
"""@brief Make a path repo-relative, or report that it is not inside.
@return Relative POSIX path or None.
@version 1
"""
try:
return path.resolve().relative_to(repo_root.resolve()).as_posix()
except ValueError:
return None
Activity · 4 steps
Flows
apply_plan
Path clew.mcp_config.apply_plan(WritePlan plan)
Write a planned edit to disk atomically, keeping a backup.
Source · 41 lines
def apply_plan(plan: WritePlan) -> Path:
"""Written to a sibling temp file and `os.replace`d onto the target, the same
swap the build pipeline uses. A config file is read by a long-running client;
a partial write would leave it holding a truncated document, and on the
user-scope file that is the user's whole Claude Code state.
ATOMICITY IS NOT ENOUGH, WHICH IS WHY THERE IS A BACKUP. `os.replace` only
guarantees the target is never half-written; it guarantees nothing about the
CONTENT being right. The user-scope target is `~/.claude.json` — on this
machine ~144KB of hand-accumulated Claude Code state that no tool can
regenerate — and it reaches here having survived a full
`json.loads` -> mutate -> `json.dumps` round-trip. A defect anywhere in that
round-trip destroys the file perfectly atomically. This is the single most
consequential write in the whole tool, so it keeps a copy.
ORDERING IS DELIBERATE: the backup is written FIRST and a failure to write it
aborts before the target is touched at all. Backing up after the swap, or
treating a failed backup as a warning, would leave exactly the case the backup
exists for uncovered.
Nothing to back up on a fresh file — no target, no loss — and in that case a
stray `.bak` would be misleading rather than helpful.
TAKES A `WritePlan`, not a `MergePlan`. The second `init` target is a delimited
block in the user's CLAUDE.md, which is a hand-curated prose file rather than a
JSON document — every sentence above applies to it verbatim, so it gets this
writer rather than a parallel one that could drift on the backup ordering.
@brief Apply a write plan atomically, preserving a backup of any existing file.
@return The path that was written.
@version 3
"""
plan.path.parent.mkdir(parents=True, exist_ok=True)
if plan.path.is_file():
backup = plan.path.with_name(plan.path.name + ".clew.bak")
backup.write_bytes(plan.path.read_bytes())
logger.info("init: previous %s saved as %s", plan.path.name, backup.name)
tmp = plan.path.with_name(plan.path.name + ".clew.tmp")
tmp.write_text(plan.text, encoding="utf-8")
os.replace(tmp, plan.path)
return plan.path1 more lines, not shown
Activity · 9 steps
Requirements
REQ-DDB-CLI-002 REQ-DDB-MCP-001
Flows
claude_state_dir
Path clew.mcp_config.claude_state_dir()
Directory Claude Code keeps its per-user state in.
Source · 17 lines
def claude_state_dir() -> Path:
"""`CLAUDE_CONFIG_DIR` relocates the WHOLE config directory, and when it is
set the state directory is that directory itself — not a `.claude` child of
it. Verified by probing a real install: with the variable pointed at a scratch
path, Claude Code created `<scratch>/.claude.json` and `<scratch>/backups/`
directly.
@brief Resolve Claude Code's per-user state directory.
@return Path to the state directory (not created by this call).
@version 1
"""
override = os.environ.get(CLAUDE_CONFIG_DIR_ENV)
if override:
return Path(override).expanduser()
return Path.home() / CLAUDE_STATE_DIR_NAME
Activity · 4 steps
Requirements
Flows
config_path
Path clew.mcp_config.config_path(str scope, Path repo_root)
The config file a given scope writes to.
Source · 11 lines
def config_path(scope: str, repo_root: Path) -> Path:
"""@brief Resolve the config file for a registration scope.
@return Path to `<repo>/.mcp.json` or the user-scope `.claude.json`.
@version 1
"""
if scope == INIT_SCOPE_REPO:
return repo_root / REPO_CONFIG_NAME
return global_config_path()
Activity · 3 steps
Requirements
Flows
global_config_available
bool clew.mcp_config.global_config_available()
Whether a user-level Claude Code config can be written with confidence.
Source · 20 lines
def global_config_available() -> bool:
"""An explicitly set `CLAUDE_CONFIG_DIR` IS the evidence and short-circuits
the disk check: the user has DECLARED where their config lives, and refusing
to honour a declaration in favour of a built-in guess is exactly the
hardcoded-only assumption this project forbids.
Otherwise the default location has to prove itself, because global scope
writes into a home directory: either the config file is already there, or
Claude Code's state directory is.
@brief Whether the user-scope config location is declared or evidenced.
@return True when the location is declared or evidenced.
@version 2
"""
if os.environ.get(CLAUDE_CONFIG_DIR_ENV):
return True
config, state = global_config_evidence()
return config.is_file() or state.is_dir()
Activity · 4 steps
Requirements
Flows
global_config_evidence
tuple[Path, Path] clew.mcp_config.global_config_evidence()
The two paths that evidence a Claude Code install for this user.
Called by _check_client_config, global_config_available
Source · 16 lines
def global_config_evidence() -> tuple[Path, Path]:
"""Global scope writes into the user's home directory, so it demands evidence
that the client actually lives there before creating a file. Either artefact
is enough: the config exists (Claude Code has run) or the state directory
exists (it is installed and has at least started).
Returned as a pair rather than a bool so a refusal can NAME what was looked
for — writing a config to an invented path is the failure this guards.
@brief Report the paths that would evidence a user-level Claude Code config.
@return (config file path, state directory path).
@version 1
"""
return global_config_path(), claude_state_dir()
Activity · 1 steps
Requirements
Flows
global_config_path
Path clew.mcp_config.global_config_path()
The user-scoped Claude Code config file.
Source · 14 lines
def global_config_path() -> Path:
"""`$CLAUDE_CONFIG_DIR/.claude.json`, else `~/.claude.json`. NOT under
`~/.claude/` — the state directory and the config file are siblings in the
default layout, which is the detail an assumption would get wrong.
@brief Resolve the user-scope MCP config path.
@return Path to the user-scope config file.
@version 1
"""
override = os.environ.get(CLAUDE_CONFIG_DIR_ENV)
base = Path(override).expanduser() if override else Path.home()
return base / CLAUDE_USER_CONFIG_NAME
Activity · 3 steps
Requirements
Flows
load_document
tuple[dict[str, Any], str] clew.mcp_config.load_document(Path path)
Read a config file into a document plus its original text.
Source · 21 lines
def load_document(path: Path) -> tuple[dict[str, Any], str]:
"""Absent is not an error — it is the `create` case. Present-but-unparseable
IS an error, and it is raised before anything is written so the user's file
survives intact.
@brief Load a config document, refusing a malformed one.
@return (document, raw text).
@version 1
"""
if not path.exists():
return {}, ""
raw = path.read_text(encoding="utf-8")
try:
document = json.loads(raw)
except ValueError as exc:
raise ConfigError(f"{path} is not valid JSON ({exc}) — refusing to touch it") from exc
if not isinstance(document, dict):
raise ConfigError(f"{path} does not hold a JSON object — refusing to touch it")
return document, raw
Activity · 10 steps
Requirements
Flows
plan_merge
MergePlan clew.mcp_config.plan_merge(Path path, dict[str, Any] entry, str name=MCP_ENTRY_NAME)
Plan the merge of this server's entry into a config file.
Source · 35 lines
def plan_merge(path: Path, entry: dict[str, Any], name: str = MCP_ENTRY_NAME) -> MergePlan:
"""Read → replace exactly one key → re-serialise. Every other key in the
document, at every level, is carried through untouched and in its original
order, because `json.loads`/`json.dumps` both preserve insertion order. That
matters most for the user-scope file, which holds the entire Claude Code
user state and would be catastrophic to rewrite from a template.
@brief Compute the merge without performing it.
@return The MergePlan.
@version 1
"""
document, raw = load_document(path)
servers = document.get(SERVERS_KEY, {})
if not isinstance(servers, dict):
raise ConfigError(f"{path}: '{SERVERS_KEY}' is not an object — refusing to touch it")
existing = servers.get(name)
if existing is not None and not isinstance(existing, dict):
raise ConfigError(f"{path}: '{SERVERS_KEY}.{name}' is not an object — refusing to touch it")
action = _classify(path.exists(), existing, entry)
merged = {**document, SERVERS_KEY: {**servers, name: entry}}
# Keep the file's own trailing-newline convention; only an existing file that
# lacked one stays without.
newline = "" if raw and not raw.endswith("\n") else "\n"
text = json.dumps(merged, indent=_indent_of(raw)) + newline
return MergePlan(
path=path,
action=action,
entry=entry,
existing=existing,
document=merged,
text=text,
diff=_entry_diff(existing, entry),
)
Activity · 12 steps
Requirements
Flows
resolve_server_command
CommandResolution clew.mcp_config.resolve_server_command(Path repo_root, str scope, *Any which=None, Path|None bindir=None)
Decide the command string to record for this machine.
Called by _check_server_command, _register
Tested by
Source · 47 lines
def resolve_server_command(
repo_root: Path,
scope: str,
*,
which: Any = None,
bindir: Path | None = None,
) -> CommandResolution:
"""THE DELIBERATE DECISION this module exists to make.
For a `pip install clew` user the right answer is the bare console
script `clew-mcp`: that is the interface the package publishes, it
survives the checkout moving, and it is what any other installed MCP server
looks like in a config. An absolute interpreter path plus `-m` is not an
interface — the same reasoning that put `[project.scripts]` in pyproject.
But a bare name that the launching shell cannot resolve produces a server
that silently never starts, which is strictly worse than a machine-specific
path. So the order is: PATH name → repo-relative path (when the script lives
inside the repo being registered, the developer-checkout case) → absolute path, flagged
non-portable → nothing found, and the caller refuses to write a config naming
a command that does not exist.
Repo-relative is offered for repo scope ONLY. A user-scoped config loads from
every directory the user works in, so a relative command there would resolve
against whatever happened to be the cwd.
@brief Resolve the MCP server command to record.
@return CommandResolution (`command` None when the script is absent).
@version 2
"""
lookup = which if which is not None else shutil.which
bins = bindir if bindir is not None else Path(sys.executable).parent
path, on_path = _locate_script(lookup, bins)
if path is None:
return CommandResolution(
None,
f"{CONSOLE_SCRIPT} not found on PATH or in {bins} — the package is "
"installed but its console script is missing, which usually means a "
"broken install: pip install --force-reinstall clew",
False,
)
relative = _repo_relative(path, repo_root) if scope == INIT_SCOPE_REPO else None
if relative is not None:
return CommandResolution(relative, f"repo-relative script ({path})", True)
return _path_or_name(path, on_path)
Activity · 9 steps
Requirements
Flows
server_entry
dict[str, Any] clew.mcp_config.server_entry(str command, str|None repo=None)
The server entry this tool writes.
Source · 40 lines
def server_entry(command: str, repo: str | None = None) -> dict[str, Any]:
"""NEITHER SCOPE PASSES `--repo` ANY MORE, so there is no longer a `scope`
parameter to branch on (gh#22).
Repo scope used to write `--repo .`, which PINNED the server: it registered its
tools at startup and refused to retarget. Both halves of that turned out to be
wrong. The refusal meant a session could not index a second repository at all
(gh#19), and the pin was not even reliable at the job it was for — a stale one
invalidated a 36-cell benchmark run, where 15 of 18 cells said in prose that they
were looking at the wrong repository and all 36 were recorded valid. A pin makes a
server MORE confidently wrong, not less.
The server now derives its target — `$CLAUDE_PROJECT_DIR` at startup, else the
client's `roots/list` on the first call — so a project-scoped config that names no
repo resolves to the project it is committed in, which is what `--repo .` was
trying to express and could not, because `.` resolves against the LAUNCHING
process's cwd rather than the config's directory.
`repo` remains, for a caller that writes a config it will not run from. The
benchmark harness is the case: its cells run in a scratch working directory, so
nothing in the environment names the target. It had been hand-rolling this entry as
a literal dict, and that copy is what went stale — one definition, so the two
cannot drift again.
No `env` key is emitted. The entry is compared for equality against whatever
is already in the file, so every field written is a field a re-run must
reproduce exactly; an empty `env: {}` would be one more thing to disagree
about for no behavioural gain.
@brief Build this server's MCP config entry.
@return The entry mapping.
@version 3
"""
return {
"type": "stdio",
"command": command,
"args": [] if repo is None else ["--repo", repo],
}