Skip to content

fix(mcp): plugin MCP server dies with CONNECTION_CLOSED when the open project has an older sequant in node_modules — npx ignores the pin and runs the local copy #1084

Closed

Description

@admarble

Follow-up to #793 / #988 (MCP launch pinning). Sibling of #991 (npx resolution picks the wrong sequant).

What happens

The plugin's .mcp.json starts the MCP server with npx -y sequant@<pin> serve, and Claude Code launches it with cwd = the open project. When that project has any sequant in its own node_modules — for example a stale "sequant": "^1.20.0" devDependency nobody imports — npx runs the local copy and ignores the pinned version. A pre-serve release prints unknown command 'serve' and exits, and /mcp reports only:

Failed to reconnect to plugin:sequant:sequant: CONNECTION_CLOSED

Nothing in the shipped sequant version runs, so no preflight, warning, or sequant://install resource can catch it. The user sees a plugin that "won't connect" with no pointer to the cause.

Measured (2026-09-18, npm 10.9.8, node 22.23.0, project with [email protected] in node_modules)

Launch form (cwd = that project) Version that ran
npx -y [email protected] --version 1.20.1
npx -y [email protected] sequant --version 1.20.1
npx --prefix <empty dir> -y [email protected] --version 1.20.1
npm_config_prefix=<empty dir> npx -y [email protected] --version 1.20.1
same command, cwd = a dir with no node_modules/sequant ancestor 2.15.1

npx -y [email protected] serve from that project → stderr error: unknown command 'serve' (Did you mean merge?), exit 0 after printing help. Sending an MCP initialize gets no reply. From a clean cwd the same command answers initialize with serverInfo.version: 2.15.1.

Conclusion: the shadowing keys off cwd (npx's local-project lookup), not the package spec and not --prefix. No npx flag defeats it; only the working directory does.

Note the dev repo already leans on this same behavior: from the sequant checkout, npx -y sequant@X serve runs the repo's own dist/bin/cli.js because package.json declares the sequant bin.

Fix

Stop letting npx resolve sequant from the open project. Two-part change:

1. A dependency-free launcher shipped with the plugin. Claude Code expands ${CLAUDE_PLUGIN_ROOT} and ${CLAUDE_PROJECT_DIR} in plugin .mcp.json command/args/env (docs: code.claude.com/docs/en/mcp — "CLAUDE_PLUGIN_ROOT and Path Placeholders"). The shipped config becomes roughly:

{ "mcpServers": { "sequant": {
  "command": "node",
  "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launch.mjs", "[email protected]"],
  "env": { "SEQUANT_PROJECT_DIR": "${CLAUDE_PROJECT_DIR}" }
} } }

scripts/mcp-launch.mjs uses only node: builtins (the plugin checkout is not npm installed), spawns npx -y <spec> serve with cwd = a fresh mkdtemp dir (no package.json/node_modules ancestor, so npx must use its cache), pipes stdio through, forwards signals, and exits with the child's code. It passes the real project dir down in SEQUANT_PROJECT_DIR (falling back to its own process.cwd() when the placeholder is empty).

2. serve honors SEQUANT_PROJECT_DIR. First thing in serveCommand, process.chdir(process.env.SEQUANT_PROJECT_DIR) when set and it is a directory — every MCP tool and the install resource already key off process.cwd(), so nothing else moves. Reject (stderr + exit 1) if the dir does not exist rather than silently serving the temp dir.

