Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions src/claude-mcp-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@
// Logs go through the shared bili.log tee because claude does not surface this
// child's stderr.

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { resolveProxyOrigin, runMcpStdio } from "./mcp.js";
import { resolveProxyOrigin, runMcpStdio, setClaudeSessionResolver } from "./mcp.js";
import { configureLogger, log as teeLog } from "./logger.js";
import { configureLogRetention } from "./log-retention.js";
import { logRetentionPolicy } from "./knobs.js";
import { defaultLogFile } from "./paths.js";
import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning, healthUrl } from "./launcher.js";
import { chooseWatchdogParentPid, planClaudeNativeBootstrap } from "./claude-native-bootstrap.js";
import { chooseWatchdogParentPid, planClaudeNativeBootstrap, resolveClaudeHostPid } from "./claude-native-bootstrap.js";
import { repinClaudeManagedBaseUrl, readClaudeManagedBaseUrl } from "./plugin-install.js";

const WATCHDOG_INTERVAL_MS = 30000;
Expand All @@ -31,6 +33,76 @@ function proxyScriptPath(): string {
return path.join(path.dirname(fileURLToPath(import.meta.url)), "index.js");
}

// #6361: the host's CURRENT session id. claude /clear (or /new) starts a new
// session id but keeps this stdio child running, so the spawn-time
// CLAUDE_CODE_SESSION_ID env (mcp.ts's CONVERSATION_FROM_ENV) goes stale. The
// live id is rewritten by claude into <CLAUDE_CONFIG_DIR|~/.claude>/sessions/
// <host-pid>.json on every /clear; the host pid is stable for this child's
// lifetime. mcp.ts's tools/call path re-reads this on each call and re-binds on
// change. Defensive about the file shape (sessionId/session_id/id; any read,
// parse, or shape failure → undefined, which means "no re-bind", never a crash).
const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{3,255}$/;

function claudeConfigDir(): string {
const fromEnv = process.env.CLAUDE_CONFIG_DIR?.trim();
if (fromEnv && fromEnv.length > 0) return fromEnv;
return path.join(os.homedir(), ".claude");
}

/** Read + validate the session id from one claude sessions file. Exported for
* tests (pure: a config dir + pid in, an id or undefined out). */
export function readClaudeSessionFile(configDir: string, pid: number): string | undefined {
let raw: string;
try {
raw = fs.readFileSync(path.join(configDir, "sessions", `${pid}.json`), "utf8");
} catch {
return undefined;
}
let data: unknown;
try {
data = JSON.parse(raw);
} catch {
return undefined;
}
if (typeof data !== "object" || data === null) return undefined;
const obj = data as Record<string, unknown>;
const sid = obj.sessionId ?? obj.session_id ?? obj.id;
if (typeof sid !== "string") return undefined;
const trimmed = sid.trim();
return SESSION_ID_RE.test(trimmed) ? trimmed : undefined;
}

let cachedHostPid: number | undefined;
let hostPidResolved = false;

function hostPid(): number | undefined {
if (!hostPidResolved) {
hostPidResolved = true;
cachedHostPid = resolveClaudeHostPid();
}
return cachedHostPid;
}

/** The full resolver injected into mcp.ts: resolve the claude host pid (cached
* — it is stable for this child's lifetime) and read its current session id. */
export function readClaudeSessionId(): string | undefined {
const pid = hostPid();
if (pid === undefined) return undefined;
return readClaudeSessionFile(claudeConfigDir(), pid);
}

// Test seams: the host pid is resolved once and cached; reset or pin it between
// cases (pinning bypasses the real process-tree walk).
export function _resetClaudeHostPidForTest(): void {
hostPidResolved = false;
cachedHostPid = undefined;
}

export function _setClaudeHostPidForTest(pid: number | undefined): void {
hostPidResolved = true;
cachedHostPid = pid;
}

