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 Effect from "effect/Effect";
22import * as TestClock from "effect/testing/TestClock";
23import * as Layer from "effect/Layer";
24import * as Schema from "effect/Schema";
25import { McpAttachmentInput } from "./attachment/input.ts";
26import { McpSchema, McpServer } from "effect/ai";
27import { FetchHttpClient } from "effect/http";
28β
29import {
30 OrchestratorCommandRejectedError,
31 OrchestratorDispatchError,
32 OrchestratorProjectionError,
33} from "../../orchestration-v2/Orchestrator.ts";
34β
35import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
36import * as ServerConfig from "../../config.ts";
37import * as ProviderAdapterRegistry from "../../orchestration-v2/ProviderAdapterRegistry.ts";
38import * as ThreadLaunchService from "../../orchestration-v2/ThreadLaunchService.ts";
39import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts";
40import * as ThreadManagement from "../../orchestration-v2/ThreadManagementService.ts";
41import * as ThreadSearch from "../../orchestration-v2/ThreadSearch.ts";
42import * as PreviewBrowser from "../../preview/PreviewBrowser.ts";
43import * as ProjectService from "../../project/ProjectService.ts";
44import * as ProviderRegistry from "../../provider/ProviderRegistry.ts";
45import * as SecretRequests from "../../secrets/SecretRequests.ts";
46import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts";
47import * as ServerSettings from "../../serverSettings.ts";
48import * as McpHttpServer from "../McpHttpServer.ts";
49import * as McpInvocationContext from "../McpInvocationContext.ts";
50import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts";
51import { dispatchFailure } from "../threadAccess.ts";
52import * as EnvironmentHandlers from "./environment/handlers.ts";
53import * as AttachmentHandlers from "./attachment/handlers.ts";
54β
55const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
56 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
57 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
58);
59β
60// Effect returns a declared tool failure as `isError` with its encoded payload
61// as JSON text, never as `structuredContent`.
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("keeps unexpected handler defects private through the production registration", () =>
291 Effect.gen(function* () {
292 const server = yield* McpServer.McpServer;
293 const result = yield* server
294 .callTool({ name: "t3_thread_organize", arguments: { action: "pin" } })
295 .pipe(
296 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
297 Effect.provideService(McpSchema.McpServerClient, client),
298 );
299 expect(result.isError).toBe(true);
300 expect(result.structuredContent).toBeUndefined();
301 expect(result.content).toEqual([
302 { type: "text", text: "Tool execution failed due to an internal server error." },
303 ]);
304 }).pipe(
305 Effect.provide(
306 layerThreadToolkit.pipe(
307 Layer.provideMerge(McpServer.McpServer.layer),
308 Layer.provide(NodeCrypto.layer),
309 Layer.provide(
310 Layer.mock(ThreadManagement.ThreadManagementService)({
311 getThreadShell: () => Effect.die(new Error("private-storage-path")),
312 }),
313 ),
314 ),
315 ),
316 ),
317);
318β
319it("keeps MCP preference output allowlisted and Unicode-bounded", () => {
320 const settings = {
321 ...DEFAULT_SERVER_SETTINGS,
322 privateCredential: "must-not-escape",
323 sourceControlWritingStyle: {
324 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
325 customInstructions: "π".repeat(4001),
326 },
327 };
328 const result = EnvironmentHandlers.preferences(settings);
329 expect(result).not.toHaveProperty("privateCredential");
330 expect(result).not.toHaveProperty("providers");
331 expect(result.sourceControlWritingStyle).toMatchObject({
332 customInstructions: "π".repeat(4000),
333 truncated: true,
334 });
335});
336β
337it.effect("resolves reused attachment references from stored metadata", () =>
338 Effect.gen(function* () {
339 const stored = ChatImageAttachment.make({
340 type: "image",
341 id: "owned-image",
342 name: "original.png",
343 mimeType: "image/png",
344 sizeBytes: 12,
345 source: {
346 kind: "snap-shot",
347 capturedAt: "2026-09-10T00:00:00.000Z",
348 appName: "Terminal",
349 windowTitle: "Test",
350 accessibility: { format: "flat-text", text: "Stored context", truncated: false },
351 },
352 });
353 const forged = yield* decodeMcpAttachmentInput({
354 type: "image",
355 id: stored.id,
356 name: "changed.jpg",
357 mimeType: "image/jpeg",
358 sizeBytes: 99,
359 });
360 const result = yield* AttachmentHandlers.resolveAttachmentReferences([forged], [stored]);
361 expect(result).toEqual([stored]);
362 const failure = yield* AttachmentHandlers.resolveAttachmentReferences(
363 [{ ...forged, id: "other-image" }],
364 [stored],
365 ).pipe(Effect.flip);
366 expect(failure.code).toBe("invalid_request");
367 }),
368);
369β
370const clientScope = (
371 access: McpInvocationContext.McpClientCaller["access"],
372): McpInvocationContext.McpInvocationScope => ({
373 environmentId: EnvironmentId.make("mcp-core-environment"),
374 requestNamespace: "client:session-1",
375 thread: undefined,
376 client: { sessionId: "session-1", label: "Claude Code", access },
377 issuedAt: 0,
378 capabilities: new Set(["orchestration", "worktree", "pull-requests"]),
379});
380β
381it.effect("a client caller targets any thread within its ceiling and cannot act as a thread", () =>
382 Effect.gen(function* () {
383 const server = yield* McpServer.McpServer;
384 const call = (
385 name: string,
386 args: Record<string, unknown>,
387 invocation: McpInvocationContext.McpInvocationScope,
388 ) =>
389 server
390 .callTool({ name, arguments: args })
391 .pipe(
392 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
393 Effect.provideService(McpSchema.McpServerClient, client),
394 );
395β
396 const untargeted = yield* call("t3_thread_organize", { action: "pin" }, clientScope("auto"));
397 expect(declaredFailure(untargeted)).toMatchObject({ code: "target_required" });
398β
399 const pinned = yield* call(
400 "t3_thread_organize",
401 { action: "pin", threadId: "other-project-thread" },
402 clientScope("auto"),
403 );
404 expect(pinned.isError).toBe(false);
405 expect(pinned.structuredContent).toMatchObject({ sequence: 7 });
406β
407 const aboveCeiling = yield* call(
408 "t3_thread_organize",
409 { action: "pin", threadId: "other-project-thread" },
410 clientScope("approval-required"),
411 );
412 expect(declaredFailure(aboveCeiling)).toMatchObject({
413 code: "runtime_mode_escalation_denied",
414 });
415β
416 const forked = yield* call(
417 "t3_thread_fork",
418 { sourcePoint: { type: "latest_stable" } },
419 clientScope("auto"),
420 );
421 expect(declaredFailure(forked)).toMatchObject({ code: "target_required" });
422 }).pipe(
423 Effect.provide(
424 layerThreadToolkit.pipe(
425 Layer.provideMerge(McpServer.McpServer.layer),
426 Layer.provide(NodeCrypto.layer),
427 Layer.provide(
428 Layer.mock(ThreadManagement.ThreadManagementService)({
429 getThreadShell: (id) =>
430 Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" })),
431 getProjectThreadRecords: () =>
432 Effect.succeed({
433 thread: {
434 id: ThreadId.make("other-project-thread"),
435 projectId: "other-project",
436 runtimeMode: "auto",
437 interactionMode: "default",
438 deletedAt: null,
439 },
440 } as never),
441 dispatch: () => Effect.succeed({ sequence: 7, storedEvents: [] }),
442 }),
443 ),
444 ),
445 ),
446 ),
447);
448β
449it.effect("a read-only client reads threads and is refused every write before it runs", () =>
450 Effect.gen(function* () {
451 const server = yield* McpServer.McpServer;
452 const call = (name: string, args: Record<string, unknown>) =>
453 server
454 .callTool({ name, arguments: args })
455 .pipe(
456 Effect.provideService(
457 McpInvocationContext.McpInvocationContext,
458 clientScope("read-only"),
459 ),
460 Effect.provideService(McpSchema.McpServerClient, client),
461 );
462β
463 const configuration = yield* call("t3_thread_configuration", {
464 threadId: "other-project-thread",
465 });
466 expect(configuration.isError).toBe(false);
467 expect(configuration.structuredContent).toMatchObject({ runtimeMode: "auto" });
468β
469 const pinned = yield* call("t3_thread_organize", {
470 action: "pin",
471 threadId: "other-project-thread",
472 });
473 expect(declaredFailure(pinned)).toMatchObject({ code: "capability_denied" });
474 expect(dispatched).toEqual([]);
475β
476 const configure = yield* call("t3_thread_configure", {
477 threadId: "other-project-thread",
478 modelSelection: { instanceId: "codex", model: "gpt-5" },
479 });
480 expect(declaredFailure(configure)).toMatchObject({ code: "capability_denied" });
481 expect(dispatched).toEqual([]);
482 }).pipe(
483 Effect.provide(
484 layerThreadToolkit.pipe(
485 Layer.provideMerge(McpServer.McpServer.layer),
486 Layer.provide(NodeCrypto.layer),
487 Layer.provide(
488 Layer.mock(ThreadManagement.ThreadManagementService)({
489 getThreadShell: () =>
490 Effect.succeed({
491 id: ThreadId.make("other-project-thread"),
492 projectId: "other-project",
493 deletedAt: null,
494 } as never),
495 getProjectThreadRecords: () =>
496 Effect.succeed({
497 thread: {
498 id: ThreadId.make("other-project-thread"),
499 projectId: "other-project",
500 modelSelection: { instanceId: "codex", model: "gpt-5" },
501 runtimeMode: "auto",
502 interactionMode: "default",
503 deletedAt: null,
504 },
505 } as never),
506 dispatch: () =>
507 Effect.sync(() => {
508 dispatched.push("dispatch");
509 return { sequence: 7 } as never;
510 }),
511 }),
512 ),
513 ),
514 ),
515 ),
516);
517const dispatched: Array<string> = [];
518β
519it.effect("refuses act-as-caller tools to a client caller", () =>
520 Effect.gen(function* () {
521 const server = yield* McpServer.McpServer;
522 const result = yield* server
523 .callTool({
524 name: "delegate_task",
525 arguments: { task: "Review", mode: "async" },
526 })
527 .pipe(
528 Effect.provideService(
529 McpInvocationContext.McpInvocationContext,
530 clientScope("full-access"),
531 ),
532 Effect.provideService(McpSchema.McpServerClient, client),
533 );
534 expect(declaredFailure(result)).toMatchObject({ code: "thread_credential_required" });
535 }).pipe(
536 Effect.provide(
537 layerOrchestratorToolkit.pipe(
538 Layer.provideMerge(McpServer.McpServer.layer),
539 Layer.provide(NodeCrypto.layer),
540 Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
541 Layer.provide(ServerSettings.layerTest()),
542 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
543 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
544 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
545 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
546 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
547 ),
548 ),
549 ),
550);
551β
552it.effect("a caller cannot rewrite a scheduled task that runs above its own modes", () =>
553 Effect.gen(function* () {
554 const server = yield* McpServer.McpServer;
555 const call = (name: string, args: Record<string, unknown>) =>
556 server
557 .callTool({ name, arguments: args })
558 .pipe(
559 Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")),
560 Effect.provideService(McpSchema.McpServerClient, client),
561 );
562 const update = yield* call("update_scheduled_task", {
563 scheduledTaskId: "task-full-access",
564 prompt: "Run something else",
565 });
566 expect(declaredFailure(update)).toMatchObject({ code: "runtime_mode_escalation_denied" });
567 const remove = yield* call("delete_scheduled_task", { scheduledTaskId: "task-full-access" });
568 expect(declaredFailure(remove)).toMatchObject({ code: "runtime_mode_escalation_denied" });
569 const allowed = yield* call("update_scheduled_task", {
570 scheduledTaskId: "task-auto",
571 enabled: false,
572 });
573 expect(allowed.isError).toBe(false);
574 }).pipe(
575 Effect.provide(
576 layerOrchestratorToolkit.pipe(
577 Layer.provideMerge(McpServer.McpServer.layer),
578 Layer.provide(NodeCrypto.layer),
579 Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})),
580 Layer.provide(ServerSettings.layerTest()),
581 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
582 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
583 Layer.provide(
584 Layer.mock(ScheduledTaskService.ScheduledTaskService)({
585 list: () =>
586 Effect.succeed({
587 tasks: [
588 scheduledTask("task-full-access", "full-access"),
589 scheduledTask("task-auto", "auto"),
590 ],
591 }),
592 upsert: (input) =>
593 Effect.succeed({
594 task: { ...(scheduledTask(input.id ?? "task-auto", "auto") as object), ...input },
595 } as never),
596 }),
597 ),
598 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
599 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
600 ),
601 ),
602 ),
603);
604β
605function scheduledTask(id: string, runtimeMode: "auto" | "full-access"): never {
606 return {
607 id,
608 title: id,
609 prompt: "Check the build",
610 enabled: true,
611 projectId: "project-a",
612 threadId: null,
613 schedule: { type: "interval", everyMs: 3_600_000 },
614 workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true },
615 modelSelection: { instanceId: "codex", model: "gpt-5" },
616 runtimeMode,
617 interactionMode: "default",
618 createdBy: "user",
619 creationSource: "web",
620 nextRunAt: null,
621 lastRunStatus: "never",
622 lastRunAt: null,
623 lastRunThreadId: null,
624 lastRunError: null,
625 runCount: 0,
626 createdAt: "2026-10-01T00:00:00.000Z",
627 updatedAt: "2026-10-01T00:00:00.000Z",
628 } as never;
629}
630β
631it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
632 "a caller cannot use %s on a thread that runs above its own modes",
633 (toolName) =>
634 Effect.gen(function* () {
635 const server = yield* McpServer.McpServer;
636 const result = yield* server
637 .callTool({
638 name: toolName,
639 arguments: {
640 threadId: "full-access-thread",
641 ...(toolName === "t3_workflow_stop" ? { subagentId: "workflow-coordinator" } : {}),
642 },
643 })
644 .pipe(
645 Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")),
646 Effect.provideService(McpSchema.McpServerClient, client),
647 );
648 expect(declaredFailure(result)).toMatchObject({ code: "runtime_mode_escalation_denied" });
649 }).pipe(
650 Effect.provide(
651 layerOrchestratorToolkit.pipe(
652 Layer.provideMerge(McpServer.McpServer.layer),
653 Layer.provide(NodeCrypto.layer),
654 Layer.provide(
655 Layer.mock(ThreadManagement.ThreadManagementService)({
656 getThreadShell: () =>
657 Effect.succeed({
658 projectId: "project-a",
659 deletedAt: null,
660 runtimeMode: "full-access",
661 interactionMode: "default",
662 } as never),
663 getProjectThreadRecords: () =>
664 Effect.succeed({
665 thread: {
666 id: ThreadId.make("full-access-thread"),
667 projectId: "project-a",
668 runtimeMode: "full-access",
669 interactionMode: "default",
670 deletedAt: null,
671 },
672 runs: [],
673 } as never),
674 stopWorkflow: () => Effect.die("workflow stop must not dispatch above the ceiling"),
675 interruptThread: () => Effect.die("interrupt must not dispatch above the ceiling"),
676 }),
677 ),
678 Layer.provide(ServerSettings.layerTest()),
679 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
680 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
681 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
682 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
683 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
684 ),
685 ),
686 ),
687);
688β
689it.effect("discovers workflow stop targets and requires orchestration capability", () => {
690 const threadId = ThreadId.make("workflow-parent");
691 const shell = McpToolAccessTestkit.liveThreadShell(threadId);
692 const subagentId = NodeId.make("workflow-coordinator");
693 const itemId = TurnItemId.make("workflow-coordinator-activity");
694 const row: OrchestrationV2ProjectedTurnItem = {
695 position: 0,
696 visibility: "local",
697 sourceThreadId: threadId,
698 sourceItemId: itemId,
699 item: {
700 id: itemId,
701 threadId,
702 runId: shell.activeRunId,
703 nodeId: subagentId,
704 providerThreadId: null,
705 providerTurnId: null,
706 nativeItemRef: null,
707 parentItemId: null,
708 ordinal: 0,
709 status: "running",
710 title: "Workflow: checkout review",
711 startedAt: shell.createdAt,
712 completedAt: null,
713 updatedAt: shell.updatedAt,
714 type: "subagent",
715 subagentId,
716 origin: "provider_native",
717 driver: ProviderDriverKind.make("claudeAgent"),
718 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
719 childThreadId: ThreadId.make("workflow-child"),
720 prompt: "Review checkout",
721 result: null,
722 },
723 };
724 const stopped: Array<{ readonly threadId: ThreadId; readonly subagentId: string }> = [];
725 return Effect.gen(function* () {
726 const server = yield* McpServer.McpServer;
727 const scope = clientScope("full-access");
728 const read = yield* server
729 .callTool({ name: "t3_thread_read", arguments: { threadId, view: "activity" } })
730 .pipe(
731 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
732 Effect.provideService(McpSchema.McpServerClient, client),
733 );
734 expect(read.isError).toBe(false);
735 const result = yield* decodeThreadReadResult(read.structuredContent);
736 expect(result.items[0]?.subagentId).toBe(subagentId);
737 const call = (invocation: McpInvocationContext.McpInvocationScope) =>
738 server
739 .callTool({
740 name: "t3_workflow_stop",
741 arguments: { threadId, subagentId: result.items[0]?.subagentId },
742 })
743 .pipe(
744 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
745 Effect.provideService(McpSchema.McpServerClient, client),
746 );
747 const denied = yield* call({ ...scope, capabilities: new Set(["worktree"]) });
748 expect(declaredFailure(denied)).toMatchObject({ code: "capability_denied" });
749 expect(stopped).toEqual([]);
750 const allowed = yield* call(scope);
751 expect(allowed.isError).toBe(false);
752 expect(stopped).toEqual([{ threadId: "workflow-parent", subagentId: "workflow-coordinator" }]);
753 }).pipe(
754 Effect.provide(
755 layerOrchestratorToolkit.pipe(
756 Layer.provideMerge(McpServer.McpServer.layer),
757 Layer.provide(NodeCrypto.layer),
758 Layer.provide(
759 Layer.mock(ThreadManagement.ThreadManagementService)({
760 getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)),
761 getProjectThreadRecords: () =>
762 Effect.succeed(McpToolAccessTestkit.idleThreadProjection(shell)),
763 getTimelinePage: () => Effect.succeed({ items: [row], totalItems: 1, hasMore: false }),
764 stopWorkflow: (input) =>
765 Effect.sync(() => {
766 stopped.push(input);
767 }),
768 }),
769 ),
770 Layer.provide(ServerSettings.layerTest()),
771 Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
772 Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
773 Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
774 Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
775 Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
776 ),
777 ),
778 );
779});
780β
781it.effect("only the caller that prepared a pending upload can discard it", () =>
782 Effect.gen(function* () {
783 const server = yield* McpServer.McpServer;
784 const call = (
785 name: string,
786 args: Record<string, unknown>,
787 invocation: McpInvocationContext.McpInvocationScope,
788 ) =>
789 server
790 .callTool({ name, arguments: args })
791 .pipe(
792 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
793 Effect.provideService(McpSchema.McpServerClient, client),
794 );
795 const prepared = yield* call(
796 "t3_attachment_prepare_upload",
797 { upload: { name: "shot.png", mimeType: "image/png", sizeBytes: 4 } },
798 scope,
799 );
800 const { attachmentId } = prepared.structuredContent as { readonly attachmentId: string };
801 const otherThread = {
802 ...scope,
803 requestNamespace: "other-session",
804 thread: { ...scope.thread!, threadId: ThreadId.make("other-thread") },
805 };
806β
807 const refused = yield* call("t3_attachment_discard", { attachmentId }, otherThread);
808 expect(declaredFailure(refused)).toMatchObject({ code: "invalid_request" });
809β
810 yield* TestClock.adjust(24 * 60 * 60 * 1000 + 5 * 60_000);
811 yield* call(
812 "t3_attachment_prepare_upload",
813 { upload: { name: "later.png", mimeType: "image/png", sizeBytes: 4 } },
814 scope,
815 );
816β
817 const discarded = yield* call(
818 "t3_attachment_discard",
819 { attachmentId },
820 { ...scope, requestNamespace: "mcp-core-session-2" },
821 );
822 expect(discarded.isError).toBe(false);
823 }).pipe(
824 Effect.provide(
825 McpHttpServer.layerAttachmentToolkit.pipe(
826 Layer.provideMerge(McpServer.McpServer.layer),
827 Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
828 Layer.provide(ServerSecretStore.layer),
829 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-attachment-" })),
830 Layer.provide(NodeServices.layer),
831 ),
832 ),
833 ),
834);