Open History to see the last commit
1import * as AssetSigner from "../../assets/AssetSigner.ts";
2import * as DocumentText from "../../provider/DocumentText.ts";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { expect, it } from "@effect/vitest";
6import {
7 DEFAULT_SERVER_SETTINGS,
8 ChatImageAttachment,
9 CommandId,
10 EnvironmentId,
11 NodeId,
12 OrchestratorMcpThreadReadResult,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 RunId,
16 ScheduledTaskError,
17 ScheduledTask,
18 RuntimeRequestId,
19 ThreadId,
20 TurnItemId,
21 type OrchestrationV2ProjectedTurnItem,
22 type OrchestrationV2ThreadShell,
23} from "@t3tools/contracts";
24import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
25import * as Deferred from "effect/Deferred";
26import * as Effect from "effect/Effect";
27import * as TestClock from "effect/testing/TestClock";
28import * as Layer from "effect/Layer";
29import * as Schema from "effect/Schema";
30import { McpAttachmentInput } from "./attachment/input.ts";
31import { McpSchema, McpServer } from "effect/ai";
32import { FetchHttpClient } from "effect/http";
33β
34import {
35 OrchestratorCommandRejectedError,
36 OrchestratorDispatchError,
37 OrchestratorProjectionError,
38} from "../../orchestration-v2/Orchestrator.ts";
39β
40import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
41import * as ServerConfig from "../../config.ts";
42import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts";
43import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts";
44import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts";
45import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts";
46import * as ThreadSearch from "../../orchestration-v2/ThreadSearch.ts";
47import * as PreviewBrowser from "../../preview/PreviewBrowser.ts";
48import * as ProjectService from "../../project/ProjectService.ts";
49import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
50import * as SecretRequests from "../../secrets/SecretRequests.ts";
51import * as RemoteDelegation from "../../peer/RemoteDelegation.ts";
52import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts";
53import * as ServerSettings from "../../serverSettings.ts";
54import * as McpHttpServer from "../McpHttpServer.ts";
55import * as McpInvocationContext from "../McpInvocationContext.ts";
56import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts";
57import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
58import { dispatchFailure } from "../threadAccess.ts";
59import * as EnvironmentHandlers from "./environment/handlers.ts";
60import * as AttachmentHandlers from "./attachment/handlers.ts";
61import * as PeerForwarding from "../../peer/PeerForwarding.ts";
62import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts";
63import * as PeerLinks from "../../peer/PeerLinks.ts";
64β
65const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
66 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
67 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
68);
69β
70const declaredFailure = (result: McpSchema.CallToolResult) => {
71 const text = result.content[0];
72 return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
73};
74import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
75β
76const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput);
77const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult);
78β
79const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
80 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
81 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
82 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
83 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
84 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
85);
86β
87const threadId = ThreadId.make("mcp-core-thread");
88const scope: McpInvocationContext.McpInvocationScope = {
89 environmentId: EnvironmentId.make("mcp-core-environment"),
90 requestNamespace: "mcp-core-session",
91 thread: {
92 threadId,
93 providerSessionId: "mcp-core-session",
94 providerInstanceId: ProviderInstanceId.make("codex"),
95 },
96 client: undefined,
97 issuedAt: 0,
98 capabilities: new Set(["orchestration"]),
99};
100const client = McpSchema.McpServerClient.of({
101 clientId: 1,
102 protocolVersion: "2025-06-18",
103 clientCapabilities: {},
104 clientInfo: { name: "mcp-core", version: "1" },
105 initializePayload: {
106 protocolVersion: "2025-06-18",
107 capabilities: {},
108 clientInfo: { name: "mcp-core", version: "1" },
109 },
110 getClient: Effect.die("unused"),
111});
112β
113it.effect("checks capability through the production registration", () =>
114 Effect.gen(function* () {
115 const server = yield* McpServer.McpServer;
116 expect(server.tools.some(({ tool }) => tool.name === "t3_thread_organize")).toBe(true);
117 const result = yield* server
118 .callTool({ name: "t3_thread_organize", arguments: { action: "pin" } })
119 .pipe(
120 Effect.provideService(McpInvocationContext.McpInvocationContext, {
121 ...scope,
122 capabilities: new Set<never>(),
123 }),
124 Effect.provideService(McpSchema.McpServerClient, client),
125 );
126 expect(declaredFailure(result)).toMatchObject({ code: "capability_denied" });
127 expect(result.isError).toBe(true);
128 expect(result.structuredContent).toBeUndefined();
129 }).pipe(
130 Effect.provide(
131 layerThreadToolkit.pipe(
132 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
133 Layer.provide(NodeCrypto.layer),
134 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
135 ),
136 ),
137 ),
138);
139β
140it.effect("an answered question reports already answered instead of not found", () => {
141 const shell = McpToolAccessTestkit.liveThreadShell(threadId);
142 const requestId = RuntimeRequestId.make("answered-question");
143 const projection = McpToolAccessTestkit.idleThreadProjection(shell);
144 return Effect.gen(function* () {
145 const server = yield* McpServer.McpServer;
146 const respond = (id: string) =>
147 server
148 .callTool({
149 name: "t3_pending_request",
150 arguments: { action: "respond", requestId: id, answers: { size: "large" } },
151 })
152 .pipe(
153 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
154 Effect.provideService(McpSchema.McpServerClient, client),
155 );
156 expect(declaredFailure(yield* respond(requestId))).toMatchObject({
157 code: "invalid_request",
158 message: "The user-input request was already answered.",
159 });
160 expect(declaredFailure(yield* respond("missing-question"))).toMatchObject({
161 code: "invalid_request",
162 message: "The pending user-input request was not found.",
163 });
164 }).pipe(
165 Effect.provide(
166 layerThreadToolkit.pipe(
167 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
168 Layer.provide(NodeCrypto.layer),
169 Layer.provide(
170 Layer.mock(ThreadManagement.ThreadManagementService)({
171 getThreadShell: () => Effect.succeed(shell),
172 getProjectThreadRecords: () =>
173 Effect.succeed({
174 ...projection,
175 runtimeRequests: [
176 {
177 id: requestId,
178 nodeId: NodeId.make("root"),
179 providerTurnId: null,
180 nativeRequestRef: null,
181 kind: "user_input",
182 status: "resolved",
183 responseCapability: { type: "message" },
184 createdAt: shell.createdAt,
185 resolvedAt: shell.updatedAt,
186 answers: { size: "large" },
187 },
188 ],
189 turnItems: [
190 {
191 id: TurnItemId.make("answered-question-item"),
192 threadId,
193 runId: null,
194 nodeId: null,
195 providerThreadId: null,
196 providerTurnId: null,
197 nativeItemRef: null,
198 parentItemId: null,
199 ordinal: 0,
200 status: "completed",
201 title: null,
202 startedAt: shell.createdAt,
203 completedAt: shell.updatedAt,
204 updatedAt: shell.updatedAt,
205 type: "user_input_request",
206 requestId,
207 questions: [],
208 },
209 ],
210 }),
211 dispatch: () => Effect.die("an answered question must not dispatch again"),
212 }),
213 ),
214 ),
215 ),
216 );
217});
218β
219it("bounds public command rejections and redacts internal dispatch causes", () => {
220 const command = { commandId: CommandId.make("mcp-core-command"), commandType: "thread.settle" };
221 expect(
222 dispatchFailure(new OrchestratorDispatchError({ ...command, cause: "π".repeat(1001) }))
223 .message,
224 ).toBe("π".repeat(1000));
225 expect(
226 dispatchFailure(
227 new OrchestratorCommandRejectedError({ ...command, cause: "Run is not queued." }),
228 ).message,
229 ).toBe("Run is not queued.");
230 for (const cause of [
231 undefined,
232 "",
233 new Error("private-storage-path"),
234 { message: "private-storage-path" },
235 ]) {
236 expect(dispatchFailure(new OrchestratorDispatchError({ ...command, cause }))).toMatchObject({
237 code: "orchestration_error",
238 message: "The operation could not be completed.",
239 });
240 expect(
241 dispatchFailure(new OrchestratorCommandRejectedError({ ...command, cause })),
242 ).toMatchObject({
243 code: "orchestration_error",
244 message: "The operation could not be completed.",
245 });
246 }
247 expect(
248 dispatchFailure(new OrchestratorProjectionError({ threadId, cause: "private-storage-path" })),
249 ).toMatchObject({
250 code: "orchestration_error",
251 message: "The operation could not be completed.",
252 });
253});
254β
255const fullAccessThreadId = ThreadId.make("mcp-core-full-access-thread");
256β
257it.effect("returns an HTML render reference that Codex and Claude tool rows both carry", () =>
258 Effect.gen(function* () {
259 const server = yield* McpServer.McpServer;
260 const result = yield* server
261 .callTool({
262 name: "html_render",
263 arguments: { html: "<p>Revenue</p>", title: "Revenue", height: 240 },
264 })
265 .pipe(
266 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
267 Effect.provideService(McpSchema.McpServerClient, client),
268 );
269 const reference = htmlRenderFromToolItem({
270 toolName: "t3-code.html_render",
271 output: result.structuredContent,
272 });
273 expect(reference).toMatchObject({ title: "Revenue", height: 240 });
274 expect(
275 htmlRenderFromToolItem({ toolName: "mcp__t3-code__html_render", output: result.content }),
276 ).toEqual(reference);
277 // Only a full-access thread may have the server read a file for it.
278 const byPath = (name: string, caller: McpInvocationContext.McpInvocationScope) =>
279 server
280 .callTool({
281 name,
282 arguments: { path: "/t3-missing-dir/revenue.html", title: "Revenue", height: 240 },
283 })
284 .pipe(
285 Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
286 Effect.provideService(McpSchema.McpServerClient, client),
287 // html_preview reports failures as plain text, html_render as a declared failure.
288 Effect.map((result) => (result.isError ? JSON.stringify(result.content) : undefined)),
289 );
290 const fullAccess = { ...scope, thread: { ...scope.thread!, threadId: fullAccessThreadId } };
291 for (const name of ["html_preview", "html_render"]) {
292 expect(yield* byPath(name, scope), name).toContain("only full-access threads");
293 expect(yield* byPath(name, fullAccess), name).toContain("not a readable HTML document");
294 }
295 }).pipe(
296 Effect.provide(
297 McpHttpServer.layerHtmlToolkit.pipe(
298 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
299 Layer.provide(McpProviderSessions.layer),
300 Layer.provide(PreviewBrowser.layer),
301 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" })),
302 Layer.provide(
303 DocumentText.layer.pipe(
304 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
305 ),
306 ),
307 Layer.provide(FetchHttpClient.layer),
308 Layer.provide(
309 Layer.mock(ThreadManagement.ThreadManagementService)({
310 getThreadShell: (id) =>
311 Effect.succeed({
312 id,
313 deletedAt: null,
314 archivedAt: null,
315 activeRunId: RunId.make("mcp-core-run"),
316 providerInstanceId: ProviderInstanceId.make("codex"),
317 runtimeMode: id === fullAccessThreadId ? "full-access" : "approval-required",
318 interactionMode: "default",
319 } as OrchestrationV2ThreadShell),
320 }),
321 ),
322 ),
323 ),
324 ),
325);
326β
327it.effect("records only failed calls of tools that hand off no work", () => {
328 // Recording runs detached from the tool response, so the first event is awaited.
329 const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>();
330 return Effect.gen(function* () {
331 const server = yield* McpServer.McpServer;
332 const organize = (capabilities: McpInvocationContext.McpInvocationScope["capabilities"]) =>
333 server.callTool({ name: "t3_thread_organize", arguments: { action: "pin" } }).pipe(
334 Effect.provideService(McpInvocationContext.McpInvocationContext, {
335 ...scope,
336 capabilities,
337 }),
338 Effect.provideService(McpSchema.McpServerClient, client),
339 );
340 expect((yield* organize(scope.capabilities)).isError).not.toBe(true);
341 expect(declaredFailure(yield* organize(new Set<never>()))).toMatchObject({
342 code: "capability_denied",
343 });
344 // The successful call ran first, so it would be the first event if it were recorded.
345 expect(yield* Deferred.await(recorded)).toMatchObject({
346 event: "mcp.tool.invoked",
347 properties: { tool: "t3_thread_organize", outcome: "error" },
348 });
349 }).pipe(
350 Effect.provide(
351 layerThreadToolkit.pipe(
352 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
353 Layer.provide(NodeCrypto.layer),
354 Layer.provide(
355 Layer.mock(ThreadManagement.ThreadManagementService)({
356 getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
357 getProjectThreadRecords: ({ threadId: id }) =>
358 Effect.succeed(
359 McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)),
360 ),
361 dispatch: () => Effect.succeed({ sequence: 1 } as never),
362 }),
363 ),
364 Layer.provide(
365 Layer.succeed(
366 AnalyticsService.AnalyticsService,
367 AnalyticsService.AnalyticsService.of({
368 record: (event, properties) =>
369 Deferred.succeed(recorded, { event, properties: properties ?? {} }).pipe(
370 Effect.asVoid,
371 ),
372 flush: Effect.void,
373 recordOwners: () => Effect.void,
374 }),
375 ),
376 ),
377 ),
378 ),
379 );
380});
381β
382it.effect("rejects an unknown organize target instead of archiving the calling thread", () => {
383 const dispatched: Array<unknown> = [];
384 return Effect.gen(function* () {
385 const server = yield* McpServer.McpServer;
386 const outcome = yield* server
387 .callTool({
388 name: "t3_thread_organize",
389 arguments: { action: "archive", threadIds: ["other-thread"] },
390 })
391 .pipe(
392 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
393 Effect.provideService(McpSchema.McpServerClient, client),
394 Effect.result,
395 );
396 expect(dispatched).toEqual([]);
397 expect(outcome).toMatchObject({
398 _tag: "Failure",
399 failure: { message: expect.stringContaining("Expected no excess property") },
400 });
401 }).pipe(
402 Effect.provide(
403 layerThreadToolkit.pipe(
404 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
405 Layer.provide(NodeCrypto.layer),
406 Layer.provide(
407 Layer.mock(ThreadManagement.ThreadManagementService)({
408 getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
409 getProjectThreadRecords: ({ threadId: id }) =>
410 Effect.succeed(
411 McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)),
412 ),
413 dispatch: (command) => {
414 dispatched.push(command);
415 return Effect.succeed({ sequence: 1 } as never);
416 },
417 }),
418 ),
419 ),
420 ),
421 );
422});
423β
424it.effect("keeps unexpected handler defects private through the production registration", () =>
425 Effect.gen(function* () {
426 const server = yield* McpServer.McpServer;
427 const result = yield* server
428 .callTool({ name: "t3_thread_organize", arguments: { action: "pin" } })
429 .pipe(
430 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
431 Effect.provideService(McpSchema.McpServerClient, client),
432 );
433 expect(result.isError).toBe(true);
434 expect(result.structuredContent).toBeUndefined();
435 expect(result.content).toEqual([
436 { type: "text", text: "Tool execution failed due to an internal server error." },
437 ]);
438 }).pipe(
439 Effect.provide(
440 layerThreadToolkit.pipe(
441 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
442 Layer.provide(NodeCrypto.layer),
443 Layer.provide(
444 Layer.mock(ThreadManagement.ThreadManagementService)({
445 getThreadShell: () => Effect.die(new Error("private-storage-path")),
446 }),
447 ),
448 ),
449 ),
450 ),
451);
452β
453it("keeps MCP preference output allowlisted and Unicode-bounded", () => {
454 const settings = {
455 ...DEFAULT_SERVER_SETTINGS,
456 privateCredential: "must-not-escape",
457 sourceControlWritingStyle: {
458 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
459 customInstructions: "π".repeat(4001),
460 },
461 };
462 const result = EnvironmentHandlers.preferences(settings);
463 expect(result).not.toHaveProperty("privateCredential");
464 expect(result).not.toHaveProperty("providers");
465 expect(result.sourceControlWritingStyle).toMatchObject({
466 customInstructions: "π".repeat(4000),
467 truncated: true,
468 });
469});
470β
471it.effect("resolves reused attachment references from stored metadata", () =>
472 Effect.gen(function* () {
473 const stored = ChatImageAttachment.make({
474 type: "image",
475 id: "owned-image",
476 name: "original.png",
477 mimeType: "image/png",
478 sizeBytes: 12,
479 source: {
480 kind: "snap-shot",
481 capturedAt: "2026-09-10T00:00:00.000Z",
482 appName: "Terminal",
483 windowTitle: "Test",
484 accessibility: { format: "flat-text", text: "Stored context", truncated: false },
485 },
486 });
487 const forged = yield* decodeMcpAttachmentInput({
488 type: "image",
489 id: stored.id,
490 name: "changed.jpg",
491 mimeType: "image/jpeg",
492 sizeBytes: 99,
493 });
494 const result = yield* AttachmentHandlers.resolveAttachmentReferences([forged], [stored]);
495 expect(result).toEqual([stored]);
496 const failure = yield* AttachmentHandlers.resolveAttachmentReferences(
497 [{ ...forged, id: "other-image" }],
498 [stored],
499 ).pipe(Effect.flip);
500 expect(failure.code).toBe("invalid_request");
501 }),
502);
503β
504const clientScope = (
505 access: McpInvocationContext.McpClientCaller["access"],
506): McpInvocationContext.McpInvocationScope => ({
507 environmentId: EnvironmentId.make("mcp-core-environment"),
508 requestNamespace: "client:session-1",
509 thread: undefined,
510 client: { sessionId: "session-1", label: "Claude Code", access },
511 issuedAt: 0,
512 capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
513});
514β
515it.effect("a client caller targets any thread within its ceiling and cannot act as a thread", () =>
516 Effect.gen(function* () {
517 const server = yield* McpServer.McpServer;
518 const call = (
519 name: string,
520 args: Record<string, unknown>,
521 invocation: McpInvocationContext.McpInvocationScope,
522 ) =>
523 server
524 .callTool({ name, arguments: args })
525 .pipe(
526 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
527 Effect.provideService(McpSchema.McpServerClient, client),
528 );
529β
530 const untargeted = yield* call("t3_thread_organize", { action: "pin" }, clientScope("auto"));
531 expect(declaredFailure(untargeted)).toMatchObject({ code: "target_required" });
532β
533 const pinned = yield* call(
534 "t3_thread_organize",
535 { action: "pin", threadId: "other-project-thread" },
536 clientScope("auto"),
537 );
538 expect(pinned.isError).toBe(false);
539 expect(pinned.structuredContent).toMatchObject({ sequence: 7 });
540β
541 const aboveCeiling = yield* call(
542 "t3_thread_organize",
543 { action: "pin", threadId: "other-project-thread" },
544 clientScope("approval-required"),
545 );
546 expect(declaredFailure(aboveCeiling)).toMatchObject({
547 code: "runtime_mode_escalation_denied",
548 });
549β
550 const forked = yield* call(
551 "t3_thread_transfer",
552 { action: "fork", sourcePoint: { type: "latest_stable" } },
553 clientScope("auto"),
554 );
555 expect(declaredFailure(forked)).toMatchObject({ code: "target_required" });
556 }).pipe(
557 Effect.provide(
558 layerThreadToolkit.pipe(
559 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
560 Layer.provide(NodeCrypto.layer),
561 Layer.provide(
562 Layer.mock(ThreadManagement.ThreadManagementService)({
563 getThreadShell: (id) =>
564 Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" })),
565 getProjectThreadRecords: () =>
566 Effect.succeed({
567 thread: {
568 id: ThreadId.make("other-project-thread"),
569 projectId: "other-project",
570 runtimeMode: "auto",
571 interactionMode: "default",
572 deletedAt: null,
573 },
574 } as never),
575 dispatch: () => Effect.succeed({ sequence: 7, storedEvents: [] }),
576 }),
577 ),
578 ),
579 ),
580 ),
581);
582β
583it.effect("a read-only client reads threads and is refused every write before it runs", () =>
584 Effect.gen(function* () {
585 const server = yield* McpServer.McpServer;
586 const call = (name: string, args: Record<string, unknown>) =>
587 server
588 .callTool({ name, arguments: args })
589 .pipe(
590 Effect.provideService(
591 McpInvocationContext.McpInvocationContext,
592 clientScope("read-only"),
593 ),
594 Effect.provideService(McpSchema.McpServerClient, client),
595 );
596β
597 const configuration = yield* call("t3_thread_configure", {
598 threadId: "other-project-thread",
599 });
600 expect(configuration.isError).toBe(false);
601 expect(configuration.structuredContent).toMatchObject({ runtimeMode: "auto" });
602β
603 const pinned = yield* call("t3_thread_organize", {
604 action: "pin",
605 threadId: "other-project-thread",
606 });
607 expect(declaredFailure(pinned)).toMatchObject({ code: "capability_denied" });
608 expect(dispatched).toEqual([]);
609β
610 const configure = yield* call("t3_thread_configure", {
611 threadId: "other-project-thread",
612 modelSelection: { instanceId: "codex", model: "gpt-5" },
613 });
614 expect(declaredFailure(configure)).toMatchObject({ code: "capability_denied" });
615 expect(dispatched).toEqual([]);
616 }).pipe(
617 Effect.provide(
618 layerThreadToolkit.pipe(
619 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
620 Layer.provide(NodeCrypto.layer),
621 Layer.provide(
622 Layer.mock(ThreadManagement.ThreadManagementService)({
623 getThreadShell: () =>
624 Effect.succeed({
625 id: ThreadId.make("other-project-thread"),
626 projectId: "other-project",
627 deletedAt: null,
628 } as never),
629 getProjectThreadRecords: () =>
630 Effect.succeed({
631 thread: {
632 id: ThreadId.make("other-project-thread"),
633 projectId: "other-project",
634 modelSelection: { instanceId: "codex", model: "gpt-5" },
635 runtimeMode: "auto",
636 interactionMode: "default",
637 deletedAt: null,
638 },
639 } as never),
640 dispatch: () =>
641 Effect.sync(() => {
642 dispatched.push("dispatch");
643 return { sequence: 7 } as never;
644 }),
645 }),
646 ),
647 ),
648 ),
649 ),
650);
651const dispatched: Array<string> = [];
652β
653it.effect("refuses act-as-caller tools to a client caller", () =>
654 Effect.gen(function* () {
655 const server = yield* McpServer.McpServer;
656 const result = yield* server
657 .callTool({
658 name: "delegate_task",
659 arguments: { task: "Review", mode: "async" },
660 })
661 .pipe(
662 Effect.provideService(
663 McpInvocationContext.McpInvocationContext,
664 clientScope("full-access"),
665 ),
666 Effect.provideService(McpSchema.McpServerClient, client),
667 );
668 expect(declaredFailure(result)).toMatchObject({ code: "thread_credential_required" });
669 }).pipe(
670 Effect.provide(
671 layerOrchestratorToolkit.pipe(
672 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
673 Layer.provide(NodeCrypto.layer),
674 Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
675 Layer.provide(ServerSettings.layerTest()),
676 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
677 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
678 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
679 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
680 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
681 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
682 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
683 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
684 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
685 ),
686 ),
687 ),
688);
689β
690it.effect("a caller cannot rewrite a scheduled task that runs above its own modes", () =>
691 Effect.gen(function* () {
692 const server = yield* McpServer.McpServer;
693 const call = (name: string, args: Record<string, unknown>) =>
694 server
695 .callTool({ name, arguments: args })
696 .pipe(
697 Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")),
698 Effect.provideService(McpSchema.McpServerClient, client),
699 );
700 const update = yield* call("schedule_task", {
701 scheduledTaskId: "task-full-access",
702 prompt: "Run something else",
703 });
704 expect(declaredFailure(update)).toMatchObject({ code: "runtime_mode_escalation_denied" });
705 const remove = yield* call("delete_scheduled_task", { scheduledTaskId: "task-full-access" });
706 expect(declaredFailure(remove)).toMatchObject({ code: "runtime_mode_escalation_denied" });
707 const allowed = yield* call("schedule_task", {
708 scheduledTaskId: "task-auto",
709 enabled: false,
710 });
711 expect(allowed.isError).toBe(false);
712 const incomplete = yield* call("schedule_task", { prompt: "Run nightly" });
713 expect(declaredFailure(incomplete)).toMatchObject({ code: "invalid_request" });
714 }).pipe(
715 Effect.provide(
716 layerOrchestratorToolkit.pipe(
717 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
718 Layer.provide(NodeCrypto.layer),
719 Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
720 Layer.provide(ServerSettings.layerTest()),
721 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
722 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
723 Layer.provide(
724 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
725 list: () =>
726 Effect.succeed({
727 tasks: [
728 scheduledTask("task-full-access", "full-access"),
729 scheduledTask("task-auto", "auto"),
730 ],
731 }),
732 upsert: (input) =>
733 Effect.succeed({
734 task: { ...(scheduledTask(input.id ?? "task-auto", "auto") as object), ...input },
735 } as never),
736 }),
737 ),
738 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
739 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
740 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
741 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
742 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
743 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
744 ),
745 ),
746 ),
747);
748β
749it.effect.each([
750 {
751 scenario: "explains why a webhook task cannot run manually",
752 tasks: [
753 {
754 ...Schema.decodeSync(ScheduledTask)(scheduledTask("task-webhook", "full-access")),
755 schedule: { type: "webhook" as const, signature: null },
756 },
757 ],
758 error: new ScheduledTaskError({
759 message: "Webhook tasks run when their URL receives a request.",
760 cause: new Error("private-webhook-cause"),
761 }),
762 code: "orchestration_error",
763 message: "Webhook tasks run when their URL receives a request.",
764 },
765 {
766 scenario: "reports a missing task before trying to run it",
767 tasks: [],
768 error: new ScheduledTaskError({ message: "must not run a missing task" }),
769 code: "invalid_request",
770 message: "The scheduled task was not found.",
771 },
772])("run_scheduled_task_now $scenario", ({ tasks, error, code, message }) =>
773 Effect.gen(function* () {
774 const server = yield* McpServer.McpServer;
775 const result = yield* server
776 .callTool({ name: "run_scheduled_task_now", arguments: { taskId: "task-webhook" } })
777 .pipe(
778 Effect.provideService(
779 McpInvocationContext.McpInvocationContext,
780 clientScope("full-access"),
781 ),
782 Effect.provideService(McpSchema.McpServerClient, client),
783 );
784 expect(result.isError).toBe(true);
785 expect(result.structuredContent).toBeUndefined();
786 expect(declaredFailure(result)).toEqual({ _tag: "OrchestratorMcpFailure", code, message });
787 expect(JSON.stringify(result)).not.toContain("private-");
788 }).pipe(
789 Effect.provide(
790 McpHttpServer.layerThreadToolkit.pipe(
791 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
792 Layer.provide(NodeCrypto.layer),
793 Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
794 Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
795 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
796 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
797 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
798 Layer.provide(
799 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
800 list: () => Effect.succeed({ tasks }),
801 runNow: () => Effect.fail(error),
802 }),
803 ),
804 ),
805 ),
806 ),
807);
808β
809function scheduledTask(id: string, runtimeMode: "auto" | "full-access"): never {
810 return {
811 id,
812 title: id,
813 prompt: "Check the build",
814 enabled: true,
815 projectId: "project-a",
816 threadId: null,
817 schedule: { type: "interval", everyMs: 3_600_000 },
818 workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true },
819 modelSelection: { instanceId: "codex", model: "gpt-5" },
820 runtimeMode,
821 interactionMode: "default",
822 createdBy: "user",
823 creationSource: "web",
824 nextRunAt: null,
825 lastRunStatus: "never",
826 lastRunAt: null,
827 lastRunThreadId: null,
828 lastRunError: null,
829 runCount: 0,
830 createdAt: "2026-10-01T00:00:00.000Z",
831 updatedAt: "2026-10-01T00:00:00.000Z",
832 } as never;
833}
834β
835it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
836 "a caller cannot use %s on a thread that runs above its own modes",
837 (toolName) =>
838 Effect.gen(function* () {
839 const server = yield* McpServer.McpServer;
840 const result = yield* server
841 .callTool({
842 name: toolName,
843 arguments: {
844 threadId: "full-access-thread",
845 ...(toolName === "t3_workflow_stop" ? { subagentId: "workflow-coordinator" } : {}),
846 },
847 })
848 .pipe(
849 Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")),
850 Effect.provideService(McpSchema.McpServerClient, client),
851 );
852 expect(declaredFailure(result)).toMatchObject({ code: "runtime_mode_escalation_denied" });
853 }).pipe(
854 Effect.provide(
855 layerOrchestratorToolkit.pipe(
856 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
857 Layer.provide(NodeCrypto.layer),
858 Layer.provide(
859 Layer.mock(ThreadManagement.ThreadManagementService)({
860 getThreadShell: () =>
861 Effect.succeed({
862 projectId: "project-a",
863 deletedAt: null,
864 runtimeMode: "full-access",
865 interactionMode: "default",
866 } as never),
867 getProjectThreadRecords: () =>
868 Effect.succeed({
869 thread: {
870 id: ThreadId.make("full-access-thread"),
871 projectId: "project-a",
872 runtimeMode: "full-access",
873 interactionMode: "default",
874 deletedAt: null,
875 },
876 runs: [],
877 } as never),
878 stopWorkflow: () => Effect.die("workflow stop must not dispatch above the ceiling"),
879 interruptThread: () => Effect.die("interrupt must not dispatch above the ceiling"),
880 }),
881 ),
882 Layer.provide(ServerSettings.layerTest()),
883 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
884 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
885 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
886 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
887 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
888 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
889 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
890 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
891 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
892 ),
893 ),
894 ),
895);
896β
897it.effect("discovers workflow stop targets and requires orchestration capability", () => {
898 const threadId = ThreadId.make("workflow-parent");
899 const shell = McpToolAccessTestkit.liveThreadShell(threadId);
900 const subagentId = NodeId.make("workflow-coordinator");
901 const itemId = TurnItemId.make("workflow-coordinator-activity");
902 const row: OrchestrationV2ProjectedTurnItem = {
903 position: 0,
904 visibility: "local",
905 sourceThreadId: threadId,
906 sourceItemId: itemId,
907 item: {
908 id: itemId,
909 threadId,
910 runId: shell.activeRunId,
911 nodeId: subagentId,
912 providerThreadId: null,
913 providerTurnId: null,
914 nativeItemRef: null,
915 parentItemId: null,
916 ordinal: 0,
917 status: "running",
918 title: "Workflow: checkout review",
919 startedAt: shell.createdAt,
920 completedAt: null,
921 updatedAt: shell.updatedAt,
922 type: "subagent",
923 subagentId,
924 origin: "provider_native",
925 driver: ProviderDriverKind.make("claudeAgent"),
926 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
927 childThreadId: ThreadId.make("workflow-child"),
928 prompt: "Review checkout",
929 result: null,
930 },
931 };
932 const stopped: Array<{ readonly threadId: ThreadId; readonly subagentId: string }> = [];
933 return Effect.gen(function* () {
934 const server = yield* McpServer.McpServer;
935 const scope = clientScope("full-access");
936 const read = yield* server
937 .callTool({ name: "t3_thread_read", arguments: { threadId, view: "activity" } })
938 .pipe(
939 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
940 Effect.provideService(McpSchema.McpServerClient, client),
941 );
942 expect(read.isError).toBe(false);
943 const result = yield* decodeThreadReadResult(read.structuredContent);
944 expect(result.items[0]?.subagentId).toBe(subagentId);
945 const call = (invocation: McpInvocationContext.McpInvocationScope) =>
946 server
947 .callTool({
948 name: "t3_workflow_stop",
949 arguments: { threadId, subagentId: result.items[0]?.subagentId },
950 })
951 .pipe(
952 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
953 Effect.provideService(McpSchema.McpServerClient, client),
954 );
955 const denied = yield* call({ ...scope, capabilities: new Set(["worktree"]) });
956 expect(declaredFailure(denied)).toMatchObject({ code: "capability_denied" });
957 expect(stopped).toEqual([]);
958 const allowed = yield* call(scope);
959 expect(allowed.isError).toBe(false);
960 expect(stopped).toEqual([{ threadId: "workflow-parent", subagentId: "workflow-coordinator" }]);
961 }).pipe(
962 Effect.provide(
963 layerOrchestratorToolkit.pipe(
964 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
965 Layer.provide(NodeCrypto.layer),
966 Layer.provide(
967 Layer.mock(ThreadManagement.ThreadManagementService)({
968 getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
969 getProjectThreadRecords: () =>
970 Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
971 getTimelinePage: () => Effect.succeed({ items: [row], totalItems: 1, hasMore: false }),
972 stopWorkflow: (input) =>
973 Effect.sync(() => {
974 stopped.push(input);
975 }),
976 }),
977 ),
978 Layer.provide(ServerSettings.layerTest()),
979 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
980 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
981 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
982 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
983 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
984 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
985 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
986 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
987 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
988 ),
989 ),
990 );
991});
992β
993it.effect("only the caller that prepared a pending upload can discard it", () =>
994 Effect.gen(function* () {
995 const server = yield* McpServer.McpServer;
996 const call = (
997 name: string,
998 args: Record<string, unknown>,
999 invocation: McpInvocationContext.McpInvocationScope,
1000 ) =>
1001 server
1002 .callTool({ name, arguments: args })
1003 .pipe(
1004 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
1005 Effect.provideService(McpSchema.McpServerClient, client),
1006 );
1007 const prepared = yield* call(
1008 "t3_attachment_prepare_upload",
1009 { upload: { name: "shot.png", mimeType: "image/png", sizeBytes: 4 } },
1010 scope,
1011 );
1012 const { attachmentId } = prepared.structuredContent as { readonly attachmentId: string };
1013 const otherThread = {
1014 ...scope,
1015 requestNamespace: "other-session",
1016 thread: { ...scope.thread!, threadId: ThreadId.make("other-thread") },
1017 };
1018β
1019 const refused = yield* call("t3_attachment_discard", { attachmentId }, otherThread);
1020 expect(declaredFailure(refused)).toMatchObject({ code: "invalid_request" });
1021β
1022 yield* TestClock.adjust(24 * 60 * 60 * 1000 + 5 * 60_000);
1023 yield* call(
1024 "t3_attachment_prepare_upload",
1025 { upload: { name: "later.png", mimeType: "image/png", sizeBytes: 4 } },
1026 scope,
1027 );
1028β
1029 const discarded = yield* call(
1030 "t3_attachment_discard",
1031 { attachmentId },
1032 { ...scope, requestNamespace: "mcp-core-session-2" },
1033 );
1034 expect(discarded.isError).toBe(false);
1035 }).pipe(
1036 Effect.provide(
1037 McpHttpServer.layerAttachmentToolkit.pipe(
1038 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
1039 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1040 Layer.provide(AssetSigner.layer.pipe(Layer.provideMerge(ServerSecretStore.layer))),
1041 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-attachment-" })),
1042 Layer.provide(
1043 DocumentText.layer.pipe(
1044 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1045 ),
1046 ),
1047 Layer.provide(NodeCrypto.layer),
1048 ),
1049 ),
1050 ),
1051);
1052β
1053it.effect(
1054 "t3_thread_list settled:false with an empty statuses list lists the unsettled threads",
1055 () => {
1056 const unsettled = McpToolAccessTestkit.liveThreadShell(ThreadId.make("unsettled-thread"));
1057 const settled = {
1058 ...McpToolAccessTestkit.liveThreadShell(ThreadId.make("settled-thread")),
1059 settledOverride: "settled",
1060 } as const;
1061 return Effect.gen(function* () {
1062 const server = yield* McpServer.McpServer;
1063 const result = yield* server
1064 .callTool({
1065 name: "t3_thread_list",
1066 arguments: { projectId: unsettled.projectId, settled: false, statuses: [] },
1067 })
1068 .pipe(
1069 Effect.provideService(
1070 McpInvocationContext.McpInvocationContext,
1071 clientScope("full-access"),
1072 ),
1073 Effect.provideService(McpSchema.McpServerClient, client),
1074 );
1075 expect(result.isError).toBe(false);
1076 expect(result.structuredContent).toMatchObject({
1077 threads: [{ threadId: unsettled.id, settled: false }],
1078 total: 1,
1079 });
1080 }).pipe(
1081 Effect.provide(
1082 layerOrchestratorToolkit.pipe(
1083 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
1084 Layer.provide(NodeCrypto.layer),
1085 Layer.provide(
1086 Layer.mock(ThreadManagement.ThreadManagementService)({
1087 listProjectThreads: () => Effect.succeed([unsettled, settled]),
1088 }),
1089 ),
1090 Layer.provide(ServerSettings.layerTest()),
1091 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
1092 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
1093 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
1094 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
1095 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
1096 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
1097 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
1098 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
1099 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
1100 ),
1101 ),
1102 );
1103 },
1104);