Skip to content

Commit 86e2cb2

Browse files
dw3105chief-archivistclaudet3dotgg
authored
fix(server): Claude turns on busy hosts no longer time out registering MCP tools (pingdotgg#30166)
Co-authored-by: chief-archivist <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Theo Browne <[email protected]>
1 parent de21fbc commit 86e2cb2

2 files changed

Lines changed: 85 additions & 16 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROV
343343
const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
344344
// The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server.
345345
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
346+
const CLAUDE_BOOT_TIMEOUT = "5 minutes";
346347
// Claude can consume a subagent result before the launching turn ends, leaving
347348
// its notification with no native wake turn to answer the continuation.
348349
const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
@@ -619,10 +620,12 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRoo
619620

620621
class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
621622
"ClaudeMcpRegistrationTimeoutError",
622-
{},
623+
{ phase: Schema.Literals(["initialize", "setMcpServers"]) },
623624
) {
624625
override get message(): string {
625-
return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
626+
return this.phase === "initialize"
627+
? "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs."
628+
: "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
626629
}
627630
}
628631

@@ -1311,6 +1314,31 @@ export const layerQueryRunner: Layer.Layer<
13111314
restore(
13121315
Effect.gen(function* () {
13131316
if (mcpServers !== undefined) {
1317+
const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
1318+
Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1319+
threadId: input.threadId,
1320+
providerSessionId: input.providerSessionId,
1321+
phase,
1322+
}).pipe(
1323+
Effect.andThen(
1324+
Effect.fail(
1325+
queryRunnerError(
1326+
new ClaudeMcpRegistrationTimeoutError({ phase }),
1327+
phase,
1328+
),
1329+
),
1330+
),
1331+
);
1332+
// The SDK leaves query() boot unbounded, and it takes about a minute on a host
1333+
// with CPUs 12x oversubscribed, so it gets its own, longer deadline.
1334+
yield* Effect.promise(() =>
1335+
queryRuntime.initializationResult().catch(() => undefined),
1336+
).pipe(
1337+
Effect.timeoutOrElse({
1338+
duration: CLAUDE_BOOT_TIMEOUT,
1339+
orElse: timedOut("initialize"),
1340+
}),
1341+
);
13141342
// Errors and mcp_status can echo headers; log only server names.
13151343
const failed = yield* Effect.tryPromise({
13161344
try: () => queryRuntime.setMcpServers(mcpServers),
@@ -1320,20 +1348,7 @@ export const layerQueryRunner: Layer.Layer<
13201348
Effect.orElseSucceed(() => Object.keys(mcpServers)),
13211349
Effect.timeoutOrElse({
13221350
duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
1323-
orElse: () =>
1324-
Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1325-
threadId: input.threadId,
1326-
providerSessionId: input.providerSessionId,
1327-
}).pipe(
1328-
Effect.andThen(
1329-
Effect.fail(
1330-
queryRunnerError(
1331-
new ClaudeMcpRegistrationTimeoutError(),
1332-
"setMcpServers",
1333-
),
1334-
),
1335-
),
1336-
),
1351+
orElse: timedOut("setMcpServers"),
13371352
}),
13381353
);
13391354
if (failed.length > 0) {

‎apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ it.effect("reopens a stalled MCP registration before delivering the resumed prom
254254
if (typeof prompt === "string") throw new Error("Expected streaming input");
255255
prompts.push(prompt);
256256
return {
257+
initializationResult: async () => ({}),
257258
setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
258259
close: prompts.length === 1 ? firstClose : secondClose,
259260
[Symbol.asyncDispose]: async () => {
@@ -360,6 +361,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
360361
cleanupProgress.resolve("retry");
361362
}
362363
return {
364+
initializationResult: async () => ({}),
363365
setMcpServers: () => {
364366
registrationStarted.resolve();
365367
return first
@@ -410,6 +412,7 @@ it.effect("stops retrying MCP registration after two timeouts and reports the ca
410412
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
411413
const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
412414
return {
415+
initializationResult: async () => ({}),
413416
setMcpServers: () => {
414417
started.resolve();
415418
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
@@ -450,6 +453,7 @@ it.effect("cancels a stalled registration without retrying or retaining its prom
450453
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
451454
() =>
452455
({
456+
initializationResult: async () => ({}),
453457
setMcpServers: () => {
454458
registrationStarted.resolve();
455459
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
@@ -480,6 +484,7 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
480484
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
481485
() =>
482486
({
487+
initializationResult: async () => ({}),
483488
setMcpServers: () => {
484489
registrationStarted.resolve();
485490
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
@@ -507,6 +512,55 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
507512
),
508513
);
509514

515+
it.effect.each([
516+
["opens after a slow CLI boot", "120 seconds", true],
517+
["times out a CLI that never boots", "5 minutes", false],
518+
] as const)("%s", ([, bootWait, boots]) =>
519+
Effect.scoped(
520+
Effect.gen(function* () {
521+
const waiting = Promise.withResolvers<void>();
522+
const booted = Promise.withResolvers<void>();
523+
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
524+
() =>
525+
({
526+
initializationResult: () => {
527+
waiting.resolve();
528+
return booted.promise;
529+
},
530+
// The CLI answers control requests only after it has booted.
531+
setMcpServers: async () => {
532+
waiting.resolve();
533+
await booted.promise;
534+
return { added: ["t3-code"], removed: [], errors: {} };
535+
},
536+
close: vi.fn(),
537+
[Symbol.asyncDispose]: async () => {},
538+
}) as unknown as ClaudeSdk.Query,
539+
);
540+
yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
541+
const runner = yield* ClaudeAgentSdkQueryRunner;
542+
const { resume, ...options } = resumedMcpQueryInput.options;
543+
const opening = yield* runner
544+
.open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
545+
.pipe(Effect.result, Effect.forkChild);
546+
yield* Effect.promise(() => waiting.promise);
547+
yield* TestClock.adjust(bootWait);
548+
if (boots) booted.resolve();
549+
const result = yield* Fiber.join(opening);
550+
551+
assert.equal(result._tag, boots ? "Success" : "Failure");
552+
if (result._tag === "Success") yield* result.success.close;
553+
else
554+
assert.equal(
555+
makeProviderFailure({
556+
cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
557+
}).message,
558+
"Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.",
559+
);
560+
}).pipe(Effect.provide(realQueryRunner)),
561+
),
562+
);
563+
510564
function fakeClaudeCli(script: string): string {
511565
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
512566
const cli = NodePath.join(dir, "claude");

0 commit comments

Comments
 (0)