The best way to control Claude Code, Codex and more from any computer or phone
fix(server): retry stalled MCP registration for resumed Claude turns (#25372)
Yash Singh committed
Oct 26, 2026 at 02:38 UTC
572cf74275bc0fc4dcdaee754db64fb3d5b575c1
3 files changed
+549
-208
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+279
-208
@@ -534,6 +534,15 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAge
534
}
535
}
536
537
+class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
538
+ "ClaudeMcpRegistrationTimeoutError",
539
+ {},
540
+) {
541
+ override get message(): string {
542
+ return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
543
+ }
544
+}
545
+
546
export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError<ClaudeBackgroundWorkBlocksQueryReplacementError>()(
547
"ClaudeBackgroundWorkBlocksQueryReplacementError",
548
{},
@@ -603,6 +612,7 @@ export interface ClaudeAgentSdkSubagentLookupInput {
612
}
613
614
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
615
+const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError);
616
const isProviderAdapterRuntimeRequestResponseError = Schema.is(
617
ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
618
);
@@ -908,249 +918,310 @@ export const layerQueryRunner: Layer.Layer<
918
allocateSessionId: crypto
919
.randomUUIDv4()
920
.pipe(Effect.mapError((cause) => queryRunnerError(cause, "allocateSessionId"))),
911
- open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* (
912
- input: ClaudeAgentSdkQueryOpenInput,
913
- ) {
914
- const protocolLogger = makeClaudeAgentSdkProtocolLogger({
915
- nativeEventLogger,
916
- threadId: input.threadId,
917
- providerSessionId: input.providerSessionId,
918
- });
919
- const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
920
- protocolLogger === undefined ? Effect.void : protocolLogger(event);
921
- const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
922
- const prompt = Stream.fromQueue(promptQueue).pipe(
923
- Stream.catchCause((cause) =>
924
- Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
925
- ),
926
- Stream.toAsyncIterable,
927
- );
928
- // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
929
- const { mcpServers, ...queryOptions } = input.options;
930
- // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
931
- const binaryPath = queryOptions.pathToClaudeCodeExecutable;
932
- const launch =
933
- binaryPath === undefined ||
934
- CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
935
- ? undefined
936
- : yield* agentScope.wrap({
937
- command: binaryPath,
938
- args: [],
939
- name: "claude",
940
- threadId: input.threadId,
941
- env: queryOptions.env,
921
+ open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(
922
+ function* (input: ClaudeAgentSdkQueryOpenInput) {
923
+ const protocolLogger = makeClaudeAgentSdkProtocolLogger({
924
+ nativeEventLogger,
925
+ threadId: input.threadId,
926
+ providerSessionId: input.providerSessionId,
927
+ });
928
+ const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
929
+ protocolLogger === undefined ? Effect.void : protocolLogger(event);
930
+ // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt.
931
+ const promptQueue = yield* Queue.unbounded<SDKUserMessage>();
932
+ const prompt = Stream.fromQueue(promptQueue).pipe(
933
+ Stream.catchCause((cause) =>
934
+ Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
935
+ ),
936
+ Stream.toAsyncIterable,
937
+ );
938
+ // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
939
+ const { mcpServers, ...queryOptions } = input.options;
940
+ // The SDK can prepend a scope wrapper to native binaries; script entries run through node.
941
+ const binaryPath = queryOptions.pathToClaudeCodeExecutable;
942
+ const launch =
943
+ binaryPath === undefined ||
944
+ CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))
945
+ ? undefined
946
+ : yield* agentScope.wrap({
947
+ command: binaryPath,
948
+ args: [],
949
+ name: "claude",
950
+ threadId: input.threadId,
951
+ env: queryOptions.env,
952
+ });
953
+ const options =
954
+ launch === undefined || launch.args.length === 0
955
+ ? queryOptions
956
+ : {
957
+ ...queryOptions,
958
+ pathToClaudeCodeExecutable: launch.command,
959
+ executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
960
+ };
961
+ const unit = launch?.unit;
962
+ const stopScope =
963
+ unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
964
+ const spawnProcess =
965
+ options.spawnClaudeCodeProcess ??
966
+ ((spawnOptions: ClaudeSpawnOptions) => {
967
+ if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope);
968
+ const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
969
+ cwd: spawnOptions.cwd,
970
+ env: spawnOptions.env,
971
+ signal: spawnOptions.signal,
972
+ windowsHide: true,
973
+ stdio: ["pipe", "pipe", "pipe"],
974
});
943
- const options =
944
- launch === undefined || launch.args.length === 0
945
- ? queryOptions
946
- : {
947
- ...queryOptions,
948
- pathToClaudeCodeExecutable: launch.command,
949
- executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],
950
- };
951
- const unit = launch?.unit;
952
- const stopScope =
953
- unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
954
- // Windows has no process groups, so there the SDK spawns the CLI itself.
955
- const spawnClaudeCodeProcess =
956
- options.spawnClaudeCodeProcess ??
957
- (platform === "win32"
958
- ? undefined
959
- : (spawnOptions: ClaudeSpawnOptions) =>
960
- spawnClaudeProcessGroup(spawnOptions, stopScope));
961
- const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
962
- Effect.try({
963
- try: () =>
964
- query({
965
- prompt,
966
- options:
967
- spawnClaudeCodeProcess === undefined
968
- ? options
969
- : { ...options, spawnClaudeCodeProcess },
970
- }),
971
- catch: (cause) => queryRunnerError(cause, "query"),
972
- }).pipe(
973
- Effect.tap((queryRuntime) =>
974
- restore(
975
- Effect.gen(function* () {
976
- if (mcpServers !== undefined) {
977
- // Errors and mcp_status can echo headers; log only server names.
978
- const failed = yield* Effect.tryPromise(() =>
979
- queryRuntime.setMcpServers(mcpServers),
980
- ).pipe(
981
- Effect.map((result) => Object.keys(result.errors)),
982
- Effect.orElseSucceed(() => Object.keys(mcpServers)),
983
- Effect.timeoutOrElse({
984
- duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
985
- orElse: () =>
986
- Effect.fail(
987
- queryRunnerError(
988
- "Claude Code did not answer the MCP server registration.",
989
- "setMcpServers",
975
+ child.stderr
976
+ .setEncoding("utf8")
977
+ .on("data", (chunk: string) => options.stderr?.(chunk));
978
+ return child;
979
+ });
980
+ let spawnedProcess: ClaudeSpawnedProcess | undefined;
981
+ let processExited = false;
982
+ let processExit: Promise<void> | undefined;
983
+ const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => {
984
+ const child = spawnProcess(spawnOptions);
985
+ spawnedProcess = child;
986
+ processExited = child.exitCode !== null || child.signalCode != null;
987
+ processExit = new Promise<void>((resolve) => {
988
+ if (processExited) resolve();
989
+ else
990
+ child.once("exit", () => {
991
+ processExited = true;
992
+ resolve();
993
+ });
994
+ });
995
+ return child;
996
+ };
997
+ const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>
998
+ Effect.try({
999
+ try: () =>
1000
+ query({
1001
+ prompt,
1002
+ options: { ...options, spawnClaudeCodeProcess },
1003
+ }),
1004
+ catch: (cause) => queryRunnerError(cause, "query"),
1005
+ }).pipe(
1006
+ Effect.tap((queryRuntime) =>
1007
+ restore(
1008
+ Effect.gen(function* () {
1009
+ if (mcpServers !== undefined) {
1010
+ // Errors and mcp_status can echo headers; log only server names.
1011
+ const failed = yield* Effect.tryPromise(() =>
1012
+ queryRuntime.setMcpServers(mcpServers),
1013
+ ).pipe(
1014
+ Effect.map((result) => Object.keys(result.errors)),
1015
+ Effect.orElseSucceed(() => Object.keys(mcpServers)),
1016
+ Effect.timeoutOrElse({
1017
+ duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
1018
+ orElse: () =>
1019
+ Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
1020
+ threadId: input.threadId,
1021
+ providerSessionId: input.providerSessionId,
1022
+ }).pipe(
1023
+ Effect.andThen(
1024
+ Effect.fail(
1025
+ queryRunnerError(
1026
+ new ClaudeMcpRegistrationTimeoutError(),
1027
+ "setMcpServers",
1028
+ ),
1029
+ ),
1030
+ ),
1031
),
991
- ),
992
- }),
993
- );
994
- if (failed.length > 0) {
995
- yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", {
996
- threadId: input.threadId,
997
- servers: failed,
998
- });
1032
+ }),
1033
+ );
1034
+ if (failed.length > 0) {
1035
+ yield* Effect.logWarning(
1036
+ "orchestration-v2.claude-mcp-servers-unavailable",
1037
+ {
1038
+ threadId: input.threadId,
1039
+ servers: failed,
1040
+ },
1041
+ );
1042
+ }
1043
}
1000
- }
1001
- yield* logProtocolEvent({
1002
- direction: "outgoing",
1003
- stage: "decoded",
1004
- payload: {
1005
- type: "query.open",
1006
- options: loggedClaudeQueryOptions(input.options),
1007
- },
1008
- });
1009
- }),
1010
- ).pipe(
1011
- Effect.onError(() =>
1012
- Queue.shutdown(promptQueue).pipe(
1013
- Effect.andThen(closeClaudeQuery(queryRuntime)),
1014
- Effect.ignore,
1044
+ yield* logProtocolEvent({
1045
+ direction: "outgoing",
1046
+ stage: "decoded",
1047
+ payload: {
1048
+ type: "query.open",
1049
+ options: loggedClaudeQueryOptions(input.options),
1050
+ },
1051
+ });
1052
+ }),
1053
+ ).pipe(
1054
+ Effect.onError(() =>
1055
+ Queue.shutdown(promptQueue).pipe(
1056
+ // SDK disposal can return before process exit; await the owned child's exit before retrying.
1057
+ Effect.andThen(
1058
+ Effect.tryPromise({
1059
+ try: async () => {
1060
+ if (spawnedProcess !== undefined && !processExited) {
1061
+ spawnedProcess.kill("SIGKILL");
1062
+ }
1063
+ await processExit;
1064
+ },
1065
+ catch: (cause) => queryRunnerError(cause, "close"),
1066
+ }).pipe(Effect.timeout("10 seconds")),
1067
+ ),
1068
+ Effect.ensuring(
1069
+ Effect.tryPromise({
1070
+ try: () => queryRuntime[Symbol.asyncDispose](),
1071
+ catch: (cause) => queryRunnerError(cause, "close"),
1072
+ }).pipe(Effect.orDie),
1073
+ ),
1074
+ Effect.orDie,
1075
+ ),
1076
),
1077
),
1078
),
1079
),
1019
- ),
1020
- );
1080
+ );
1081
1022
- return {
1023
- messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>
1024
- queryRunnerError(cause, "fromAsyncIterable"),
1025
- ).pipe(
1026
- Stream.tap((message) =>
1027
- logProtocolEvent({
1028
- direction: "incoming",
1029
- stage: "decoded",
1030
- payload: message,
1031
- }),
1032
- ),
1033
- ),
1034
- offer: (message, onQueued) =>
1035
- Effect.uninterruptibleMask((restore) =>
1036
- restore(Queue.offer(promptQueue, message)).pipe(
1037
- Effect.tap(() => Effect.sync(() => onQueued?.())),
1038
- ),
1082
+ return {
1083
+ messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>
1084
+ queryRunnerError(cause, "fromAsyncIterable"),
1085
).pipe(
1040
- Effect.asVoid,
1041
- Effect.tap(() =>
1086
+ Stream.tap((message) =>
1087
logProtocolEvent({
1043
- direction: "outgoing",
1088
+ direction: "incoming",
1089
stage: "decoded",
1045
- payload: {
1046
- type: "prompt.offer",
1047
- message,
1048
- },
1090
+ payload: message,
1091
}),
1092
),
1093
),
1052
- setModel: (model) =>
1053
- Effect.tryPromise({
1054
- try: () => queryRuntime.setModel(model),
1055
- catch: (cause) => queryRunnerError(cause, "setModel"),
1056
- }).pipe(
1057
- Effect.tap(() =>
1058
- logProtocolEvent({
1059
- direction: "outgoing",
1060
- stage: "decoded",
1061
- payload: {
1062
- type: "query.set_model",
1063
- model,
1064
- },
1065
- }),
1094
+ offer: (message, onQueued) =>
1095
+ Effect.uninterruptibleMask((restore) =>
1096
+ restore(Queue.offer(promptQueue, message)).pipe(
1097
+ Effect.tap(() => Effect.sync(() => onQueued?.())),
1098
+ ),
1099
+ ).pipe(
1100
+ Effect.asVoid,
1101
+ Effect.tap(() =>
1102
+ logProtocolEvent({
1103
+ direction: "outgoing",
1104
+ stage: "decoded",
1105
+ payload: {
1106
+ type: "prompt.offer",
1107
+ message,
1108
+ },
1109
+ }),
1110
+ ),
1111
),
1067
- ),
1068
- applyFlagSettings: (settings) =>
1069
- Effect.tryPromise({
1070
- try: () => queryRuntime.applyFlagSettings(settings),
1071
- catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
1112
+ setModel: (model) =>
1113
+ Effect.tryPromise({
1114
+ try: () => queryRuntime.setModel(model),
1115
+ catch: (cause) => queryRunnerError(cause, "setModel"),
1116
+ }).pipe(
1117
+ Effect.tap(() =>
1118
+ logProtocolEvent({
1119
+ direction: "outgoing",
1120
+ stage: "decoded",
1121
+ payload: {
1122
+ type: "query.set_model",
1123
+ model,
1124
+ },
1125
+ }),
1126
+ ),
1127
+ ),
1128
+ applyFlagSettings: (settings) =>
1129
+ Effect.tryPromise({
1130
+ try: () => queryRuntime.applyFlagSettings(settings),
1131
+ catch: (cause) => queryRunnerError(cause, "applyFlagSettings"),
1132
+ }).pipe(
1133
+ Effect.tap(() =>
1134
+ logProtocolEvent({
1135
+ direction: "outgoing",
1136
+ stage: "decoded",
1137
+ payload: {
1138
+ type: "query.apply_flag_settings",
1139
+ settings,
1140
+ },
1141
+ }),
1142
+ ),
1143
+ ),
1144
+ setPermissionMode: (mode) =>
1145
+ Effect.tryPromise({
1146
+ try: () => queryRuntime.setPermissionMode(mode),
1147
+ catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
1148
+ }).pipe(
1149
+ Effect.tap(() =>
1150
+ logProtocolEvent({
1151
+ direction: "outgoing",
1152
+ stage: "decoded",
1153
+ payload: {
1154
+ type: "query.set_permission_mode",
1155
+ mode,
1156
+ },
1157
+ }),
1158
+ ),
1159
+ ),
1160
+ stopTask: (taskId) =>
1161
+ Effect.tryPromise({
1162
+ try: () => queryRuntime.stopTask(taskId),
1163
+ catch: (cause) => queryRunnerError(cause, "stopTask"),
1164
+ }).pipe(
1165
+ Effect.tap(() =>
1166
+ logProtocolEvent({
1167
+ direction: "outgoing",
1168
+ stage: "decoded",
1169
+ payload: { type: "query.stop_task", taskId },
1170
+ }),
1171
+ ),
1172
+ ),
1173
+ backgroundTasks: (toolUseId) =>
1174
+ Effect.tryPromise({
1175
+ try: () => queryRuntime.backgroundTasks(toolUseId),
1176
+ catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
1177
+ }).pipe(
1178
+ Effect.tap(() =>
1179
+ logProtocolEvent({
1180
+ direction: "outgoing",
1181
+ stage: "decoded",
1182
+ payload: { type: "query.background_tasks", toolUseId },
1183
+ }),
1184
+ ),
1185
+ ),
1186
+ interrupt: Effect.tryPromise({
1187
+ try: () => queryRuntime.interrupt(),
1188
+ catch: (cause) => queryRunnerError(cause, "interrupt"),
1189
}).pipe(
1190
Effect.tap(() =>
1191
logProtocolEvent({
1192
direction: "outgoing",
1193
stage: "decoded",
1194
payload: {
1078
- type: "query.apply_flag_settings",
1079
- settings,
1195
+ type: "query.interrupt",
1196
},
1197
}),
1198
),
1199
),
1084
- setPermissionMode: (mode) =>
1085
- Effect.tryPromise({
1086
- try: () => queryRuntime.setPermissionMode(mode),
1087
- catch: (cause) => queryRunnerError(cause, "setPermissionMode"),
1088
- }).pipe(
1200
+ close: Queue.shutdown(promptQueue).pipe(
1201
+ Effect.andThen(closeClaudeQuery(queryRuntime)),
1202
Effect.tap(() =>
1203
logProtocolEvent({
1204
direction: "outgoing",
1205
stage: "decoded",
1206
payload: {
1094
- type: "query.set_permission_mode",
1095
- mode,
1207
+ type: "query.close",
1208
},
1209
}),
1210
),
1211
),
1100
- stopTask: (taskId) =>
1101
- Effect.tryPromise({
1102
- try: () => queryRuntime.stopTask(taskId),
1103
- catch: (cause) => queryRunnerError(cause, "stopTask"),
1104
- }).pipe(
1105
- Effect.tap(() =>
1106
- logProtocolEvent({
1107
- direction: "outgoing",
1108
- stage: "decoded",
1109
- payload: { type: "query.stop_task", taskId },
1110
- }),
1111
- ),
1112
- ),
1113
- backgroundTasks: (toolUseId) =>
1114
- Effect.tryPromise({
1115
- try: () => queryRuntime.backgroundTasks(toolUseId),
1116
- catch: (cause) => queryRunnerError(cause, "backgroundTasks"),
1117
- }).pipe(
1118
- Effect.tap(() =>
1119
- logProtocolEvent({
1120
- direction: "outgoing",
1121
- stage: "decoded",
1122
- payload: { type: "query.background_tasks", toolUseId },
1123
- }),
1124
- ),
1125
- ),
1126
- interrupt: Effect.tryPromise({
1127
- try: () => queryRuntime.interrupt(),
1128
- catch: (cause) => queryRunnerError(cause, "interrupt"),
1129
- }).pipe(
1130
- Effect.tap(() =>
1131
- logProtocolEvent({
1132
- direction: "outgoing",
1133
- stage: "decoded",
1134
- payload: {
1135
- type: "query.interrupt",
1136
- },
1137
- }),
1138
- ),
1139
- ),
1140
- close: Queue.shutdown(promptQueue).pipe(
1141
- Effect.andThen(closeClaudeQuery(queryRuntime)),
1142
- Effect.tap(() =>
1143
- logProtocolEvent({
1144
- direction: "outgoing",
1145
- stage: "decoded",
1146
- payload: {
1147
- type: "query.close",
1148
- },
1149
- }),
1150
- ),
1212
+ } satisfies ClaudeAgentSdkQuerySession;
1213
+ },
1214
+ // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID.
1215
+ (effect, input) =>
1216
+ effect.pipe(
1217
+ Effect.retry({
1218
+ times: 1,
1219
+ while: (error) =>
1220
+ input.options.resume !== undefined &&
1221
+ isClaudeMcpRegistrationTimeoutError(error.cause),
1222
+ }),
1223
),
1152
- } satisfies ClaudeAgentSdkQuerySession;
1153
- }),
1224
+ ),
1225
forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
1226
input: ClaudeAgentSdkSessionForkInput,
1227
) {
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+269
@@ -1,25 +1,32 @@
1
// @effect-diagnostics nodeBuiltinImport:off -- the fake CLI and its leftover child are real processes.
2
import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
3
import * as NodeChildProcess from "node:child_process";
4
+import * as NodeEvents from "node:events";
5
import * as NodeFS from "node:fs";
6
import * as NodeOS from "node:os";
7
import * as NodePath from "node:path";
8
+import * as NodeStream from "node:stream";
9
import * as NodeServices from "@effect/platform-node/NodeServices";
10
import { assert, describe, it } from "@effect/vitest";
11
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
12
import * as Effect from "effect/Effect";
13
+import * as Exit from "effect/Exit";
14
import * as Deferred from "effect/Deferred";
15
+import * as Fiber from "effect/Fiber";
16
import * as FileSystem from "effect/FileSystem";
17
import * as Layer from "effect/Layer";
18
import * as Path from "effect/Path";
19
+import * as TestClock from "effect/testing/TestClock";
20
import { vi } from "vite-plus/test";
21
22
import * as HostProcess from "@t3tools/shared/HostProcess";
23
import { AgentScope } from "@t3tools/shared/AgentScope";
24
import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers";
25
+import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
26
import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup";
27
import {
28
ClaudeAgentSdkQueryRunner,
29
+ type ClaudeAgentSdkQueryOpenInput,
30
layerQueryRunner,
31
spawnClaudeProcessGroup,
32
} from "./ClaudeAdapterV2.ts";
@@ -112,6 +119,268 @@ const realQueryRunner = layerQueryRunner.pipe(
119
Layer.provide(NodeServices.layer),
120
);
121
122
+const resumedMcpQueryInput = {
123
+ threadId: ThreadId.make("thread-restart-registration"),
124
+ providerSessionId: ProviderSessionId.make("session-restart-registration"),
125
+ options: {
126
+ resume: FORK_SESSION_ID,
127
+ model: "claude-sonnet-4-6",
128
+ tools: [],
129
+ permissionMode: "default",
130
+ mcpServers: {
131
+ "t3-code": {
132
+ type: "http",
133
+ url: "http://localhost:3773/mcp",
134
+ headers: { Authorization: "Bearer test-mcp-credential" },
135
+ },
136
+ },
137
+ },
138
+} satisfies ClaudeAgentSdkQueryOpenInput;
139
+
140
+it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () =>
141
+ Effect.scoped(
142
+ Effect.gen(function* () {
143
+ const registrationStarted = Promise.withResolvers<void>();
144
+ const disposalStarted = Promise.withResolvers<void>();
145
+ const finishDisposal = Promise.withResolvers<void>();
146
+ const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = [];
147
+ const firstClose = vi.fn();
148
+ const secondClose = vi.fn();
149
+ const firstRegistration = vi.fn(() => {
150
+ registrationStarted.resolve();
151
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
152
+ });
153
+ const secondRegistration = vi.fn(async () => ({
154
+ added: ["t3-code"],
155
+ removed: [],
156
+ errors: {},
157
+ }));
158
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => {
159
+ assert.notTypeOf(prompt, "string");
160
+ if (typeof prompt === "string") throw new Error("Expected streaming input");
161
+ prompts.push(prompt);
162
+ return {
163
+ setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
164
+ close: prompts.length === 1 ? firstClose : secondClose,
165
+ [Symbol.asyncDispose]: async () => {
166
+ firstClose();
167
+ disposalStarted.resolve();
168
+ await finishDisposal.promise;
169
+ },
170
+ } as unknown as ClaudeSdk.Query;
171
+ });
172
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
173
+ const runner = yield* ClaudeAgentSdkQueryRunner;
174
+ const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
175
+ yield* Effect.promise(() => registrationStarted.promise);
176
+ yield* TestClock.adjust("90 seconds");
177
+ yield* Effect.promise(() => disposalStarted.promise);
178
+ assert.equal(querySpy.mock.calls.length, 1);
179
+ finishDisposal.resolve();
180
+ const session = yield* Fiber.join(opening);
181
+ yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
182
+
183
+ assert.equal(firstClose.mock.calls.length, 1);
184
+ assert.equal(secondClose.mock.calls.length, 0);
185
+ assert.equal(querySpy.mock.calls.length, 2);
186
+ for (const [call] of querySpy.mock.calls) {
187
+ assert.equal(call.options?.resume, FORK_SESSION_ID);
188
+ assert.isUndefined(call.options?.mcpServers);
189
+ }
190
+ assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]);
191
+ const message = {
192
+ type: "user",
193
+ message: { role: "user", content: "Continue where you left off." },
194
+ parent_tool_use_id: null,
195
+ session_id: FORK_SESSION_ID,
196
+ } satisfies ClaudeSdk.SDKUserMessage;
197
+ yield* session.offer(message);
198
+ assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done);
199
+ const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next());
200
+ assert.deepEqual(delivered.value, message);
201
+ assert.isFalse(delivered.done);
202
+ }).pipe(Effect.provide(realQueryRunner)),
203
+ ),
204
+);
205
+
206
+it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>
207
+ Effect.scoped(
208
+ Effect.gen(function* () {
209
+ const registrationStarted = Promise.withResolvers<void>();
210
+ const cleanupProgress = Promise.withResolvers<"kill" | "retry">();
211
+ const events = new NodeEvents.EventEmitter();
212
+ const stdin = new NodeStream.PassThrough();
213
+ const stdout = new NodeStream.PassThrough();
214
+ const child = {
215
+ stdin,
216
+ stdout,
217
+ killed: false,
218
+ exitCode: null,
219
+ kill: vi.fn(() => {
220
+ cleanupProgress.resolve("kill");
221
+ return true;
222
+ }),
223
+ on: events.on.bind(events),
224
+ once: events.once.bind(events),
225
+ off: events.off.bind(events),
226
+ } satisfies ClaudeSdk.SpawnedProcess;
227
+ const signal = yield* Effect.abortSignal;
228
+ const disposed = vi.fn(async () => {});
229
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
230
+ const first = querySpy.mock.calls.length === 1;
231
+ if (first) {
232
+ options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
233
+ } else {
234
+ cleanupProgress.resolve("retry");
235
+ }
236
+ return {
237
+ setMcpServers: () => {
238
+ registrationStarted.resolve();
239
+ return first
240
+ ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
241
+ : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
242
+ },
243
+ close: vi.fn(),
244
+ [Symbol.asyncDispose]: disposed,
245
+ } as unknown as ClaudeSdk.Query;
246
+ });
247
+ yield* Effect.addFinalizer(() =>
248
+ Effect.sync(() => {
249
+ querySpy.mockRestore();
250
+ stdin.destroy();
251
+ stdout.destroy();
252
+ }),
253
+ );
254
+ const runner = yield* ClaudeAgentSdkQueryRunner;
255
+ const opening = yield* runner
256
+ .open({
257
+ ...resumedMcpQueryInput,
258
+ options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child },
259
+ })
260
+ .pipe(Effect.exit, Effect.forkChild);
261
+ yield* Effect.promise(() => registrationStarted.promise);
262
+ yield* TestClock.adjust("90 seconds");
263
+
264
+ assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
265
+ assert.equal(querySpy.mock.calls.length, 1);
266
+ assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]);
267
+ if (exits) events.emit("exit", null, "SIGKILL");
268
+ else yield* TestClock.adjust("10 seconds");
269
+ const result = yield* Fiber.join(opening);
270
+ assert.equal(Exit.isSuccess(result), exits);
271
+ if (Exit.isSuccess(result)) yield* result.value.close;
272
+ assert.equal(querySpy.mock.calls.length, exits ? 2 : 1);
273
+ assert.equal(disposed.mock.calls.length, 1);
274
+ }).pipe(Effect.provide(realQueryRunner)),
275
+ ),
276
+);
277
+
278
+it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
279
+ Effect.scoped(
280
+ Effect.gen(function* () {
281
+ const firstRegistration = Promise.withResolvers<void>();
282
+ const secondRegistration = Promise.withResolvers<void>();
283
+ const disposed = vi.fn(async () => {});
284
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
285
+ const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
286
+ return {
287
+ setMcpServers: () => {
288
+ started.resolve();
289
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
290
+ },
291
+ [Symbol.asyncDispose]: disposed,
292
+ } as unknown as ClaudeSdk.Query;
293
+ });
294
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
295
+ const runner = yield* ClaudeAgentSdkQueryRunner;
296
+ const opening = yield* runner
297
+ .open(resumedMcpQueryInput)
298
+ .pipe(Effect.result, Effect.forkChild);
299
+ yield* Effect.promise(() => firstRegistration.promise);
300
+ yield* TestClock.adjust("90 seconds");
301
+ yield* Effect.promise(() => secondRegistration.promise);
302
+ yield* TestClock.adjust("90 seconds");
303
+ const result = yield* Fiber.join(opening);
304
+
305
+ assert.equal(result._tag, "Failure");
306
+ if (result._tag !== "Failure") return;
307
+ assert.equal(querySpy.mock.calls.length, 2);
308
+ assert.equal(disposed.mock.calls.length, 2);
309
+ assert.equal(
310
+ makeProviderFailure({
311
+ cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
312
+ }).message,
313
+ "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
314
+ );
315
+ }).pipe(Effect.provide(realQueryRunner)),
316
+ ),
317
+);
318
+
319
+it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
320
+ Effect.scoped(
321
+ Effect.gen(function* () {
322
+ const registrationStarted = Promise.withResolvers<void>();
323
+ const disposed = vi.fn(async () => {});
324
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
325
+ () =>
326
+ ({
327
+ setMcpServers: () => {
328
+ registrationStarted.resolve();
329
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
330
+ },
331
+ [Symbol.asyncDispose]: disposed,
332
+ }) as unknown as ClaudeSdk.Query,
333
+ );
334
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
335
+ const runner = yield* ClaudeAgentSdkQueryRunner;
336
+ const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
337
+ yield* Effect.promise(() => registrationStarted.promise);
338
+ yield* Fiber.interrupt(opening);
339
+
340
+ assert.equal(querySpy.mock.calls.length, 1);
341
+ assert.equal(disposed.mock.calls.length, 1);
342
+ const prompt = querySpy.mock.calls[0]![0].prompt;
343
+ if (typeof prompt === "string") throw new Error("Expected streaming input");
344
+ assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done);
345
+ }).pipe(Effect.provide(realQueryRunner)),
346
+ ),
347
+);
348
+
349
+it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
350
+ Effect.scoped(
351
+ Effect.gen(function* () {
352
+ const registrationStarted = Promise.withResolvers<void>();
353
+ const disposed = vi.fn(async () => {});
354
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
355
+ () =>
356
+ ({
357
+ setMcpServers: () => {
358
+ registrationStarted.resolve();
359
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
360
+ },
361
+ [Symbol.asyncDispose]: disposed,
362
+ }) as unknown as ClaudeSdk.Query,
363
+ );
364
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
365
+ const runner = yield* ClaudeAgentSdkQueryRunner;
366
+ const { resume, ...options } = resumedMcpQueryInput.options;
367
+ const opening = yield* runner
368
+ .open({
369
+ ...resumedMcpQueryInput,
370
+ options: { ...options, sessionId: resume },
371
+ })
372
+ .pipe(Effect.result, Effect.forkChild);
373
+ yield* Effect.promise(() => registrationStarted.promise);
374
+ yield* TestClock.adjust("90 seconds");
375
+ const result = yield* Fiber.join(opening);
376
+
377
+ assert.equal(result._tag, "Failure");
378
+ assert.equal(querySpy.mock.calls.length, 1);
379
+ assert.equal(disposed.mock.calls.length, 1);
380
+ }).pipe(Effect.provide(realQueryRunner)),
381
+ ),
382
+);
383
+
384
function fakeClaudeCli(script: string): string {
385
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
386
const cli = NodePath.join(dir, "claude");
packages/provider-core/src/server/failure.ts
+1
@@ -91,6 +91,7 @@ function curatedCauseMessages(cause: unknown): {
91
case "ClaudeBackgroundWorkBlocksQueryReplacementError":
92
case "ClaudeAppendSystemPromptFileError":
93
case "ClaudeAppendSystemPromptMissingValueError":
94
+ case "ClaudeMcpRegistrationTimeoutError":
95
case "CursorModelUnavailableError":
96
return { known: stringField(cause, "message"), category: categoryMessage() };
97
case "ContextHandoffDeliveryUncertainError":