Skip to content

[PR] fix: re-bind the claude MCP shim to the host's current session after /clear - #6478

Closed
ranxianglei wants to merge 2 commits into
masterfrom
2026-11-13_claude-clear-mcp-rebind
Closed

ranxianglei wants to merge 2 commits into
masterfrom
2026-11-13_claude-clear-mcp-rebind

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

Claude Code /clear (or /new) starts a new session id but keeps the stdio MCP child running, so the spawn-time CLAUDE_CODE_SESSION_ID env (mcp.ts's CONVERSATION_FROM_ENV) goes stale. Neither existing recovery path fires:

Result: after /clear, bili MCP tools silently run against the old session, and the new session is never registered → it stays in proxy mode (no [acp-usage], inputTokens:0). The only reliable new-session signal available to the long-lived shim is ~/.claude/sessions/<host-pid>.json (rewritten on /clear; the host pid is stable for the child's lifetime).

Fix

The claude entry (src/claude-mcp-entry.ts) now injects a resolver that reads the host's current session id from <CLAUDE_CONFIG_DIR|~/.claude>/sessions/<host-pid>.json. On each tools/call, src/mcp.ts re-reads it and, when it differs from the bound id, re-binds the module conversationId and re-registers the new session (POST /__bili/plugin/register {conversationId, agent:"mcp", identity:true}) so the new session enters plugin mode immediately.

Why it's safe / scoped

  • The resolver is injected only by the claude entry, so dist/mcp.js (shared by codex/zcode/kimi) is untouched — those hosts never set the resolver, so the re-bind seam is a no-op for them. Verified in the build: dist/mcp.js carries the seam but none of the claude resolver functions.
  • Defensive about the file shape (sessionId/session_id/id, UUID-ish shape check; any read/parse/shape failure → undefined = "no re-bind", never a crash). Worst case the resolver returns undefined → the bug persists exactly as today, no regression.
  • Identity-bound hosts only (gated on CLAUDE_CODE_SESSION_ID); a per-call / native override still wins for the current call and never touches the global binding.
  • No kernel changes.

Config surface

No new config field, env var, or default. The re-bind is gated on the existing identity-binding (on by default for a claude shim, consistent with the #656 orphan-adopt default-on behavior). A single claude process = one MCP child = one session, so there is no multi-session sibling to mis-bind.

Tests

tests/issue6361-claude-clear-rebind.test.ts (22 tests, both gate directions per #3617):

  • resolver — reads + validates the sessions file (valid id, session_id/id fallbacks, sessionId precedence, missing file, malformed JSON, non-object, missing field, non-string field, invalid shape, whitespace trim); wires CLAUDE_CONFIG_DIR + the (cached) host pid.
  • shim — maybeRebindConversation re-binds exactly when the id changed; no re-bind for same-id / no-resolver / throwing-resolver / non-identity; the tools/call sequence carries the re-bound id to the proxy; a re-bind fires a register for the new session.

Verified locally: npm run typecheck (exit 0), npm run build (exit 0), targeted test green, related existing suites (issue4168, claude-mcp-entry, issue4580, mcp-native-thread) green on the rebased head. Full-suite verdict = remote CI.

Closes #6361

@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-11-13_claude-clear-mcp-rebind (9378f68)

Latest build — install this exact version

npm install -g billion-context@0.0.9454-pr.6478.fcc8c58

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Recent builds (commit → version)

commit version build
9378f68 billion-context@0.0.9454-pr.6478.fcc8c58 build
5fccc57 billion-context@0.0.9438-pr.6478.24cbb15 build

Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr6478.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei ranxianglei changed the title fix: re-bind the claude MCP shim to the host's current session after /clear [PR] fix: re-bind the claude MCP shim to the host's current session after /clear Nov 13, 2026
ci-check added 2 commits November 13, 2026 11:42
…/clear

Claude Code /clear (or /new) starts a NEW session id but keeps the stdio MCP
child running, so the spawn-time CLAUDE_CODE_SESSION_ID env (mcp.ts's
CONVERSATION_FROM_ENV) goes stale and neither recovery path fires: the #656 404
adoption needs the bound id to be unknown (it is still registered + active, so
calls succeed against it) and the #4168 409 re-bind needs a witness conflict
(none occurs). Tools silently run against the OLD session and the NEW session
never enters plugin mode.

The claude entry now injects a resolver that reads the host's CURRENT session
id from <CLAUDE_CONFIG_DIR|~/.claude>/sessions/<host-pid>.json (rewritten on
/clear; the host pid is stable for this child's lifetime). On each tools/call
the shim re-reads it and, when it differs from the bound id, re-binds +
re-registers so the new session enters plugin mode. Identity-bound hosts only;
dist/mcp.js (codex/zcode/kimi) is untouched — the resolver is injected solely
by the claude entry.

Closes #6361
@ranxianglei
ranxianglei force-pushed the 2026-11-13_claude-clear-mcp-rebind branch from 5fccc57 to 9378f68 Compare November 13, 2026 03:49
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

查重: 不重复 — no other open PR/issue targets the claude /clear re-bind mechanism (checked live open [PR] rows + issue/PR search). Nearest neighbors #656 (404 orphan-adopt) and #4168 (409 witness re-bind) are same-family prior mechanisms that this PR explicitly complements, not duplicates.

Independent review of PR #6478 (Closes #6361)

① Direction — correct. Verified the diagnosis against the code: after /clear, the spawn-time CLAUDE_CODE_SESSION_ID goes stale and neither recovery path fires — #656's 404 adoption needs the bound id to be unknown, but the old session is still registered so tool calls succeed against it; #4168's 409 needs a witness conflict, and none occurs. The fix attacks the root cause (stale spawn-time env) by re-reading the host's current session id per tools/call. Verified the re-register works for an already-trafficked session: POST /__bili/plugin/register {identity:true} → queuePluginRegister → registeredIds, consumed at src/server/handle.ts:1833-1840 (consumePluginRegisterFor(clientConv ?? conversation)) on every model request — no requests===0 gate — flipping the session to plugin mode. Matches the reporter's manual verification.

② Regression review — existing behaviors checked, all preserved:

③ Code review — sound. Per-call file re-read (one small JSON) beats file-watching (no watcher lifecycle, no missed events); SESSION_ID_RE is permissive for real ids, rejects garbage; stderr logging is the right channel (stdout is JSON-RPC); fire-and-forget register with 5s timeout mirrors the initialize path (src/mcp.ts:363-371). Clean naming, no dead code, no new deps.

④ Test review — one gap found and fixed. The main file (22 tests) is real: resolver matrix uses actual mkdtemp I/O, shim tests drive a real HTTP mock on 127.0.0.1:0, register body pinned. Gap: the PR body claims "no re-bind for … non-identity" is tested, but no such test existed — IDENTITY_BINDING is a module-load constant, and that file sets the env at load. Added tests/issue6361-claude-clear-rebind-nonidentity.test.ts (own process, env deleted before import, mirroring the issue4580 precedent): resolver armed + fresh id available → maybeRebindConversation() returns undefined and the resolver is never called (pins the gate short-circuit). Both gate directions now asserted per #3617.

Local evidence (rebased head 9378f68): typecheck clean; issue6361-claude-clear-rebind 22/22 + new non-identity test 1/1; related suites (issue4168, claude-mcp-entry, issue4580, mcp-native-thread) 52/52.

Actions taken on the PR branch:

  1. Rebased onto current master (was 17 commits behind; no file contention) — 5fccc57ab9 → 029b7e09da.
  2. Added the missing non-identity gate test — commit 9378f6875e.

CI: green on the pre-rebase head (30/30 checks, 0 failed); the rebased head's run is in flight — full-suite verdict lands there.


中文八问

  1. 是什么问题:claude /clear 后 MCP shim 仍绑定旧会话 id,新会话永远进不了 plugin 模式(无 [acp-usage]、inputTokens:0)。
  2. 什么原因导致的:CLAUDE_CODE_SESSION_ID 是 spawn 时注入的 env,/clear 后不变;两条既有恢复路径都不触发——MCP tools fail with 'unknown plugin conversation' after Claude Code --resume (shim holds a stale session id) #656 的 404 收养要求绑定 id 是"未知"的,但旧会话仍注册着、工具调用会成功打到它身上;[Bug] Claude Code native compaction: compress/acp_status permanently broken after resumption — outbound tool witness doe | [Bug] Claude Code 原生 compaction 续接后 compress/acp_status 永久失效:outbound tool witness does not match conversationId,ref 空间为空 #4168 的 409 重绑要求出现冲突见证,而这里没有。
  3. 影响范围与严重程度:仅 claude MCP 车道 + /clear 场景;触发后新会话压缩能力失效(功能不可用),旧会话行为不变、其他车道不受影响——特定条件下功能失效,非全局故障。判 p2。
  4. 怎么修复的:每次 tools/call 重读宿主当前会话 id(<CLAUDE_CONFIG_DIR|~/.claude>/sessions/<host-pid>.json),与绑定 id 不同则重绑 + 重新注册(identity:true),新会话立即进入 plugin 模式;resolver 只在 claude 入口接线,其余车道该缝为 no-op。
  5. 是否有回归问题:逐项核查既有行为——codex/zcode/kimi(seam no-op,构建级验证 dist/mcp.js 无 resolver 代码)、非 identity 宿主(gate no-op)、per-call 覆盖仍优先、[bug] Claude Code Task subagents: bili MCP tools run against the root session (process-wide CLAUDE_CODE_SESSION_ID) → 409 witness conflicts, phantom range errors, and a subagent fold applied to the parent | Claude Code 子代理的 MCP 压缩落到父会话 #4580 toolCallId 路由不受影响、MCP tools fail with 'unknown plugin conversation' after Claude Code --resume (shim holds a stale session id) #656/[Bug] Claude Code native compaction: compress/acp_status permanently broken after resumption — outbound tool witness doe | [Bug] Claude Code 原生 compaction 续接后 compress/acp_status 永久失效:outbound tool witness does not match conversationId,ref 空间为空 #4168 路径保留、resolver 失败退化为现状——未发现回归。发现一处测试缺口(非 identity 方向未测但 PR 声称已测),已在 review 中补上。
  6. 是否破坏缓存:不涉及——不动缓存/重试/增量游标/去重键;重注册只改会话的 plugin 模式绑定。
  7. 是否改了设计方向:不涉及——既有 identity-binding 机制的增量扩展,无架构/边界/数据流变化,无 kernel 改动。
  8. 是否引入了新的配置:无——不新增 env/config/默认值;复用既有 identity-binding(claude shim 默认开,与 MCP tools fail with 'unknown plugin conversation' after Claude Code --resume (shim holds a stale session id) #656 orphan-adopt 默认开一致)。

判定:可合并 —— 待 rebased head 的 CI 转绿;本地定向验证全绿,机制与范围均已独立核实。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

CI on the rebased head 9378f6875e is green: 30/30 checks, 0 failed — all test shards (ubuntu/windows × node 22/24), static-gates, mysql-contract, lifecycle-ledger-guard, gate, docs-sync pass; e2e lanes skipped per the file-list gates (same as the pre-rebase head — the PR touches no e2e-trigger file).

Review verdict stands: mergeable — ready for you to merge: #6478

@ranxianglei

Copy link
Copy Markdown
Owner Author

此 PR 的内容已整体进入批量 PR #7107(逐 commit 原样 cherry-pick,作者与 commit message 保留,已合并)。

This PR's changes have been merged verbatim (commit-by-commit, authorship preserved) via the batch PR #7107. Closing this to avoid a duplicate merge. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

1 participant