Skip to content
Open
21 changes: 19 additions & 2 deletions src/claude-mcp-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,17 @@ export function startWatchdog(state: MutableWatchdogState, plan: { port: number;
return timer;
}

/** #5128: origin precedence for a running claude session's ACP tools — the
* managed block's last-repinned URL (exactly what this session's model traffic
* dials) beats a stale install-time BILI_MCP_PROXY pin, which beats live
* discovery. Exported pure for tests. */
export function resolveClaudeMcpOrigin(managed: string | undefined, env: NodeJS.ProcessEnv = process.env): string {
if (managed !== undefined) return managed;
const pin = env.BILI_MCP_PROXY?.trim();
if (pin !== undefined && pin.length > 0) return pin;
return resolveProxyOrigin();
}

export async function main(opts: WatchdogDeps & { runStdio?: () => void } = {}): Promise<void> {
if (process.env.NODE_TEST_CONTEXT !== undefined) return;
configureLogger(defaultLogFile());
Expand All @@ -134,8 +145,14 @@ export async function main(opts: WatchdogDeps & { runStdio?: () => void } = {}):
return;
}
// Track what THIS running claude dialed: the managed block's last-repinned
// URL wins (settings.json), then the installer pin / live discovery.
const state: MutableWatchdogState = { origin: readClaudeManagedBaseUrl() ?? resolveProxyOrigin(), failures: 0 };
// URL wins (settings.json), then the installer pin / live discovery (#5128).
const managedUrl = readClaudeManagedBaseUrl();
const state: MutableWatchdogState = { origin: resolveClaudeMcpOrigin(managedUrl), failures: 0 };
// Bridge the fresh origin into the stdio tool calls: resolveProxyOrigin reads
// BILI_MCP_PROXY first, so an old installer's baked pin would otherwise
// short-circuit the live origin the session actually rides (#5128). Only when
// the repinned URL won — otherwise leave discovery live.
if (managedUrl !== undefined) process.env.BILI_MCP_PROXY = managedUrl;
startWatchdog(state, plan, log, opts);
(opts.runStdio ?? runMcpStdio)();
}
Expand Down
41 changes: 26 additions & 15 deletions src/plugin-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,7 @@ function defaultWhereRunner(name: string): { stdout: string | null } {
// checkouts and pnpm stores rename the package dir) counts as ours; anything
// else keeps the name and is never touched. An unreadable .claude.json falls
// back to the legacy behavior (plain add; the CLI owns its own file errors).
function claudeMcpFaceAction(entryJs: string, stableOrigin: string):
function claudeMcpFaceAction(entryJs: string, explicitPin: string | undefined):
{ kind: "current" } | { kind: "fresh" } | { kind: "replace"; reason: string } | { kind: "foreign" } {
let data: Record<string, unknown>;
try {
Expand All @@ -905,8 +905,13 @@ function claudeMcpFaceAction(entryJs: string, stableOrigin: string):
const legacy = isNodeCommand && args.some((a) => /dist[\\/]mcp\.(?:js|mjs)$/.test(a));
if (!ours && !legacy) return { kind: "foreign" };
if (!ours) return { kind: "replace", reason: "migrated from dist/mcp.js" };
// #5128: canonical form since the lane port drifts (#1660) — our script +
// (the user's explicit install-time pin, else NO pin: dist/claude-mcp-entry.js
// resolves the live lane proxy per session). A stale baked pin is healed away.
const pin = typeof entry.env === "object" && entry.env !== null ? (entry.env as Record<string, unknown>).BILI_MCP_PROXY : undefined;
if (pin === stableOrigin && args.includes(entryJs)) return { kind: "current" };
const pinMatches = (pin === undefined && explicitPin === undefined) || (pin !== undefined && pin === explicitPin);
if (pinMatches && args.includes(entryJs)) return { kind: "current" };
if (pin !== undefined && explicitPin === undefined) return { kind: "replace", reason: "removed stale BILI_MCP_PROXY pin (the entry resolves the live lane proxy per session)" };
return { kind: "replace", reason: "re-pinned" };
}

Expand All @@ -930,7 +935,6 @@ function claudeInstall(): string {
// can no longer desync from the hook: both resolve through
// resolveClaudeNativePort(), and the SessionStart hook's repin pass
// rewrites the baked URL to the live origin anyway (#1660).
const nativePort = resolveClaudeNativePort() ?? lanePreferredPort("claude");
const file = claudeSettingsFile();
const settings = readJson(file);
// #1902: bare `node`, PATH-resolved by whichever client shell runs the hook.
Expand All @@ -949,30 +953,37 @@ function claudeInstall(): string {
});
writeJson(file, data);

// MCP face: pinned to the STABLE port the hook brings up — never
// proxyOriginForInstall() (an ephemeral launcher proxy would go stale in
// this static config). #1821: the entry now carries the mid-session
// watchdog that respawns the lane proxy when it dies; pre-watchdog
// installs registered plain dist/mcp.js and are swapped in place below so
// an upgrade lands the self-heal without a manual reinstall dance.
const stableOrigin = `http://127.0.0.1:${nativePort}`;
// MCP face. #5128 (same class as #926, fixed for opencode in #936): no
// origin pin by default — the lane port drifts +1 on collision (#1660), so
// baking BILI_MCP_PROXY to the install-time base froze it stale once the
// lane hopped while model traffic rode the repinned URL. The entry resolves
// the live proxy per session; a pin lands only from an explicit BILI_MCP_PROXY
// env at install time. Never proxyOriginForInstall() (ephemeral → goes stale).
// #1821: the entry carries the mid-session watchdog that respawns the lane
// proxy when it dies; pre-watchdog installs registered plain dist/mcp.js,
// swapped in place below so an upgrade lands the self-heal without a reinstall.
const rawPin = process.env.BILI_MCP_PROXY?.trim();
const hasPin = rawPin !== undefined && rawPin.length > 0;
const claude = resolveClaudeCli(process.env.CLAUDE?.trim() || "claude");
const mcpAdd = ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${stableOrigin}`, "--", process.execPath, mcpEntryJs];
const mcpAdd = hasPin
? ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${rawPin}`, "--", process.execPath, mcpEntryJs]
: ["mcp", "add", "bili", "--scope", "user", "--", process.execPath, mcpEntryJs];
const pinSuffix = hasPin ? `pinned ${rawPin}` : "no origin pin — resolves the live lane proxy per session";
let mcpNote: string;
try {
const action = claudeMcpFaceAction(mcpEntryJs, stableOrigin);
const action = claudeMcpFaceAction(mcpEntryJs, hasPin ? rawPin : undefined);
switch (action.kind) {
case "current":
mcpNote = `MCP face current (${claudeMcpJson()}, pinned ${stableOrigin})`;
mcpNote = `MCP face current (${claudeMcpJson()}, ${pinSuffix})`;
break;
case "fresh":
runClaudeCli(claude, mcpAdd);
mcpNote = `MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin})`;
mcpNote = `MCP face -> ${claudeMcpJson()} (${pinSuffix})`;
break;
case "replace":
runClaudeCli(claude, ["mcp", "remove", "bili", "--scope", "user"]);
runClaudeCli(claude, mcpAdd);
mcpNote = `MCP face -> ${claudeMcpJson()} (pinned ${stableOrigin}, ${action.reason})`;
mcpNote = `MCP face -> ${claudeMcpJson()} (${action.reason}${hasPin ? `, pinned ${rawPin}` : ""})`;
break;
case "foreign":
mcpNote = `MCP face left untouched (foreign bili server at ${claudeMcpJson()})`;
Expand Down
77 changes: 67 additions & 10 deletions tests/claude-mcp-entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { main, startWatchdog, watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts";
import { main, resolveClaudeMcpOrigin, startWatchdog, watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts";
import { pluginInstall, readClaudeManagedBaseUrl, selfPackageRoot } from "../src/plugin-install.ts";
import { LAUNCHER_DEFAULT_HOST, ensureProxyRunning, type LauncherDeps } from "../src/launcher.ts";

Expand Down Expand Up @@ -338,18 +338,23 @@ function writeMcpBili(box: { mcpJson: string }, entry: Record<string, unknown>):
fs.writeFileSync(box.mcpJson, JSON.stringify({ mcpServers: { bili: entry } }, null, 2));
}

test("installer: fresh machine registers the watchdog entry", () => {
test("installer: fresh machine registers the watchdog entry without an origin pin (#5128)", () => {
const prevPin = process.env.BILI_MCP_PROXY;
const { box, logFile, cleanup } = mcpFaceSandbox();
try {
delete process.env.BILI_MCP_PROXY;
const note = pluginInstall("claude");
assert.match(note, /MCP face -> .*pinned http:\/\/127\.0\.0\.1:\d+/);
assert.match(note, /MCP face -> .*no origin pin/);
const calls = cliLog(logFile);
assert.equal(calls.length, 1);
assert.ok(calls[0].startsWith("mcp add bili --scope user"), calls[0]);
assert.ok(!calls[0].includes("BILI_MCP_PROXY="), "no origin pin baked (#5128/#1660 lane drift)");
const expected = path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js").replace(/\\/g, "/");
assert.ok(calls[0].replace(/\\/g, "/").includes(expected), calls[0]);
} finally {
cleanup();
if (prevPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = prevPin;
}
});

Expand All @@ -373,40 +378,48 @@ test("installer: legacy dist/mcp.js registration is migrated (remove + add)", ()
}
});

test("installer: current registration with matching pin is left alone", () => {
test("installer: our entry with no origin pin is left current (#5128)", () => {
const prevPin = process.env.BILI_MCP_PROXY;
const { box, logFile, cleanup } = mcpFaceSandbox();
try {
delete process.env.BILI_MCP_PROXY;
writeMcpBili(box, {
type: "stdio",
command: "node",
args: [path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js")],
env: { BILI_MCP_PROXY: `http://127.0.0.1:${ZONE_PORT_BASE}` },
});
const note = pluginInstall("claude");
assert.match(note, /MCP face current/);
assert.equal(cliLog(logFile).length, 0);
assert.equal(cliLog(logFile).length, 0, "no-pin entry is the canonical form — no CLI churn");
} finally {
cleanup();
if (prevPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = prevPin;
}
});

test("installer: our entry with a stale port pin gets re-pinned", () => {
test("installer: our entry with a stale port pin has the pin removed (healed, #5128)", () => {
const prevPin = process.env.BILI_MCP_PROXY;
const { box, logFile, cleanup } = mcpFaceSandbox();
try {
delete process.env.BILI_MCP_PROXY;
writeMcpBili(box, {
type: "stdio",
command: "node",
args: [path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js")],
env: { BILI_MCP_PROXY: "http://127.0.0.1:1" },
});
const note = pluginInstall("claude");
assert.match(note, /re-pinned/);
assert.match(note, /removed stale BILI_MCP_PROXY pin/);
const calls = cliLog(logFile);
assert.equal(calls.length, 2);
assert.ok(calls[0].startsWith("mcp remove bili --scope user"), calls[0]);
assert.ok(calls[1].startsWith("mcp add bili --scope user"), calls[1]);
assert.ok(!calls[1].includes("BILI_MCP_PROXY="), "re-added WITHOUT a stale pin");
} finally {
cleanup();
if (prevPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = prevPin;
}
});

Expand All @@ -424,17 +437,61 @@ test("installer: a foreign bili server keeps its registration untouched", () =>
}
});

test("installer: unreadable .claude.json falls back to plain add", () => {
test("installer: unreadable .claude.json falls back to plain add without a pin", () => {
const prevPin = process.env.BILI_MCP_PROXY;
const { box, logFile, cleanup } = mcpFaceSandbox();
try {
delete process.env.BILI_MCP_PROXY;
fs.mkdirSync(path.dirname(box.mcpJson), { recursive: true });
fs.writeFileSync(box.mcpJson, "{ not json");
const note = pluginInstall("claude");
assert.match(note, /MCP face -> .*pinned/);
assert.match(note, /MCP face -> .*no origin pin/);
const calls = cliLog(logFile);
assert.equal(calls.length, 1);
assert.ok(calls[0].startsWith("mcp add bili --scope user"), calls[0]);
assert.ok(!calls[0].includes("BILI_MCP_PROXY="), calls[0]);
} finally {
cleanup();
if (prevPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = prevPin;
}
});

test("installer: an explicit BILI_MCP_PROXY env bakes the pin and keeps a matching entry current (#5128)", () => {
const prevPin = process.env.BILI_MCP_PROXY;
const { box, logFile, cleanup } = mcpFaceSandbox();
try {
process.env.BILI_MCP_PROXY = "http://127.0.0.1:18888";
// Fresh install: the explicit pin lands.
const note = pluginInstall("claude");
assert.match(note, /MCP face -> .*pinned http:\/\/127\.0\.0\.1:18888/);
const calls = cliLog(logFile);
assert.equal(calls.length, 1);
assert.ok(calls[0].includes("-e BILI_MCP_PROXY=http://127.0.0.1:18888"), calls[0]);
// Reinstall over the matching pinned entry: current, no churn.
writeMcpBili(box, {
type: "stdio",
command: "node",
args: [path.join(selfPackageRoot(), "dist", "claude-mcp-entry.js")],
env: { BILI_MCP_PROXY: "http://127.0.0.1:18888" },
});
const note2 = pluginInstall("claude");
assert.match(note2, /MCP face current.*pinned http:\/\/127\.0\.0\.1:18888/);
assert.equal(cliLog(logFile).length, 1, "the matching explicit pin is left untouched");
} finally {
cleanup();
if (prevPin === undefined) delete process.env.BILI_MCP_PROXY;
else process.env.BILI_MCP_PROXY = prevPin;
}
});

test("resolveClaudeMcpOrigin: managed repin beats a stale pin, then pin, then discovery (#5128)", () => {
const stalePin = { BILI_MCP_PROXY: "http://127.0.0.1:18787" };
// The reporter's exact case: the lane drifted to :18791 but the baked pin
// still says :18787 — the repinned URL must win so tools reach the live proxy.
assert.equal(resolveClaudeMcpOrigin("http://127.0.0.1:18791", stalePin), "http://127.0.0.1:18791");
// No managed URL → an explicit pin is honoured.
assert.equal(resolveClaudeMcpOrigin(undefined, stalePin), "http://127.0.0.1:18787");
// No managed URL and a blank pin → falls through to live discovery (a URL).
assert.match(resolveClaudeMcpOrigin(undefined, { BILI_MCP_PROXY: " " }), /^https?:\/\//);
});
Loading