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