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.

clew/init_command.py:529

Show on the map →

Called by _register

Calls none

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
lines 535–535return [c for c in checks if c.status == CHECK_FAIL and c.name in BLOCKING_CHECKS]

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.

clew/init_command.py:189

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
lines 200–200◇ if scope == INIT_SCOPE_REPOlines 201–201return Check(CHECK_CLIENT_CONFIG, CHECK_OK, f"repo scope — <repo>/{REPO_CONFIG_NAME}")lines 202–202config, state = global_config_evidence()lines 203–203◇ if global_config_available()lines 204–204return Check(CHECK_CLIENT_CONFIG, CHECK_OK, f"user-scope config {config}")lines 205–211return 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}.", )

Flows

_check_declaration

Check clew.init_command._check_declaration(Path repo_root)

Whether the repo declares its own indexing conventions.

clew/init_command.py:464

Show on the map →

Called by diagnose

Calls none

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
lines 474–474path = repo_root / DECLARATION_NAMElines 475–475◇ if path.is_file()lines 476–476return Check(CHECK_DECLARATION, CHECK_OK, str(path))lines 477–482return 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.", )

Flows

_check_doxygen

Check clew.init_command._check_doxygen(Path repo_root)

Whether the external doxygen binary is available.

clew/init_command.py:329

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
lines 348–348from .rustdoc import uses_rustdoclines 350–350◇ if uses_rustdoc(repo_root)lines 351–356return Check( CHECK_DOXYGEN, CHECK_OK, "not required — this repo's structural index is built with rustdoc, not doxygen " "(no Cargo.toml-adjacent Doxyfile found)", )lines 357–357found = shutil.which("doxygen")lines 358–358◇ if not found and not _needs_doxygen(repo_root)lines 359–364return 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)", )lines 365–365◇ if not foundlines 366–371return Check( CHECK_DOXYGEN, CHECK_FAIL, "doxygen is not on PATH — no database can be built until it is " "(e.g. apt install doxygen)", )lines 378–378from .doxygen import doxygen_supports_sqlite3lines 380–380supported = doxygen_supports_sqlite3(found)lines 381–381◇ if supported is Falselines 382–390return 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", )lines 391–391◇ if supported is Nonelines 392–397return 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", )lines 398–398return Check(CHECK_DOXYGEN, CHECK_OK, f"{found} (sqlite3 output supported)")

Flows

_check_indexable

Check clew.init_command._check_indexable(Path repo_root)

Whether this repo can be indexed at all.

clew/init_command.py:406

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
lines 419–419from .doxygen import discover_doxyfilelines 420–420from .scope import derive_scopelines 422–422doxyfile = discover_doxyfile(repo_root)lines 423–423◇ if doxyfile is not Nonelines 424–424return Check(CHECK_INDEXABLE, CHECK_OK, f"Doxyfile: {doxyfile}")lines 443–443derived = derive_scope(repo_root)lines 444–444◇ if derived.rootslines 445–445route = "declared scope" if derived.is_derived() else "the whole repository"lines 446–450return Check( CHECK_INDEXABLE, CHECK_OK, f"no Doxyfile — one will be synthesized from {route} ({derived.reason})", )lines 451–456return 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})", )

Flows

_check_mcp_sdk

Check clew.init_command._check_mcp_sdk()

Whether the SDK module the server imports can actually be imported.

clew/init_command.py:237

Show on the map →

Called by diagnose

Calls none

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
lines 266–266trylines 267–267from .mcp_server._sdk import MCP_SERVER_MODULElines 268–268except Exception as exclines 269–276return 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", )lines 277–277return Check(CHECK_MCP_SDK, CHECK_OK, f"{MCP_SERVER_MODULE} is importable")

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.

clew/init_command.py:220

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
lines 226–226resolution = resolve_server_command(repo_root, scope)lines 227–227◇ if resolution.command is Nonelines 228–228return Check(CHECK_SERVER_COMMAND, CHECK_FAIL, resolution.origin)lines 229–229status = CHECK_OK if resolution.portable else CHECK_WARNlines 230–230return Check(CHECK_SERVER_COMMAND, status, f"{resolution.command} — {resolution.origin}")

Flows

_emit

None clew.init_command._emit(MergePlan plan, bool dry_run)

Emit a plan: print it under dry-run, otherwise write it.

clew/init_command.py:602

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
lines 609–609◇ if dry_runlines 610–610_print_merge_preview(plan)lines 611–611returnlines 612–612◇ if plan.action == INIT_ACTION_UNCHANGEDlines 613–613print(f"\n {plan.path}: '{MCP_ENTRY_NAME}' already registered and identical — no change.")lines 614–614returnlines 615–615apply_plan(plan)lines 616–616print(f"\n {plan.action}: wrote '{MCP_ENTRY_NAME}' to {plan.path}")

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.

clew/init_command.py:627

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
lines 637–637◇ if plan.action == INIT_ACTION_UPDATE and not args.forcelines 638–638_print_conflict(plan)lines 639–639return 1lines 640–640_emit(plan, args.dry_run)lines 641–641_print_next_steps(plan, args.dry_run)lines 642–642return 1 if any(c.status == CHECK_FAIL for c in checks) else 0

Flows

_format_check

str clew.init_command._format_check(Check check)