async function probeProxyHealth(origin: string): Promise<boolean> {
try {
const res = await fetch(healthUrl(origin), { signal: AbortSignal.timeout(2000) });
Expand Down Expand Up @@ -130,6 +202,10 @@ export async function main(opts: WatchdogDeps & { runStdio?: () => void } = {}):
configureLogRetention(logRetentionPolicy());
configureLogger(defaultLogFile());
const log = (msg: string) => teeLog("info", `[bili-claude-mcp] ${msg}`);
// #6361: arm the /clear session re-bind in every posture (attach/passthrough
// included — the tool calls still need to follow the host's current session).
// mcp.ts ignores it unless the shim is identity-bound (CLAUDE_CODE_SESSION_ID).
setClaudeSessionResolver(readClaudeSessionId);
const plan = planClaudeNativeBootstrap(process.env);
if (plan.action !== "start") {
// attach (BILLION_CONTEXT_PROXY / BILI_PROVIDER_REWRITES) or passthrough
Expand Down
58 changes: 58 additions & 0 deletions src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,60 @@ export function _resetMcpBindingForTest(nextConversationId?: string): void {
conversationId = nextConversationId;
}

// #6361: claude /clear (or /new) starts a NEW session id but keeps this stdio
// child running — the spawn-time CLAUDE_CODE_SESSION_ID env (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).
// The host's CURRENT session id lives in <CLAUDE_CONFIG_DIR|~/.claude>/sessions/
// <host-pid>.json (rewritten on /clear; the host pid is stable for this child's
// lifetime). The claude entry (claude-mcp-entry.ts) injects a resolver that reads
// it; on each tools/call we re-read it and, when it differs from the bound id,
// re-bind + re-register so the new session enters plugin mode. Identity-bound
// hosts only (the resolver is injected solely by the claude entry); a per-call /
// native override still wins for the current call — it never touches this global.
let claudeSessionResolver: (() => string | undefined) | undefined;

export function setClaudeSessionResolver(fn: (() => string | undefined) | undefined): void {
claudeSessionResolver = fn;
}

/** Re-point the default binding at the host's current session id when it has
* changed under a live shim (claude /clear). Returns the new id when a re-bind
* happened, else undefined. The register is fire-and-forget (identity binding
* survives any arrival order, same as initialize); the binding update is
* synchronous so the in-flight forward already carries the new id. */
export function maybeRebindConversation(): string | undefined {
if (!IDENTITY_BINDING || claudeSessionResolver === undefined) return undefined;
let current: string | undefined;
try {
current = claudeSessionResolver();
} catch {
current = undefined;
}
if (!current || current === conversationId) return undefined;
const previous = conversationId;
conversationId = current;
process.stderr.write(
`[bili-mcp] host session id changed ${previous ?? "(none)"} → ${current} (claude /clear?); re-binding\n`,
);
if (!registeredConversations.has(current)) {
registeredConversations.add(current);
void fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ conversationId: current, agent: "mcp", identity: true }),
signal: AbortSignal.timeout(5000),
}).catch(() => {});
}
return current;
}

// Test seam: clear the injected resolver between cases (it is module state).
export function _resetClaudeSessionResolverForTest(): void {
claudeSessionResolver = undefined;
}

const ERR_TOOL = -32602;

async function handleMessage(msg: {
Expand Down Expand Up @@ -404,6 +458,10 @@ async function handleMessage(msg: {
const args = { ...rawArgs };
if (!keepForSearch) delete args.conversation_id;
const routeOverride = nativeThreadId ?? (keepForSearch ? undefined : perCall || undefined);
// #6361: before forwarding, re-point the default binding at the
// host's current session id if claude /clear moved it (identity
// hosts only; a routeOverride above still wins for THIS call).
maybeRebindConversation();
// #1685: with no binding and no per-call id, forward anyway — the
// proxy routes the id-less POST itself (outbound tool_use witness,
// else single-active arbitration) and answers a loud 400 when it
Expand Down
33 changes: 33 additions & 0 deletions tests/issue6361-claude-clear-rebind-nonidentity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// #6361 (gate direction 2 — non-identity host): the re-bind seam is scoped to
// identity-bound hosts only. This file loads src/mcp.ts WITHOUT
// CLAUDE_CODE_SESSION_ID (IDENTITY_BINDING is a module-load constant, so the
// direction needs its own process), mirroring the issue4580 precedent of
// importing the shim unbound: even with a resolver armed (as the claude entry
// does) and a fresh session id available, no re-bind may fire — an MCP child
// spawned without the session env keeps the pre-#6361 binding behavior
// exactly.
import { describe, test } from "node:test";
import assert from "node:assert/strict";

delete process.env.CLAUDE_CODE_SESSION_ID;
process.env.BILI_CONVERSATION_ID = "nonidentity-bound-id";

const { _resetMcpBindingForTest, setClaudeSessionResolver, maybeRebindConversation, _resetClaudeSessionResolverForTest } = await import("../src/mcp.ts");

describe("#6361 shim: non-identity host — the re-bind seam stays a no-op", () => {
test("resolver armed + fresh id available → no re-bind, resolver never called", () => {
_resetMcpBindingForTest("nonidentity-bound-id");
let resolverCalls = 0;
setClaudeSessionResolver(() => {
resolverCalls += 1;
return "fresh-session-after-clear";
});
try {
assert.equal(maybeRebindConversation(), undefined, "the identity gate must hold on a non-identity host");
assert.equal(resolverCalls, 0, "the gate must short-circuit before the resolver runs");
} finally {
_resetClaudeSessionResolverForTest();
_resetMcpBindingForTest();
}
});
});
Loading
Loading