Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

core.test.ts

1,007 lines37.5 KB

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