Render one check as a single report line.

clew/init_command.py:515

Show on the map →

Called by init_main

Calls none

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
lines 521–521return f" [{check.status:<4}] {check.name:<15} {check.detail}"

Flows

_needs_doxygen

bool clew.init_command._needs_doxygen(Path repo_root)

Whether any file in the repo is one doxygen would index.

clew/init_command.py:292

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
lines 300–300import fnmatchlines 301–301import oslines 303–303from .doxygen import DOXYGEN_DEFAULT_FILE_PATTERNSlines 305–305from .synth import claimslines 307–309patterns = [ p for p in DOXYGEN_DEFAULT_FILE_PATTERNS if p not in ("*.md", "*.markdown", "*.dox") ]lines 310–310seen = 0lines 311–311parse_built = Falselines 312–312◇ for _dir, dirnames, filenames in os.walk(repo_root)lines 313–313dirnames[:] = [d for d in dirnames if d not in _NO_SOURCE_DIRS and not d.startswith(".")]lines 314–314◇ for name in filenameslines 315–315seen += 1lines 316–316◇ if seen > _DOXYGEN_PROBE_LIMIT or any(fnmatch.fnmatchcase(name, p) for p in patterns)lines 317–317return Truelines 318–318parse_built = parse_built or claims(name)lines 321–321return not parse_built

Requirements

REQ-DDB-PIPE-012

Flows

_print_conflict

None clew.init_command._print_conflict(MergePlan plan)

Print the refusal for a conflicting existing entry.

clew/init_command.py:542

Show on the map →

Called by _execute

Calls none

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
lines 551–551print(f"\n refusing to change the existing '{MCP_ENTRY_NAME}' entry in {plan.path}")lines 552–552print(" it differs from what would be written:\n")lines 553–553◇ for line in plan.diff.splitlines()lines 554–554print(f" {line}")lines 555–555print("\n re-run with --force to replace it.")

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.

clew/init_command.py:562

Show on the map →

Called by _emit

Calls none

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
lines 584–584head = f"\n --dry-run ({plan.action}) — nothing written."lines 585–585◇ if plan.action == INIT_ACTION_UNCHANGEDlines 586–586print(f"{head} {plan.path} already holds an identical '{MCP_ENTRY_NAME}' entry.")lines 587–587returnlines 588–588print(f"{head} {plan.path} would {plan.action} the '{MCP_ENTRY_NAME}' entry:\n")lines 589–589◇ for line in json.dumps(plan.entry, indent=2, sort_keys=True).splitlines()lines 590–590print(f" {line}")lines 591–591◇ if plan.difflines 592–592print("\n replacing the entry recorded there now:\n")lines 593–593◇ for line in plan.diff.splitlines()lines 594–594print(f" {line}")

Flows

_print_next_steps

None clew.init_command._print_next_steps(MergePlan plan, bool dry_run)

Tell the user what happens next.

clew/init_command.py:650

Show on the map →

Called by _execute

Calls none

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
lines 655–655◇ if dry_runlines 656–656returnlines 657–660print( f" restart your MCP client so it loads {plan.path}; the agent's first " "call to this server will offer to build the index." )

Flows

_register

int clew.init_command._register(list[Check] checks, Path repo_root, argparse.Namespace args)

Compute and perform the registration, given the diagnostics.

clew/init_command.py:670

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
lines 676–676blocked = _blocking(checks)lines 677–677◇ if blockedlines 678–678print("\n not registering — " + "; ".join(c.detail for c in blocked))lines 679–679return 1lines 680–680resolution = resolve_server_command(repo_root, args.scope)lines 681–681entry = server_entry(str(resolution.command))lines 682–682trylines 683–683plan = plan_merge(config_path(args.scope, repo_root), entry)lines 684–684except ConfigError as exclines 685–685print(f"\n not registering — {exc}")lines 686–686return 1lines 687–687return _execute(plan, repo_root, args, checks)

Flows

build_parser

argparse.ArgumentParser clew.init_command.build_parser()

Build the clew init argument parser.

clew/init_command.py:138

Show on the map →

Called by init_main

Tested by

1 teststest_parser_defaults

Calls none

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
lines 148–152parser = argparse.ArgumentParser( prog="clew init", description="Register the clew MCP server and check it can run.", epilog=_EPILOG, )lines 153–162parser.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." ), )lines 163–167parser.add_argument( "--repo-root", default=".", help="Repo to register and diagnose (default: the current directory).", )lines 168–175parser.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." ), )lines 176–180parser.add_argument( "--dry-run", action="store_true", help="Print the exact JSON that would be written, and touch nothing.", )lines 181–181return parser

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.

clew/init_command.py:492

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
lines 500–507return [ _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), ]

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 .

clew/init_command.py:695

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

Activity · 8 steps
lines 705–705args = build_parser().parse_args(argv)lines 706–706repo_root = Path(args.repo_root).expanduser().resolve()lines 707–707checks = diagnose(repo_root, args.scope)lines 708–708print(f"\nclew init — {repo_root} (scope: {args.scope})\n")lines 709–709print(f" {CHECK_STATUS.means}\n")lines 710–710◇ for check in checkslines 711–711print(_format_check(check))lines 712–712return _register(checks, repo_root, args)

Requirements

REQ-DDB-CLI-001

Flows