init_command.py¶
clew/init_command.py
`clew init` — register this MCP server, and check it will actually run.
_blocking
list[Check] clew.init_command._blocking(list[Check] checks)
The blocking failures among a set of checks.
Source · 9 lines
def _blocking(checks: list[Check]) -> list[Check]:
"""@brief Select the failures that must stop the write.
@return Blocking failed checks.
@version 1
"""
return [c for c in checks if c.status == CHECK_FAIL and c.name in BLOCKING_CHECKS]
Activity · 1 steps
Flows
_check_client_config
Check clew.init_command._check_client_config(str scope)
Whether the user-scope config location can be established on this machine.
Source · 25 lines
def _check_client_config(scope: str) -> Check:
"""Repo scope is unconditionally fine — the file lives in the repo the user
named. Global scope must first EVIDENCE that Claude Code keeps its config
where we think it does; with no evidence it refuses and names both paths it
looked at, because writing a config to an invented path is worse than not
writing one.
@brief Verify the target config location for this scope.
@return The client-config check.
@version 1
"""
if scope == INIT_SCOPE_REPO:
return Check(CHECK_CLIENT_CONFIG, CHECK_OK, f"repo scope — <repo>/{REPO_CONFIG_NAME}")
config, state = global_config_evidence()
if global_config_available():
return Check(CHECK_CLIENT_CONFIG, CHECK_OK, f"user-scope config {config}")
return Check(
CHECK_CLIENT_CONFIG,
CHECK_FAIL,
f"no user-level Claude Code config found — looked for {config} and {state}/. "
f"Set {CLAUDE_CONFIG_DIR_ENV} if it lives elsewhere, or use --scope "
f"{INIT_SCOPE_REPO}.",
)
Activity · 6 steps
Flows
_check_declaration
Check clew.init_command._check_declaration(Path repo_root)
Whether the repo declares its own indexing conventions.
Source · 21 lines
def _check_declaration(repo_root: Path) -> Check:
"""Absent is the norm, not a defect — most repos run entirely on built-in
defaults. It is still surfaced, because an empty causal layer on a repo whose
accessors the defaults cannot see is the single most common "why is this
database useless" report, and `clew propose` answers it from evidence.
@brief Report whether the repo carries a `.clew.yaml`.
@return The declaration check.
@version 2
"""
path = repo_root / DECLARATION_NAME
if path.is_file():
return Check(CHECK_DECLARATION, CHECK_OK, str(path))
return Check(
CHECK_DECLARATION,
CHECK_WARN,
f"no {DECLARATION_NAME} — built-in defaults apply. Run `clew propose` "
"to see, from evidence, what this repo could declare.",
)
Activity · 4 steps
Flows
_check_doxygen
Check clew.init_command._check_doxygen(Path repo_root)
Whether the external doxygen binary is available.
Called by diagnose
Tested by 5 tests
test_an_unrunnable_doxygen_probe_warns_rather_than_claiming_no_support, test_doxygen_check_is_informational_for_a_rustdoc_repo, test_doxygen_with_sqlite3_support_passes_the_doctor, test_doxygen_without_sqlite3_support_fails_the_doctor, test_init_doctor_does_not_require_doxygen_for_a_js_only_repo
Calls _needs_doxygen, doxygen_supports_sqlite3, uses_rustdoc
Source · 72 lines
def _check_doxygen(repo_root: Path) -> Check:
"""doxygen is a SUBPROCESS dependency, invisible to pip, so nothing else in
the install path notices it is missing — the first `build_or_refresh` does.
A repo whose build routes through rustdoc instead (see `rustdoc.uses_rustdoc`)
never shells out to doxygen at all — a broken or absent doxygen there is not
a blocker, and reporting it as [fail] (confirmed live: exit 1, on a pure-Rust
repo with no Doxyfile) reads as "clew is broken" when nothing on that repo's
actual build path is. Downgraded to informational for that case rather than
dropped outright, so a repo that LATER grows a C/C++ component still has the
evidence on record.
A repo holding nothing doxygen reads (JavaScript / TypeScript only) does not run it
either, so it is not a blocker there.
@brief Verify doxygen is on PATH and was built with sqlite3 output.
@return The doxygen check.
@version 5
"""
from .rustdoc import uses_rustdoc
if uses_rustdoc(repo_root):
return Check(
CHECK_DOXYGEN,
CHECK_OK,
"not required — this repo's structural index is built with rustdoc, not doxygen "
"(no Cargo.toml-adjacent Doxyfile found)",
)
found = shutil.which("doxygen")
if not found and not _needs_doxygen(repo_root):
return Check(
CHECK_DOXYGEN,
CHECK_OK,
"not required — nothing in this repo is a language doxygen reads (JavaScript / "
"TypeScript are indexed by clew's own parse)",
)
if not found:
return Check(
CHECK_DOXYGEN,
CHECK_FAIL,
"doxygen is not on PATH — no database can be built until it is "
"(e.g. apt install doxygen)",
)
## PRESENT IS NOT ENOUGH (gh#3). doxygen's sqlite3 generator is a BUILD-time option and
## Ubuntu 22.04 ships it OFF, so `apt install doxygen` satisfies the check above and every
## build still fails — with "Expected database not found", which names neither doxygen nor
## sqlite3. A doctor that reports [ok] on a binary that cannot do the one thing the pipeline
## needs is worse than no check: it actively certifies the broken environment.
from .doxygen import doxygen_supports_sqlite3
supported = doxygen_supports_sqlite3(found)
if supported is False:
return Check(
CHECK_DOXYGEN,
CHECK_FAIL,
f"{found} was built WITHOUT sqlite3 support, which clew requires — it will ignore "
f"GENERATE_SQLITE3, exit 0 and write no database. This is a build option "
f"(-Dbuild_sqlite3=ON), not a version: Ubuntu 22.04's doxygen 1.9.1 lacks it. "
f"Install a build that has it (conda-forge, homebrew, or build from source), then "
f"confirm with: doxygen -g - | grep GENERATE_SQLITE3",
)
if supported is None:
return Check(
CHECK_DOXYGEN,
CHECK_WARN,
f"{found} — could not probe whether it supports sqlite3 output; if a build fails "
f"with 'Expected database not found', check: doxygen -g - | grep GENERATE_SQLITE3",
)
return Check(CHECK_DOXYGEN, CHECK_OK, f"{found} (sqlite3 output supported)")
Activity · 15 steps
Flows
_check_indexable
Check clew.init_command._check_indexable(Path repo_root)
Whether this repo can be indexed at all.
Source · 53 lines
def _check_indexable(repo_root: Path) -> Check:
"""Two routes exist and the doctor reports WHICH: the repo ships a Doxyfile,
or it declares a doxygen-guard scope a minimal Doxyfile can be synthesized
from. Neither is a warning rather than a failure — the registration is still
correct, and adding either later needs no re-run of `init`.
Imported lazily: both modules pull the pipeline's heavier dependencies, and
`init` must stay runnable on a bare install.
@brief Verify the repo has, or can derive, a doxygen scope.
@return The indexable check.
@version 4
"""
from .doxygen import discover_doxyfile
from .scope import derive_scope
doxyfile = discover_doxyfile(repo_root)
if doxyfile is not None:
return Check(CHECK_INDEXABLE, CHECK_OK, f"Doxyfile: {doxyfile}")
## ANY SCOPE WITH ROOTS IS INDEXABLE, and that is the whole correction. This asked
## `is_derived()`, which is true ONLY for SOURCE_DECLARED — so a repo that declares nothing
## fell to a warn saying "index(action='refresh') will fail until this repo has one".
##
## MEASURED, on the exact configuration a new user arrives with: a git repo holding one `.c`
## file, no Doxyfile, no doxygen-guard config, no declaration. It BUILDS — doxygen is
## synthesized from the whole-repo scope and the function is indexed. The warn was wrong every
## time it fired, on the FIRST SCREEN `init` shows, telling a stranger the tool does not
## support their repository.
##
## The premise died with gh#333, which made whole-repo the DEFAULT tier rather than a last
## resort; `is_derived()` was not part of that change and kept meaning "declared". THE SUITE
## PINNED THE OLD ANSWER — `test_unindexable_repo_warns_but_still_registers` asserted the
## warn — so running the tests could not have found this. Running the product did.
##
## The warn is KEPT for a scope with no roots at all. `whole_repo_scope` always supplies one,
## so it is not currently reachable, and that is the point: a check should report what it
## measured rather than assert that a state is impossible.
derived = derive_scope(repo_root)
if derived.roots:
route = "declared scope" if derived.is_derived() else "the whole repository"
return Check(
CHECK_INDEXABLE,
CHECK_OK,
f"no Doxyfile — one will be synthesized from {route} ({derived.reason})",
)
return Check(
CHECK_INDEXABLE,
CHECK_WARN,
"no Doxyfile, and the derived scope named no roots to synthesize one from — "
f"index(action='refresh') will fail until this repo has one ({derived.reason})",
)
Activity · 10 steps
Flows
_check_mcp_sdk
Check clew.init_command._check_mcp_sdk()
Whether the SDK module the server imports can actually be imported.
Source · 43 lines
def _check_mcp_sdk() -> Check:
"""The SDK is a REQUIRED dependency (it was an optional extra until
2026-07-28), so a missing one now means a broken install rather than a missing
opt-in — and the message says so, because "run this pip command" would be
wrong advice for a dependency that pip should already have placed.
Still checked rather than assumed, and the probe targets the module the server
actually imports rather than the top-level package: `import mcp` succeeds under
every generation, so probing it would report OK for the one failure worth
catching.
THE PROBE PERFORMS THE SERVER'S OWN IMPORT rather than checking a name that
stands in for it. `_sdk` is the one module that imports the SDK, so if `_sdk`
imports, the server can start — that is ground truth, not a proxy for it, and
it is why this is an import inside the function rather than at module scope:
importing the SDK eagerly would crash the very command whose job is to report
that the SDK is broken.
The distinction is not pedantic. This check probed `find_spec` on a literal
`mcp.server.fastmcp` and called it "the server's own import line"; that stopped
being true when `_sdk` took over the import and the version cap moved, so the
doctor hard-failed every environment holding the only version a fresh install
resolves — while the suite stayed green, because the check had a test for its
fail path and none for its OK path. Both now exist.
@brief Verify the SDK module the server imports can actually be imported.
@return The mcp-sdk check.
@version 4
"""
try:
from .mcp_server._sdk import MCP_SERVER_MODULE
except Exception as exc:
return Check(
CHECK_MCP_SDK,
CHECK_FAIL,
f"the server's SDK import failed ({type(exc).__name__}: {exc}), so the "
"server cannot start. The SDK is a required dependency, so this means a "
"broken or partial install, or an `mcp` outside the declared `>=2,<3` "
"window. Reinstall: pip install --force-reinstall clew",
)
return Check(CHECK_MCP_SDK, CHECK_OK, f"{MCP_SERVER_MODULE} is importable")
Activity · 5 steps
Flows
_check_server_command
Check clew.init_command._check_server_command(Path repo_root, str scope)
Whether the MCP server console script can be located.
Source · 13 lines
def _check_server_command(repo_root: Path, scope: str) -> Check:
"""@brief Verify the server launch command resolves on this machine.
@return The server-command check.
@version 1
"""
resolution = resolve_server_command(repo_root, scope)
if resolution.command is None:
return Check(CHECK_SERVER_COMMAND, CHECK_FAIL, resolution.origin)
status = CHECK_OK if resolution.portable else CHECK_WARN
return Check(CHECK_SERVER_COMMAND, status, f"{resolution.command} — {resolution.origin}")
Activity · 5 steps
Flows
_emit
None clew.init_command._emit(MergePlan plan, bool dry_run)
Emit a plan: print it under dry-run, otherwise write it.
Source · 17 lines
def _emit(plan: MergePlan, dry_run: bool) -> None:
"""The dry-run preview is delegated so this function stays a two-way branch, and
so the entry-scoped rule lives in exactly one place.
@brief Print or apply a merge plan.
@version 2
"""
if dry_run:
_print_merge_preview(plan)
return
if plan.action == INIT_ACTION_UNCHANGED:
print(f"\n {plan.path}: '{MCP_ENTRY_NAME}' already registered and identical — no change.")
return
apply_plan(plan)
print(f"\n {plan.action}: wrote '{MCP_ENTRY_NAME}' to {plan.path}")
Activity · 8 steps
Flows
_execute
int clew.init_command._execute(MergePlan plan, Path repo_root, argparse.Namespace args, list[Check] checks)
Apply a plan subject to the conflict rule, and pick the exit code.
Source · 18 lines
def _execute(
plan: MergePlan, repo_root: Path, args: argparse.Namespace, checks: list[Check]
) -> int:
"""ONE WRITE, then the next-steps line. A differing existing entry is refused here rather
than deeper in, so the refusal is reported before anything has been emitted.
@brief Perform the write (or refuse) and return the exit code.
@return 0 when nothing failed, else 1.
@version 3
"""
if plan.action == INIT_ACTION_UPDATE and not args.force:
_print_conflict(plan)
return 1
_emit(plan, args.dry_run)
_print_next_steps(plan, args.dry_run)
return 1 if any(c.status == CHECK_FAIL for c in checks) else 0
Activity · 6 steps
Flows
_format_check
str clew.init_command._format_check(Check check)
Render one check as a single report line.
Source · 9 lines
def _format_check(check: Check) -> str:
"""@brief Format a check for the report.
@return One aligned `[status] name detail` line.
@version 1
"""
return f" [{check.status:<4}] {check.name:<15} {check.detail}"
Activity · 1 steps
Flows
_needs_doxygen
bool clew.init_command._needs_doxygen(Path repo_root)
Whether any file in the repo is one doxygen would index.
Source · 32 lines
def _needs_doxygen(repo_root: Path) -> bool:
"""Asked only when doxygen is missing, so a repo that has it never pays for the walk.
Mirrors the build's own decision (`cli._doxygen_has_source`): documentation files
(markdown, `.dox`) do not count.
@brief Probe the tree for a doxygen-source file.
@return Whether doxygen is needed.
"""
import fnmatch
import os
from .doxygen import DOXYGEN_DEFAULT_FILE_PATTERNS
from .synth import claims
patterns = [
p for p in DOXYGEN_DEFAULT_FILE_PATTERNS if p not in ("*.md", "*.markdown", "*.dox")
]
seen = 0
parse_built = False
for _dir, dirnames, filenames in os.walk(repo_root):
dirnames[:] = [d for d in dirnames if d not in _NO_SOURCE_DIRS and not d.startswith(".")]
for name in filenames:
seen += 1
if seen > _DOXYGEN_PROBE_LIMIT or any(fnmatch.fnmatchcase(name, p) for p in patterns):
return True
parse_built = parse_built or claims(name)
## Only a repo that HAS JavaScript / TypeScript is known not to need doxygen. An empty
## or unrecognised tree keeps the old verdict: doxygen is what a build will look for.
return not parse_built
Activity · 15 steps
Requirements
Flows
_print_conflict
None clew.init_command._print_conflict(MergePlan plan)
Print the refusal for a conflicting existing entry.
Source · 16 lines
def _print_conflict(plan: MergePlan) -> None:
"""Shows the diff and stops. Silently overwriting an entry the user tuned by
hand — a different command, extra args, a pinned repo — is the failure mode
this whole command is designed against, and it is invisible after the fact
because the config still looks well-formed.
@brief Report a conflicting entry and how to override.
@version 1
"""
print(f"\n refusing to change the existing '{MCP_ENTRY_NAME}' entry in {plan.path}")
print(" it differs from what would be written:\n")
for line in plan.diff.splitlines():
print(f" {line}")
print("\n re-run with --force to replace it.")
Activity · 5 steps
Flows
_print_merge_preview
None clew.init_command._print_merge_preview(MergePlan plan)
Print what a dry run would change, scoped to this server's entry.
Source · 35 lines
def _print_merge_preview(plan: MergePlan) -> None:
"""PRINTS THE ENTRY, NEVER `plan.text` — and that is a disclosure fix, not a
formatting preference (gh#27). `plan.text` is the whole re-serialised document,
and for `--scope global` the document is `~/.claude.json`: every project path the
user has ever opened, plus their prompt history, ~150KB of it. `--dry-run` is
precisely what someone runs before pasting output into a bug report and what an
agent runs inside a transcript, so it was the one code path guaranteed to publish
that file. It did so even when the action was `unchanged` and the run was a
verified no-op.
The rule is to show the REGION under review and nothing else. Everything outside
`mcpServers.<name>` is carried through untouched by `plan_merge` — by
construction, not by best effort — so the entry plus `plan.diff` IS the complete
change. Nothing reviewable is lost, including on `create`, where the document
`plan.text` would have printed holds this entry and nothing else anyway.
`unchanged` gets one line and no body. Printing a payload under a no-op reads as a
pending change and is simply untrue.
@brief Show the entry a dry run would write, plus any entry-level diff.
@version 2
"""
head = f"\n --dry-run ({plan.action}) — nothing written."
if plan.action == INIT_ACTION_UNCHANGED:
print(f"{head} {plan.path} already holds an identical '{MCP_ENTRY_NAME}' entry.")
return
print(f"{head} {plan.path} would {plan.action} the '{MCP_ENTRY_NAME}' entry:\n")
for line in json.dumps(plan.entry, indent=2, sort_keys=True).splitlines():
print(f" {line}")
if plan.diff:
print("\n replacing the entry recorded there now:\n")
for line in plan.diff.splitlines():
print(f" {line}")
Activity · 11 steps
Flows
_print_next_steps
None clew.init_command._print_next_steps(MergePlan plan, bool dry_run)
Tell the user what happens next.
Source · 13 lines
def _print_next_steps(plan: MergePlan, dry_run: bool) -> None:
"""@brief Print the follow-on step after a successful registration.
@version 1
"""
if dry_run:
return
print(
f" restart your MCP client so it loads {plan.path}; the agent's first "
"call to this server will offer to build the index."
)
Activity · 3 steps
Flows
_register
int clew.init_command._register(list[Check] checks, Path repo_root, argparse.Namespace args)
Compute and perform the registration, given the diagnostics.
Called by init_main
Calls _blocking, _execute, config_path, plan_merge, resolve_server_command, server_entry
Source · 20 lines
def _register(checks: list[Check], repo_root: Path, args: argparse.Namespace) -> int:
"""@brief Plan and apply the config write, refusing on a blocking failure.
@return Process exit code.
@version 3
"""
blocked = _blocking(checks)
if blocked:
print("\n not registering — " + "; ".join(c.detail for c in blocked))
return 1
resolution = resolve_server_command(repo_root, args.scope)
entry = server_entry(str(resolution.command))
try:
plan = plan_merge(config_path(args.scope, repo_root), entry)
except ConfigError as exc:
print(f"\n not registering — {exc}")
return 1
return _execute(plan, repo_root, args, checks)
Activity · 12 steps
Flows
build_parser
argparse.ArgumentParser clew.init_command.build_parser()
Build the clew init argument parser.
Source · 46 lines
def build_parser() -> argparse.ArgumentParser:
"""Four flags, and `--force` is deliberately never implied by another. A blanket
"assume yes" that also covered `--force` would let one flag replace a hand-tuned
server entry, which is the outcome `--force` exists to require a separate decision
for.
@brief Construct the init command's CLI parser.
@return The configured ArgumentParser.
@version 3
"""
parser = argparse.ArgumentParser(
prog="clew init",
description="Register the clew MCP server and check it can run.",
epilog=_EPILOG,
)
parser.add_argument(
"--scope",
choices=INIT_SCOPE.values,
default=INIT_SCOPE_REPO,
help=(
f"Where to register. '{INIT_SCOPE_REPO}' (default) writes "
f"<repo>/{REPO_CONFIG_NAME}; '{INIT_SCOPE_GLOBAL}' writes the "
"user-level Claude Code config."
),
)
parser.add_argument(
"--repo-root",
default=".",
help="Repo to register and diagnose (default: the current directory).",
)
parser.add_argument(
"--force",
action="store_true",
help=(
"Replace an existing entry for this server that differs from the one "
"that would be written. Never implied: the config is the user's file."
),
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print the exact JSON that would be written, and touch nothing.",
)
return parser
Activity · 6 steps
Requirements
REQ-DDB-CLI-001 REQ-DDB-CLI-002
Flows
diagnose
list[Check] clew.init_command.diagnose(Path repo_root, str scope)
Run every doctor check for a repo and scope.
Called by init_main
Tested by
Calls _check_client_config, _check_declaration, _check_doxygen, _check_indexable, _check_mcp_sdk, _check_server_command
Source · 18 lines
def diagnose(repo_root: Path, scope: str) -> list[Check]:
"""Ordered so the two blocking checks come first: when one of them fails,
everything after it is context for a run that is not going to write anything.
@brief Produce the full diagnostic report.
@return List of checks in reporting order.
@version 4
"""
return [
_check_client_config(scope),
_check_server_command(repo_root, scope),
_check_mcp_sdk(),
_check_doxygen(repo_root),
_check_indexable(repo_root),
_check_declaration(repo_root),
]
Activity · 1 steps
Requirements
REQ-DDB-CLI-001 REQ-DDB-CLI-002
Flows
init_main
int clew.init_command.init_main(list[str]|None argv=None)
Run clew init .
Source · 18 lines
def init_main(argv: list[str] | None = None) -> int:
"""Diagnose first, always, and print the whole report before doing anything
— including on the runs that end in a refusal. The report IS the product on
those runs: a user whose `doxygen` is missing needs to see that on the same
run that told them the entry conflicts, not one re-run later.
@brief Diagnose the environment and register the MCP server.
@return Process exit code.
@version 1
"""
args = build_parser().parse_args(argv)
repo_root = Path(args.repo_root).expanduser().resolve()
checks = diagnose(repo_root, args.scope)
print(f"\nclew init — {repo_root} (scope: {args.scope})\n")
print(f" {CHECK_STATUS.means}\n")
for check in checks:
print(_format_check(check))
return _register(checks, repo_root, args)1 more lines, not shown