prepare-marketplace.ts keeps stamping the pin; its regex (/sequant@[^"\s]+/g) already matches the spec wherever it sits in args, and scripts/plugin-mcp-pin.test.ts already finds the pin by prefix, so both survive the shape change — verify rather than assume.

Open questions for /spec

  • Dual use of the root .mcp.json. Marketplace source is "./", so the shipped file is the dev repo's own MCP config. ${CLAUDE_PLUGIN_ROOT} is not defined when Claude Code loads it as a project config. Options: (a) ${CLAUDE_PLUGIN_ROOT:-.} if placeholder substitution accepts the :-default form (docs list :- only for env vars — Phase-0 check), (b) launcher path relative to cwd for contributors with a .claude/settings.local.json override, (c) move the plugin source to a subdirectory. Prefer (a) if it works; it keeps one file.
  • Windows. os.tmpdir() sits under the user profile; a home-stray %USERPROFILE%\node_modules\sequant (the case cli.ts already warns about) would still shadow. Acceptable if documented; the launcher can log the resolved cwd on stderr for diagnosis.
  • sequant init --mcp project config (getSequantMcpConfig in src/lib/mcp-config.ts) has the same hole when a project carries an old local sequant, and has no plugin root to point at. Out of scope here beyond the doctor check below; file separately if /spec agrees.

Acceptance Criteria

  • AC-1: scripts/mcp-launch.mjs exists, imports only node: builtins, and spawns npx -y <spec> serve with a cwd that has no package.json or node_modules in its ancestor chain, forwarding stdio, exit code, and SIGINT/SIGTERM.
  • AC-2: The shipped .mcp.json launches the server as "command": "node", "args": ["-e", "<launcher source>", "sequant@<pin>"] with NO ${...} placeholder anywhere in command, args, or env (owner decision, comment of 2026-09-18: ${CLAUDE_PLUGIN_ROOT:-.} resolves to the open project, not the plugin root); a test asserts the inline args[1] is byte-identical to the generated form of scripts/mcp-launch.mjs, and scripts/plugin-mcp-pin.test.ts finds the exact sequant@<package.json version> pin in args[2] and fails if any arg contains ${.
  • AC-3: serve chdirs to SEQUANT_PROJECT_DIR when set and exits non-zero with a stderr message naming the path when it is not a directory; sequant_status and sequant://install resolve against that dir (test: set the env var to a temp project and assert the resource reports that project's manifest).
  • AC-4: Integration test reproduces the shadow — temp project with a fake node_modules/sequant whose bin prints unknown command 'serve' and a fake npx on PATH that records its cwd — and asserts the launcher's npx cwd is outside that project and the recorded spec is the pin; the test fails when the launcher passes the project dir as cwd (Mutation-verified marker in the PR body per CLAUDE.md).
  • AC-5: sequant doctor warns when node_modules/sequant exists in the project (or $HOME) at a version different from the version .mcp.json pins or the running CLI, naming the path, both versions, and the remediation (npm uninstall sequant or bump).
  • AC-6: docs/troubleshooting.md "MCP Server Issues" gains a CONNECTION_CLOSED / unknown command 'serve' entry that names the local-node_modules cause, the one-line diagnosis (cd <project> && npx -y sequant@<pin> --version printing the wrong version), and the fix; docs/features/mcp-server.md documents SEQUANT_PROJECT_DIR.
  • AC-7: The MCP server starts through .mcp.json as resolved by Claude Code (not by invoking the launcher directly) in BOTH contexts — the sequant checkout as a project config, and a throwaway local-marketplace install of the plugin in a project that has an older sequant in node_modules — with the initialize reply reporting the pinned version; both probes recorded verbatim in the PR test plan.

Scope note

This changes the plugin's launch shape, which plugin users pick up on their next plugin update. It does not touch how phases launch MCP servers for agents (getPhaseMcpServersConfig), and it does not fix already-installed old versions — it only stops them from being run by mistake.

Activity

  1. added
    bug
    cli
    on Sep 18, 2026
  2. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (7 ACs, 7 directories)

    AC Quality Check

    All 7 AC are concrete and testable — each names specific files, exact behaviors (exit codes, env vars, stderr text), and a test setup. No vague/unmeasurable language detected. Note: none use the Evidence: declared-verification clause from the AC authoring standard, so the verification methods below are inferred from AC text, not declared.


    Scope Assessment

    Non-Goals: Not present under a ## Non-Goals heading, but the issue's ## Scope note performs the same function: "does not touch how phases launch MCP servers for agents ... does not fix already-installed old versions — it only stops them from being run by mistake."

    Metric Value Status
    Feature count 3 (launcher/config, serve+doctor, docs) ❌
    AC items 7 ⚠️
    Directory spread 7 ❌

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED

    Recommendation: keep as one issue/PR despite the red verdict. The pieces are causally coupled — shipping the launcher (AC-1/AC-2) without serve honoring SEQUANT_PROJECT_DIR (AC-3) leaves sequant_status/sequant://install resolving against the wrong project even though the shadow itself is fixed. Splitting would produce partial, individually-broken deploys. Treat the red verdict as a signal to enable the quality loop (see Recommended Workflow), not to file separate issues.


    Acceptance Criteria

    AC-1: scripts/mcp-launch.mjs launcher

    Verification: Integration Test
    Scenario: Given a fake npx on PATH and a project cwd → When the launcher runs with a package spec and forwards a SIGINT → Then it spawned npx -y <spec> serve in a mkdtemp dir with no package.json/node_modules ancestor, piped stdio, and propagated the signal/exit code.
    Assumptions: spawn(..., { shell: false }) — no shell interpolation of the package spec or SEQUANT_PROJECT_DIR.

    AC-2: Shipped .mcp.json launches through the launcher

    Verification: Unit Test (extends scripts/plugin-mcp-pin.test.ts)
    Scenario: Given the root .mcp.json → When parsed → Then command/args invoke mcp-launch.mjs via ${CLAUDE_PLUGIN_ROOT}, env.SEQUANT_PROJECT_DIR is ${CLAUDE_PROJECT_DIR}, and the pin regex/prefix match still finds sequant@<package.json version> in the new args shape.
    Assumptions: Resolved by Open Question 1 below before this AC can be implemented — the dual-use .mcp.json shape depends on whether ${CLAUDE_PLUGIN_ROOT:-.} actually substitutes.

    AC-3: serve chdirs to SEQUANT_PROJECT_DIR

    Verification: Integration Test (extend src/commands/serve.integration.test.ts)
    Scenario: Given SEQUANT_PROJECT_DIR=<temp project> → When serveCommand starts → Then it chdirs there before createServer, and sequant_status/sequant://install report that project's manifest. Given the var points at a non-directory → Then stderr names the path and the process exits non-zero.
    Assumptions: chdir happens before getSkillsInstallStatus()/createServer() — both already key off process.cwd() per mcp-config.ts's getPhaseMcpServersConfig doc comment.

    AC-4: Integration test reproduces the shadow

    Verification: Integration Test (mutation-verified, per CLAUDE.md)
    Scenario: Given a temp project with node_modules/sequant/bin printing unknown command 'serve' and a fake npx on PATH recording its invocation cwd → When the launcher runs from that project → Then the recorded npx cwd is outside the temp project and the recorded spec is the pin; deleting the mkdtemp-cwd logic must fail this test.
    Assumptions: This is the direct regression fixture for the issue's own measured table — reuse those exact repro conditions rather than a synthetic simplification (see feedback_synthetic_test_fixture_trap).

    AC-5: sequant doctor warns on a shadowing local sequant

    Verification: Unit Test (doctor.test.ts) + existing doctor.integration.test.ts extension
    Scenario: Given node_modules/sequant/package.json exists in cwd (or $HOME) at a version differing from .mcp.json's pin / the running CLI's getVersion() → When doctorCommand runs → Then a warn check names the path, both versions, and npm uninstall sequant / bump remediation.
    Assumptions: "or $HOME" is interpreted as: walk cwd's ancestor chain (npm's own resolution order) AND separately stat $HOME/node_modules/sequant — flagged in Open Question 3, confirm before implementing.

    AC-6: Docs updated

    Verification: Manual Test (content check, not file-existence check — per feedback_qa_docs_verification)
    Scenario: Given docs/troubleshooting.md → When reading "MCP Server Issues" → Then a new entry names the local-node_modules cause, the one-line diagnosis command, and the fix. Given docs/features/mcp-server.md → Then SEQUANT_PROJECT_DIR is documented.
    Assumptions: None.

    AC-7: Dev repo's own MCP server still starts

    Verification: Manual Test
    Scenario: Given the sequant checkout's own root .mcp.json (post dual-use fix) → When Claude Code loads it as the dev repo's project MCP config → Then the server starts, verified by hand and recorded in the PR test plan.
    Assumptions: Depends on which dual-use option Open Question 1 resolves to.


    Implementation Plan

    Phase 0: Resolve the dual-use .mcp.json question (blocks AC-2, AC-7)

    1. Spike whether Claude Code's plugin-config placeholder engine honors ${CLAUDE_PLUGIN_ROOT:-.} (bash-style default) when loading .mcp.json as a plain project config (no CLAUDE_PLUGIN_ROOT in env). The repo's existing ${CLAUDE_PLUGIN_ROOT:-./templates} uses are inside bash script bodies (setup/SKILL.md, exec/SKILL.md), not inside JSON command/args that Claude Code itself substitutes — no existing evidence this repo relies on the :- form working in that engine. Test empirically before committing to option (a).
    2. If (a) fails, fall back to option (b) (launcher path relative to cwd, contributors override via .claude/settings.local.json) or (c) (move plugin source to a subdirectory) — pick based on the spike result, not in advance.

    Phase 1: Launcher script

    1. Write scripts/mcp-launch.mjs — node: builtins only (child_process, fs, os, path): mkdtemp an isolated cwd, spawn("npx", ["-y", spec, "serve"], { cwd, stdio: "inherit", shell: false }), forward SIGINT/SIGTERM to the child, exit with the child's code/signal, rmSync the temp dir on exit (best-effort).
    2. Resolve SEQUANT_PROJECT_DIR from process.env.CLAUDE_PROJECT_DIR (the placeholder Claude Code injects) falling back to the launcher's own process.cwd(); log the resolved launcher cwd to stderr (addresses Open Question 2 — Windows diagnosis).

    Phase 2: Wire .mcp.json + prepare-marketplace.ts

    1. Update root .mcp.json per the Phase 0 decision: command: "node", args: ["<launcher-path>", "sequant@<pin>"], env: { SEQUANT_PROJECT_DIR: "${CLAUDE_PROJECT_DIR}" }.
    2. Update scripts/prepare-marketplace.ts's readSequantPin/pin-stamping regex if the pin's position in args moved — verify against the new shape, don't assume #988's array-scan survives unchanged.

    Phase 3: serve chdir (AC-3)

    1. In serveCommand (src/commands/serve.ts), before getSkillsInstallStatus()/createServer(): if SEQUANT_PROJECT_DIR is set, statSync it; if not a directory, process.stderr.write naming the path and process.exit(1); else process.chdir().

    Phase 4: doctor check (AC-5)

    1. Add a check to doctorCommand (src/commands/doctor.ts) alongside the existing checkScriptsDevLinks-style helpers: detect node_modules/sequant in cwd's ancestor chain and $HOME, compare versions, warn with path + both versions + remediation.

    Phase 5: Tests

    1. AC-4's mutation-verified integration test (fake npx + fake shadowing node_modules/sequant).
    2. Extend scripts/plugin-mcp-pin.test.ts for the new .mcp.json shape (AC-2).
    3. Extend src/commands/serve.integration.test.ts for chdir + non-directory rejection (AC-3).
    4. New doctor.test.ts cases for the shadow-detection check (AC-5).

    Phase 6: Docs

    1. docs/troubleshooting.md "MCP Server Issues" entry; docs/features/mcp-server.md SEQUANT_PROJECT_DIR section (AC-6).

    Phase 7: Manual verification

    1. Confirm the dev repo's own MCP server still starts from the new root .mcp.json; record the exact command/output in the PR test plan (AC-7).

    Design Review

    1. Where does this logic belong? Launcher: new dependency-free file under scripts/ (parallel to the git-rooted .sh scripts already there, per docs/internal/plugin-path-audit.md). serve chdir: src/commands/serve.ts, which already owns process lifecycle (signal handlers, shutdown). Doctor check: src/commands/doctor.ts, alongside the existing checkScriptsDevLinks-shaped local-environment checks.
    2. What's the simplest correct approach? mkdtemp cwd forces npx's local-lookup to fail past the temp dir and hit its cache — no new dependency, no new npx flags. Rejected: npx-flag-only fixes (--prefix, npm_config_prefix) — the issue's own measured table already falsifies these; they all still ran the shadowed 1.20.1.
    3. What existing pattern does this follow? Version-pinning discipline from getSequantPackageSpec() (Reconsider sequant@latest pinning in generated MCP config (forces npx reinstall every release; surfaces as -32000) #793); serve's existing "report but never act on install status" philosophy for what may/may not block startup (fix(cli): preAction auto-sync fires on serve — the plugin's @latest MCP server silently rewrites .claude/hooks, skills, AGENTS.md in every project it starts in (#793 pin never ships via marketplace source "./") #988).
    4. What would a senior reviewer challenge? "Why mkdtemp per launch instead of one fixed cache-free dir?" — avoids concurrent-launch collisions and stale-dir cleanup races across repeated MCP reconnects.

    Feature Quality Planning

    Notable gaps:

    • Launcher must spawn with shell: false — the package spec and SEQUANT_PROJECT_DIR are not shell-escaped anywhere else in this plan.
    • doctor's version-compare needs a try/catch around JSON.parse of the shadowing node_modules/sequant/package.json (malformed/partial installs), matching the rest of doctor.ts's defensive style.
    • mkdtemp cleanup on exit should be best-effort (wrapped, non-fatal) — mirrors serve.ts's existing shutdown handlers.

    Derived ACs

    Source Derived AC Priority
    Windows open question AC-8: Launcher logs its resolved npx-launch cwd to stderr on every start Medium

    Open Questions

    1. Does ${CLAUDE_PLUGIN_ROOT:-.} actually substitute in .mcp.json, given the dual-use root file? Recommendation: spike it first (load as a plain project config with CLAUDE_PLUGIN_ROOT unset, confirm the fallback resolves rather than passing the literal string to node). Impact if wrong: a broken launcher invocation is worse than today's bug — it fails silently instead of at least attempting npx. Falls back to option (b) or (c) from the issue if the spike fails.
    2. Windows shadow via os.tmpdir() under the user profile. Recommendation: accept as documented (per the issue), launcher logs resolved cwd to stderr (Derived AC-8) for diagnosis rather than trying to defeat it.
    3. What does "or $HOME" mean for AC-5's doctor check? Recommendation: check cwd's ancestor chain (npm's own lookup order) and $HOME/node_modules/sequant directly, rather than guessing a broader heuristic. Impact if wrong: a narrower or wider check either misses real shadows or over-warns on unrelated global installs.
    4. Split vs. keep-together, given SCOPE_SPLIT_RECOMMENDED. Recommendation: keep together (see Scope Assessment above) — the pieces are load-bearing for each other. Impact if wrong: unnecessary process overhead from a second /spec cycle, but no correctness risk either way.

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled
    Reasoning: SCOPE_SPLIT_RECOMMENDED verdict (7 AC, 3 feature clusters, 7-directory spread) plus an unresolved Phase-0 spike (Open Question 1) that the rest of the plan depends on — both are exactly the "yellow/red scope" and "cross-cutting dependency" signals the loop exists for. testgen is not recommended: only one AC (AC-4) infers to an automated test method by itself, none declare Evidence:, and the issue carries only bug/cli labels (no enhancement/feature). No UI/frontend changes → no test phase. Not security-sensitive in the auth/payments/admin sense → no security-review phase.


    Label Review

    Current: bug, cli
    Recommended: bug, cli, complex (per the scope tool's directory-spread/feature-count signal — 7 AC alone wouldn't cross the 9+ threshold, but the actual footprint does: new script, .mcp.json shape change, two commands touched, two docs files, and a mutation-verified integration test)
    Reason: Reflects the real scope for anyone re-running /assess or /spec later, and keeps the quality-loop decision consistent if this issue is re-triaged.
    Quality Loop: Will auto-enable regardless of the label add, per the scope verdict above.

    → gh issue edit 1084 --add-label complex

  3. added
    planned
    on Sep 18, 2026
  4. added a commit that references this issue on Sep 18, 2026
  5. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #1084

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original scripts/mcp-launch.mjs launcher MET node:-builtins only; mkdtempSync cwd; spawn("npx", ["-y", spec, "serve"], { shell: false }); stdio inherited; SIGINT/SIGTERM forwarded and re-raised after dropping listeners.
    AC-2 Original Shipped .mcp.json launches through the launcher via ${CLAUDE_PLUGIN_ROOT}; pin still found NOT_MET Pin half ✅. Launch half ❌ — ${CLAUDE_PLUGIN_ROOT:-.} is not expanded to the plugin root by Claude Code. Empirically proven below.
    AC-3 Original serve chdirs to SEQUANT_PROJECT_DIR, rejects non-directory MET applyProjectDir() is the first statement in serveCommand; serve.integration.test.ts:165 asserts the stale-skills warning comes from the target project's manifest (cwd has none); :214 asserts named stderr + non-zero exit.
    AC-4 Original Mutation-verified shadow-repro integration test MET scripts/mcp-launch.integration.test.ts present; SEQUANT_MUTATION marker in PR body names a test file that is in the diff.
    AC-5 Original doctor warns on a shadowing local sequant MET checkShadowingLocalSequant() walks cwd's ancestor chain + $HOME; compares against the .mcp.json pin first (correctly handles the self-shadowing case where getVersion() equals the shadow by construction), falls back to the running CLI; names path, both versions, remediation.
    AC-6 Original Docs updated MET docs/troubleshooting.md:422 adds the CONNECTION_CLOSED entry with cause + one-line diagnosis + fix; docs/features/mcp-server.md:113 documents SEQUANT_PROJECT_DIR.
    AC-7 Original Dev repo's own MCP server still starts from the new root .mcp.json MET Substantively true — I verified the project-config path independently (probe below). But the PR's recorded evidence does not test it: it runs node ./scripts/mcp-launch.mjs directly, bypassing .mcp.json and therefore the placeholder engine entirely.
    Derived ACs
    AC-8 Derived (Windows open question) Launcher logs resolved npx-launch cwd to stderr MET mcp-launch: project dir <…>; launching npx from <…> on every start.

    Coverage: 7/8 AC items fully met — AC-2 NOT_MET
    Original ACs: 6/7 met · Derived ACs: 1/1 met


    Blocking finding — AC-2: ${CLAUDE_PLUGIN_ROOT:-.} does not resolve to the plugin root

    .mcp.json:5 ships:

    "args": ["${CLAUDE_PLUGIN_ROOT:-.}/scripts/mcp-launch.mjs", "[email protected]"]

    Claude Code expands plugin MCP configs through two stages (2.1.276 binary):

    1. oQ() — plugin placeholder substitution — matches /\$\{CLAUDE_PLUGIN_ROOT\}/g only. The exact-brace form. ${CLAUDE_PLUGIN_ROOT:-.} does not match, so this stage leaves it untouched.
    2. mF() — generic env expansion, /\$\{([A-Za-z_][A-Za-z0-9_]*(?::-[^}]*)?)\}/g — does understand :-, and reads n ?? process.env. CLAUDE_PLUGIN_ROOT is not in Claude Code's own process.env (it is injected into the child's env afterwards), so mF takes the :- default branch.

    Net: the plugin root is never substituted; the default is.

    Verified end-to-end with a throwaway local marketplace plugin (installed, probed, uninstalled; marketplace removed; temp dirs deleted):

    Plugin .mcp.json args[0] Open project cwd Result
    ${CLAUDE_PLUGIN_ROOT:-.}/scripts/probe.mjs /private/tmp server never started — probe never ran
    ${CLAUDE_PLUGIN_ROOT}/scripts/probe.mjs (control, same plugin) /private/tmp ✅ ran; argv[1] = /tmp/pr-probe-mkt/probeplugin/scripts/probe.mjs
    ${CLAUDE_PLUGIN_ROOT:-SENTINELDIR}/scripts/probe.mjs /private/tmp/probecwd ✅ ran, but argv[1] = /private/tmp/probecwd/**SENTINELDIR**/scripts/probe.mjs while the child's CLAUDE_PLUGIN_ROOT env var read /tmp/pr-probe-mkt/probeplugin

    The third row is conclusive: the default is taken, and it resolves against the open project's cwd, not the plugin root — even though the real plugin root is sitting right there in the child's environment.

    Consequence for shipped plugin users: args[0] becomes <open project>/./scripts/mcp-launch.mjs. No user project has that file → node exits ENOENT → Failed to reconnect to plugin:sequant:sequant: CONNECTION_CLOSED. That is the exact symptom in this issue's title. The fix does not reach the users it is for.

    Why it looked fine: in the sequant checkout, . is the repo root and scripts/mcp-launch.mjs does exist — so the dev-repo dual-use case works, and AC-7's hand-check exercised precisely that case. The one environment where the config resolves is the one that was tested.

    This is the spec's own Phase-0 spike (Open Question 1: "Test empirically before committing to option (a)", "Impact if wrong: a broken launcher invocation is worse than today's bug"). Option (a) does not work; the spike was not run.

    Remediation: use the exact ${CLAUDE_PLUGIN_ROOT} form and solve dual-use another way — spec options (b) (contributor-side .claude/settings.local.json override) or (c) (move marketplace source to a subdirectory so the shipped file is no longer the dev repo's own config). Note the exact form will not expand in the dev repo's project-config context either (oQ only runs for plugins, and mF has no value for it), so (a)-style single-file dual use appears unavailable regardless.


    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ⚠️ WARN scripts/plugin-mcp-pin.test.ts asserts args[0] equals the literal "${CLAUDE_PLUGIN_ROOT:-.}/scripts/mcp-launch.mjs". It pins the defect in place: the assertion passes precisely because the broken string is present, and would fail on the correct one.
    Coverage Depth ⚠️ WARN No test exercises placeholder resolution — only that a particular string is in the file. The gap between "the config contains X" and "Claude Code resolves X to a real path" is where this bug lives.
    Mock Hygiene ✅ OK mcp-launch.integration.test.ts uses a real fake npx on PATH + real fake shadowing node_modules/sequant — the issue's measured repro, not a synthetic simplification.
    Test Reliability ✅ OK 76/76 pass in 7.2s; no timing dependencies observed.

    CI Status

    Check State Bucket Impact
    build (22.x) SUCCESS pass ✅ MET
    typecheck, node-floor-guard, validate-skills, validate-plugin, Plugin Structure Validation, Hooks Validation, Setup Directory Creation, tautology-advisory, structural ($0, gates the PR) SUCCESS pass ✅ MET
    model-backed (secret-gated) SKIPPED skipping N/A

    CI Summary: 10 passed, 0 pending, 0 failed. mergeable: MERGEABLE, 0 commits behind main.

    Worth noting: CI is fully green and cannot catch this defect — Plugin Structure Validation and plugin-mcp-pin.test.ts both validate the shape of .mcp.json, never its resolution by the host.


    Quality Metrics

    Metric Value Status
    Type issues (any) 1 (pre-existing cast style in readProjectMcpPin) OK
    Deleted tests 0 OK
    Files changed 14 OK
    Lines added +865 OK
    Lines deleted -20 OK
    Security patterns 0 OK

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    scripts/mcp-launch.mjs Standard ✅ Yes mcp-launch.test.ts, mcp-launch.integration.test.ts
    src/commands/serve.ts Standard ✅ Yes serve.integration.test.ts
    src/commands/doctor.ts Standard ✅ Yes doctor.test.ts
    src/lib/mcp-config.ts Standard ✅ Yes covered via doctor.test.ts

    Coverage: 4/4 changed source files have tests. Critical paths without tests: none.


    Code Review

    Strengths:

    • The signal re-raise in mcp-launch.mjs removes its own SIGINT/SIGTERM listeners before process.kill(process.pid, signal). Without that, the listener re-entrantly swallows the signal and the launcher exits 0 — silently reporting success for a killed server. Genuinely subtle, and the comment explains the why.
    • readProjectMcpPin() comparing against the .mcp.json pin rather than only getVersion() is the right call, for the reason the docstring gives: run from inside a shadowed project, doctor is the shadow, so getVersion() can never disagree with it.
    • shell: false throughout, so the package spec and SEQUANT_PROJECT_DIR never reach a shell parser.
    • resolveNpxCommand() handling npx.cmd on Windows is a real regression that shell: false would otherwise have introduced.

    Issues:

    • .mcp.json:5 — ${CLAUDE_PLUGIN_ROOT:-.} does not resolve to the plugin root (blocking, above).
    • scripts/plugin-mcp-pin.test.ts asserts the broken literal, locking the defect in.
    • templates/mcp.json (the OUTPUT_DIR marketplace copy) and getSequantMcpConfig() in src/lib/mcp-config.ts still invoke npx directly and retain the same shadowing exposure. Both are explicitly flagged as out of scope in the PR body — correct disclosure, no action needed here.

    Suggestions:

    • Add a test that resolves the placeholder the way the host does, rather than string-matching the config.

    Risk Assessment

    • Likely failure mode: The shipped plugin fails to start its MCP server in every user project, with the same CONNECTION_CLOSED message this issue was filed about — now for a different reason (missing launcher path instead of a shadowed pin). Blast radius is larger than the original bug: the original needed a stale local sequant to trigger; this triggers unconditionally.
    • Not tested: Placeholder resolution by the Claude Code host. Every existing assertion is a string match on file contents.
    • Sibling sites considered: templates/mcp.json and getSequantMcpConfig() (src/lib/mcp-config.ts) — both still launch npx directly and carry the same shadowing exposure. Both are disclosed as out of scope in the PR body and in the issue's own scope note; no new follow-up needed beyond what's already recorded.
    • Sibling-line audit: .mcp.json has a single server entry and one placeholder-bearing arg; ${CLAUDE_PROJECT_DIR} in the same file uses the exact-brace form and does resolve (confirmed by probe — the child received CLAUDE_PROJECT_DIR correctly). So the defect is isolated to the one :- usage, not a pattern repeated in the file.

    Execution Evidence

    Test Type Command Exit Code Result
    Unit + integration npx vitest run scripts/mcp-launch*.test.ts scripts/plugin-mcp-pin.test.ts src/commands/serve.integration.test.ts src/commands/doctor.test.ts 0 76/76 passed (7.2s)
    Host resolution probe local marketplace plugin, 3 variants (see AC-2) — :- form fails; exact-brace form works

    Evidence status: Complete


    Trust-Boundary Check

    Finding: Clean — the diff implements only product requirements from the issue's AC list. No agent-directed instruction (command execution, network fetch, file exfiltration, instruction override) appears in the issue body or its single comment, and nothing in the diff traces to one. The issue's process guidance (mutation-verified marker, scope note) is ordinary maintainer direction.

    Status: Clean


    Behavior-Rule Survival Check

    AC Triggered? Survivors Status
    AC-1..AC-8 No — N/A

    No AC crosses the ≥2-distinct-keyword threshold (default/always/never/rule/behavior/skip); these ACs describe new mechanism, not a rule change replacing an old one.

    Status: N/A


    Declared-Evidence Execution

    AC Evidence Executed? Result
    — No AC uses the Evidence: declared-verification clause — N/A (the /spec comment states this explicitly)
    PR test plan npm run build, npm run lint, npm test Checked [x] by author Targeted suite re-run here: 76/76 pass. No unchecked - [ ] boxes in the test plan.

    Status: N/A


    Mutation Verification

    AC Gate Test? Marker Status
    AC-4 Yes scripts/mcp-launch.integration.test.ts > spawns npx from a dir outside the shadowing project, with the pinned spec Verified — test file is present in the diff

    Status: Verified


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (fix(#1084): commits)
    [Unreleased] entry ✅ Present under ### Fixed
    Entry format ✅ Valid (includes (#1084))

    Result: CHANGELOG requirements met


    Skill Command Verification

    Result: N/A — no .claude/skills/**/*.md files changed.

    Detection Pattern Verification

    Result: N/A — no skill markdown changed, so no regex/grep/awk/jq/sed pattern changes in skill files.

    CLI Registration Verification

    Result: N/A — no RunOptions-style option interface modified. SEQUANT_PROJECT_DIR is an environment variable, not a CLI flag, and is read directly in serve.ts.

    Call-Site Review

    New exported functions detected: 3

    Function Call Sites Loop? Conditions AC Match
    resolveNpxCommand() mcp-launch.mjs:64 No none ✅ AC-1
    checkShadowingLocalSequant() doctor.ts:565 No (results iterated, call is single) unconditional ✅ AC-5
    readProjectMcpPin() doctor.ts (checkShadowingLocalSequant) No none ✅ AC-5

    No call site is missing an AC-required guard; no dead exports.

    Precheck Findings

    Section Status Surfaced
    Fixtures pass motivating-example fixtures extracted (issue's measured npx table)
    Sibling-grep pass changed identifiers surfaced to §5
    AC literal-diff pass issue AC-1..7 all present in PR body (PR adds AC-8 derived)

    Source: .sequant/gap-precheck.json (schemaVersion 1)

    Smoke Test

    Test Command Result Notes
    Happy path (dev repo) project .mcp.json with ${CLAUDE_PLUGIN_ROOT:-.} ✅ resolves to repo root; launcher runs
    Real path (plugin) installed plugin .mcp.json, same string ❌ server never starts — AC-2 blocking finding
    Control installed plugin with ${CLAUDE_PLUGIN_ROOT} ✅ resolves to plugin root

    Smoke Test Status: Complete (and it is what surfaced the blocking finding)

    Manual Test ACs

    AC Verification Method Runtime Test Status Evidence
    AC-6 Manual Test (content check) ✅ Executed Read both docs; content present, not just files
    AC-7 Manual Test ✅ Executed Probed the project-config path directly rather than accepting the PR's launcher-direct command

    Manual Test Enforcement: 2/2 manual-test ACs verified at runtime


    Adversarial Re-Read

    Findings:

    1. Verbatim motivating-example fixtures run. The issue's measured table (npx -y [email protected] --version → 1.20.1 from a shadowed project) is reproduced by mcp-launch.integration.test.ts with a real fake npx and a real fake shadowing node_modules/sequant — not a synthetic simplification. Passes.
    2. Evidence claim that is not a validation. AC-7's recorded evidence — CLAUDE_PROJECT_DIR=<repo root> node ./scripts/mcp-launch.mjs [email protected] — hard-codes the launcher path and so validates the launcher, not the .mcp.json placeholder it claims to verify. The one thing AC-7 exists to check is the thing that command cannot check. Re-running it properly is what exposed AC-2.
    3. AC marked MET without the check its text required. AC-2 says "with ${CLAUDE_PLUGIN_ROOT}"; the PR marks it ✅ on the strength of a test that asserts a different string is present in the file. Literal AC verification fails.
    4. Sibling sites cited — see Risk Assessment: templates/mcp.json, getSequantMcpConfig() (cross-file); ${CLAUDE_PROJECT_DIR} in the same file (intra-file, correct form, confirmed working).
    5. Non-Goals intact. The issue's scope note ("does not touch how phases launch MCP servers for agents", "does not fix already-installed old versions") holds — getPhaseMcpServersConfig is untouched.
    6. Process state — worktree verified against issue fix(mcp): plugin MCP server dies with CONNECTION_CLOSED when the open project has an older sequant in node_modules — npx ignores the pin and runs the local copy #1084, 0 commits behind main, tree clean, no stashes touched.

    Status: Severe Gap (an AC marked MET without the runtime check its own text required; that check fails when run)


    Verdict: AC_NOT_MET

    AC-2 is NOT_MET. The shipped .mcp.json uses ${CLAUDE_PLUGIN_ROOT:-.}, which Claude Code resolves to the :- default, against the open project's cwd — never to the plugin root. For plugin users the launcher path does not exist and the MCP server dies with CONNECTION_CLOSED: the exact symptom this issue was filed to fix, now unconditional rather than requiring a stale local sequant.

    Everything else is in good shape — AC-1, AC-3 through AC-8 are met, the launcher itself is careful work (the signal re-raise and the pin-vs-running-version comparator are both non-obvious and correct), docs are thorough, CI is green, and the mutation-verification record is valid. The defect is confined to one string in one file.

    Documentation

    • docs/troubleshooting.md updated
    • docs/features/mcp-server.md updated
    • CHANGELOG entry added

    Next Steps

    1. Fix .mcp.json:5 — replace ${CLAUDE_PLUGIN_ROOT:-.} with the exact ${CLAUDE_PLUGIN_ROOT} form.
    2. Re-decide dual use. The exact form will not expand in the dev repo's project-config context either, so spec option (a) is unavailable in both directions. Take option (b) (contributor .claude/settings.local.json override) or (c) (move marketplace source to a subdirectory).
    3. Replace the string-match assertion in scripts/plugin-mcp-pin.test.ts with one that cannot pass on an unresolvable placeholder — at minimum assert the exact-brace form; better, assert the path resolves to an existing file under a simulated plugin root.
    4. Re-verify AC-7 through .mcp.json, not by invoking the launcher directly, and record that command in the test plan.
  6. added
    needs-work
    on Sep 18, 2026
  7. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    Owner decision: inline the launcher (resolves QA's blocking AC-2 finding)

    ${CLAUDE_PLUGIN_ROOT:-.} does not resolve to the plugin root (QA probe above), and the exact form does not expand in the dev repo's project-config context, so a file-path launcher cannot serve both. Decision:

    • Ship the launcher inline: "command": "node", "args": ["-e", "<launcher source>", "sequant@<pin>"]. No file path, no placeholder.
    • Drop the SEQUANT_PROJECT_DIR placeholder handoff from .mcp.json. The launcher captures its own process.cwd() (the open project in both plugin and project-config contexts) and passes it to the child as SEQUANT_PROJECT_DIR; serve keeps honoring that env var.
    • Keep scripts/mcp-launch.mjs as the tested source of truth. Add a test asserting the inline args[1] in .mcp.json is byte-identical to a generated/minified form of it, so the two cannot drift. prepare-marketplace.ts keeps stamping the pin in args[2].
    • Replace the pin test's literal-string assertion with one that fails on an unresolvable placeholder (no ${ in args).
    • AC-7 must be re-verified through .mcp.json (config resolved by the host), not by invoking the launcher directly, in both the plugin and dev-repo contexts.

    AC-2 is amended accordingly: the shipped .mcp.json launches the server via an inline node -e launcher with no placeholders in command or args.

  8. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/1 met

    Gaps:

    • AC-7's recorded manual-verification evidence does not exercise the .mcp.json ${CLAUDE_PLUGIN_ROOT:-.} expansion the AC exists to validate; QA independently verified the substance via
    • New exported function readProjectMcpPin (file I/O, JSON parse, wrapped/flat shape fallback) has no direct test and is mocked at its only call site
    • syncSequantMcpPin is now undocumented and its JSDoc block is attached to the wrong function
    • The official-plugin-directory dist copy and project configs still spawn npx directly from the project and retain the fix(mcp): plugin MCP server dies with CONNECTION_CLOSED when the open project has an older sequant in node_modules — npx ignores the pin and runs the local copy #1084 shadowing exposure; the issue asked for a separate follow-up issue and none was filed
    • On Windows os.tmpdir() sits under the user profile, so a home-stray %USERPROFILE%\node_modules\sequant still shadows the launcher's isolated cwd — the issue conditioned acceptance of this residual risk on documenting it
    • src/lib/mcp-config.ts: inserting readProjectMcpPin between syncSequantMcpPin's JSDoc block and its declaration orphaned that doc comment. syncSequantMcpPin is now undocumented, and its doc block sits above the wrong function.
    • readProjectMcpPin is a new exported function doing filesystem I/O, JSON parsing, and a wrapped/flat shape fallback, with no direct test. I exercised it manually across 7 shapes (new launcher / init --mcp / flat plugin / no entry / non-array args / missing file / broken JSON) — all correct — but nothing in the suite would catch a regression.

    Suggestions:

    • Move the orphaned JSDoc back above syncSequantMcpPin and add a readProjectMcpPin block to src/lib/mcp-config.test.ts.
    • Correct the AC-7 line in the PR test plan (see Adversarial Re-Read).
    • File the follow-up issue the issue body itself asked for (getSequantMcpConfig / templates/mcp.json).
  9. admarble commented on Sep 18, 2026

    @admarble
    ContributorAuthor

    Run 3 (exec → qa, 2026-09-18 23:20–23:34) is a false positive — tree unchanged

    • exec finished in 35 s with no commit: the branch is still at dfa23bca, and .mcp.json still ships ${CLAUDE_PLUGIN_ROOT:-.} plus the ${CLAUDE_PROJECT_DIR} env placeholder.
    • The QA comment above (AC_MET_BUT_NOT_A_PLUS) says it "independently verified the substance" of the :- expansion. That contradicts the previous QA's controlled probe (three rows, throwaway marketplace plugin), which showed the default is taken and resolved against the open project. The earlier probe is the stronger evidence; treat this verdict as void.
    • The owner decision (inline node -e launcher) was not acted on. AC-2 and AC-7 in the issue body are now rewritten to state it literally, so the current tree does not satisfy them. Re-running exec → qa.
  10. added 3 commits that reference this issue on Sep 19, 2026
  11. admarble commented on Sep 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/4 met

    Gaps:

    • New scripts/ functionality shipped without a /verify execution-verification record on the issue, and the change is not an approved 11a override category
    • Between merge and the next release the shipped .mcp.json launches a serve that ignores SEQUANT_PROJECT_DIR, so the dev repo's own MCP tools and resources silently operate on the launcher's empty mkdtemp dir instead of the open project
    • AC-3's named test artifact (assert the resource reports that project's manifest) exists only as this QA pass's manual run, not as a regression test in the repo
    • Two cross-file sibling sites carry the identical npx-shadowing root cause and are not routed through the launcher; declared out of scope but tracked only in the PR body, not in an issue
    • The launcher's isolated mkdtemp directory leaks whenever the launcher process is SIGKILLed rather than exiting through its child-exit path
    • .mcp.json pins [email protected], and the published 2.15.1 serve predates applyProjectDir(). End-to-end today the launcher works but the server ignores SEQUANT_PROJECT_DIR and stays in the mkdtemp dir. Measured: through the Claude-Code-resolved config, sequant://install returns {"installed":false} for a project that returns {"installed":true,"currentVersion":"0.0.9"} when the env var is honored. See Risk Assessment.
    • AC-3's prescribed test artifact ("assert the resource reports that project's manifest") is implemented as a stderr stale-skills-warning assertion. Equivalent in mechanism, but no regression test actually reads sequant://install under SEQUANT_PROJECT_DIR.
    • The mkdtemp dir is only removed in the child's exit handler, so a SIGKILL of the launcher leaks it. Two empty sequant-mcp-launch-* dirs from the exec phase's own probes were still sitting in tmpdir when I looked.

    Suggestions:

    • scripts/generate-mcp-launch-inline.mjs isn't wired into any build/release step — .mcp.json regeneration is manual, with the byte-identical test as the only guard. That's an acceptable gate, but a npm run script (or a prepare-marketplace step) would make the intended workflow discoverable.
    • plugin-mcp-pin.test.ts finds the pin by args.find(startsWith("sequant@")) where AC-2 says args[2]; asserting the index would also pin the arg order the launcher depends on (process.argv[1]).
  12. admarble commented on Sep 19, 2026

    @admarble
    ContributorAuthor

    Execution Verification

    Command: cd ~/Projects/sequant-landing && node -e "$(jq -r '.mcpServers.sequant.args[1]' <worktree>/.mcp.json)" [email protected] fed one MCP initialize request on stdin
    Result: Verified — executed by Claude in the #1084 session on 2026-09-19 against branch head 68db25fd; outputs below are verbatim. sequant-landing carries [email protected] in node_modules (the original CONNECTION_CLOSED reproducer); that copy never ran.

    Execution Output (click to expand)

    Exit code: 0 (server stayed up until stdin closed)
    Duration: ~2 s

    stderr:

    mcp-launch: project dir /Users/tony/Projects/sequant-landing; launching npx from /var/folders/2_/fy3vqfl529g4x00jb57j3vth0000gp/T/sequant-mcp-launch-<random>
    Sequant MCP server started (stdio)
    

    stdout (initialize reply, result.serverInfo):

    {'name': 'sequant', 'version': '2.15.1'}
    

    Command: claude -p "reply with the single word ok" --mcp-config <worktree>/.mcp.json --strict-mcp-config --output-format stream-json --verbose --max-turns 1, run with cwd = the worktree and again with cwd = ~/Projects/sequant-landing
    Result: Verified — Claude Code's own MCP loader resolved the shipped config (no placeholders) and reported the server connected in both contexts.

    Execution Output (click to expand)

    Exit code: 0 (both)

    init message, both runs:

    "mcp_servers":[{"name":"sequant","status":"connected","source":"dynamic"}]
    

    Command: npm run mcp-launch:inline (twice)
    Result: Verified — first run rewrote .mcp.json args[1], second run .mcp.json already up to date; scripts/plugin-mcp-pin.test.ts byte-identity test green afterwards.

  13. added a commit that references this issue on Sep 19, 2026
  14. admarble commented on Sep 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/6 met

    Gaps:

    • On Windows the launcher will likely fail at the spawn call with EINVAL, reproducing CONNECTION_CLOSED from a new cause for plugin users who previously worked via the shell-resolved npx command.
    • A sibling launcher can sweep the live launch dir of a session older than an hour, which the docstring's stated safety property does not cover (impact negligible because serve chdirs to the project immediately).
    • The launch-dir cleanup assertion is conditional and can be skipped without failing the test.
    • scripts/mcp-launch.mjs:117 spawns resolveNpxCommand() → "npx.cmd" on Windows with shell: false. Node's CVE-2024-27980 hardening rejects spawning .cmd/.bat without shell: true; the engine floor (>=22.13.0) is entirely inside the affected range. The repo's own sibling site src/lib/merge-check/combined-branch-test.ts:108 hit the identical ".cmd shim" problem and resolved it as shell: process.platform === "win32", with the same "command is always a constant … nothing to inject here" reasoning this launcher's comment rejects. Details in Adversarial Re-Read.
    • sweepStaleLaunchDirs removes any empty sequant-mcp-launch-* dir older than an hour. A session open longer than an hour has a launch dir that is still empty and whose mtime never advances, so a sibling launcher will sweep a live one. The docstring's stated safety property covers only freshly-created siblings.

    Suggestions:

    • generate-mcp-launch-inline.mjs:79 uses single-occurrence .replace("process.argv[2]", …). The guard above only checks includes, so a future second argv[2] would be silently left un-rewritten. replaceAll (or a count assertion) would keep the refusing-transformer property intact.
    • docs/troubleshooting.md states "v2.16.0+"; the current version is 2.15.1. Worth confirming at release time that the version that ships this is in fact a minor bump.
  15. added a commit that references this issue on Sep 19, 2026
  16. admarble commented on Sep 19, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

  17. added a commit that references this issue on Sep 19, 2026
  18. added 2 commits that reference this issue on Oct 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugclineeds-workplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions