Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import type * as Types from "effect/Types";
14import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
15import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16import {
17 DeviceToolError,
18 OrchestratorMcpFailure,
19 PreviewAutomationError,
20 type RunId,
21 ThreadId,
22} from "@t3tools/contracts";
23
24import packageJson from "../../package.json" with { type: "json" };
25import * as ServerConfig from "../config.ts";
26import * as DeviceService from "../device/DeviceService.ts";
27import * as HtmlRender from "../htmlRender/HtmlRender.ts";
28import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
29import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
30import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
31import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
32import {
33 type AgentThread,
34 agentToolProperties,
35 handoffSettings,
36 MAX_REPORTED_DEPTH,
37 toolOutcome,
38} from "../telemetry/ProviderDimensions.ts";
39import * as McpInvocationContext from "./McpInvocationContext.ts";
40import * as McpToolAccess from "./McpToolAccess.ts";
41import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
42import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
43import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
44import { EnvironmentToolkit } from "./toolkits/environment/tools.ts";
45import * as EnvironmentHandlers from "./toolkits/environment/handlers.ts";
46import { ProjectToolkit } from "./toolkits/project/tools.ts";
47import * as ProjectHandlers from "./toolkits/project/handlers.ts";
48import { AttachmentToolkit } from "./toolkits/attachment/tools.ts";
49import * as AttachmentHandlers from "./toolkits/attachment/handlers.ts";
50import { ThreadToolkit } from "./toolkits/thread/tools.ts";
51import * as ThreadHandlers from "./toolkits/thread/handlers.ts";
52import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
53import * as McpSessionRegistry from "./McpSessionRegistry.ts";
54import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
55import * as OrchestratorHandlers from "./toolkits/orchestrator/handlers.ts";
56import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
57import * as PreviewHandlers from "./toolkits/preview/handlers.ts";
58import {
59 PreviewSnapshotTool,
60 PreviewSnapshotToolkit,
61 PreviewStandardToolkit,
62} from "./toolkits/preview/tools.ts";
63import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
64import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
65import * as WorktreeMcpService from "./WorktreeMcpService.ts";
66import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
67import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
68import * as DeviceHandlers from "./toolkits/device/handlers.ts";
69import {
70 DeviceScreenshotTool,
71 DeviceScreenshotToolkit,
72 DeviceStandardToolkit,
73} from "./toolkits/device/tools.ts";
74import * as HtmlHandlers from "./toolkits/html/handlers.ts";
75import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts";
76
77const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) =>
78 HttpServerRequest.toURL(request).pipe(
79 Option.map((url) => `${url.origin}/.well-known/oauth-protected-resource/mcp`),
80 );
81
82/** Launched agents cannot open OAuth browsers; OAuth would mint credentials outliving their session. */
83const unauthorized = (input: {
84 readonly request: HttpServerRequest.HttpServerRequest;
85 readonly presentedToken: boolean;
86 readonly offerOAuth: boolean;
87}) => {
88 const metadataUrl = input.offerOAuth
89 ? Option.getOrUndefined(mcpResourceMetadataUrl(input.request))
90 : undefined;
91 const challenge = [
92 "Bearer",
93 [
94 ...(metadataUrl === undefined ? [] : [`resource_metadata="${metadataUrl}"`]),
95 ...(input.presentedToken ? ['error="invalid_token"'] : []),
96 ].join(", "),
97 ]
98 .filter((part) => part.length > 0)
99 .join(" ");
100 return HttpServerResponse.jsonUnsafe(
101 {
102 error: "invalid_mcp_credential",
103 message: "A valid T3 Code MCP credential is required.",
104 },
105 {
106 status: 401,
107 headers: {
108 "cache-control": "no-store",
109 "www-authenticate": challenge,
110 },
111 },
112 );
113};
114
115export class McpClientAuthenticator extends Context.Service<
116 McpClientAuthenticator,
117 {
118 readonly authenticate: (
119 request: HttpServerRequest.HttpServerRequest,
120 ) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
121 }
122>()("t3/mcp/McpHttpServer/McpClientAuthenticator") {}
123
124type AuthenticatedHttpEffect = Effect.Effect<
125 HttpServerResponse.HttpServerResponse,
126 Types.unhandled,
127 McpInvocationContext.McpInvocationContext
128>;
129
130type McpAuthMiddleware = (
131 httpEffect: AuthenticatedHttpEffect,
132) => Effect.Effect<
133 HttpServerResponse.HttpServerResponse,
134 Types.unhandled,
135 HttpServerRequest.HttpServerRequest
136>;
137
138const normalizeMcpHttpResponse = (
139 response: HttpServerResponse.HttpServerResponse,
140): HttpServerResponse.HttpServerResponse => {
141 const bodyIsEmpty =
142 response.body._tag === "Empty" ||
143 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
144 (response.body._tag === "Raw" && response.body.contentLength === 0);
145 return response.status === 200 && bodyIsEmpty
146 ? HttpServerResponse.setStatus(response, 202)
147 : response;
148};
149
150// Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
151const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
152
153const makeMcpAuthMiddleware = Effect.gen(function* () {
154 const registry = yield* McpSessionRegistry.McpSessionRegistry;
155 const clients = yield* Effect.serviceOption(McpClientAuthenticator);
156 return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
157 const request = yield* HttpServerRequest.HttpServerRequest;
158 const authorization = request.headers.authorization;
159 const token =
160 authorization?.startsWith("Bearer ") === true
161 ? authorization.slice("Bearer ".length).trim()
162 : "";
163 const invocation =
164 (yield* registry.resolve(token)) ??
165 (Option.isSome(clients) && token.length > 0
166 ? yield* clients.value.authenticate(request)
167 : undefined);
168 if (!invocation) {
169 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
170 reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
171 });
172 return unauthorized({
173 request,
174 presentedToken: token.length > 0,
175 offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
176 });
177 }
178 return yield* httpEffect.pipe(
179 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
180 Effect.map(normalizeMcpHttpResponse),
181 );
182 }) satisfies McpAuthMiddleware;
183}).pipe(Effect.withSpan("McpHttpServer.makeAuthMiddleware"));
184
185const layerMcpAuthMiddleware = HttpRouter.middleware<{
186 provides: McpInvocationContext.McpInvocationContext;
187}>()(makeMcpAuthMiddleware).layer;
188
189/** Claude Code spills oversized results to files, losing locators; bound both text and its preferred structuredContent. */
190export const MAX_SNAPSHOT_TEXT_BYTES = 20_000;
191const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;
192const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;
193const MAX_SNAPSHOT_LOG_ENTRIES = 40;
194const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500;
195const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048;
196
197const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
198const utf8Length = (text: string) => Buffer.byteLength(text, "utf8");
199const cutText = (text: string, max: number) =>
200 text.length > max ? `${text.slice(0, max)}…` : text;
201
202const cutEntryStrings = <A>(entry: A): A =>
203 typeof entry === "object" && entry !== null
204 ? (Object.fromEntries(
205 Object.entries(entry).map(([key, value]) => [
206 key,
207 typeof value === "string" ? cutText(value, MAX_SNAPSHOT_LOG_TEXT_CHARS) : value,
208 ]),
209 ) as A)
210 : entry;
211
212const hasLongString = (entry: unknown, max: number) =>
213 typeof entry === "object" &&
214 entry !== null &&
215 Object.values(entry).some((value) => typeof value === "string" && value.length > max);
216
217type SnapshotMetadata = {
218 readonly url: string;
219 readonly title: string;
220 readonly visibleText: string;
221 readonly interactiveElements: ReadonlyArray<{
222 readonly name: string;
223 readonly [key: string]: unknown;
224 }>;
225 readonly consoleEntries: ReadonlyArray<unknown>;
226 readonly networkEntries: ReadonlyArray<unknown>;
227 readonly actionTimeline: ReadonlyArray<unknown>;
228 readonly [key: string]: unknown;
229};
230
231const boundSnapshotMetadata = (metadata: SnapshotMetadata) => {
232 const omitted: Array<string> = [];
233 const { accessibilityTree, ...withoutTree } = metadata;
234 const ariaTree = typeof accessibilityTree === "string" ? accessibilityTree : undefined;
235 if (accessibilityTree !== undefined && ariaTree === undefined) {
236 omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)");
237 }
238 const tail = <A>(entries: ReadonlyArray<A>, label: string) => {
239 if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) {
240 omitted.push(`${entries.length - MAX_SNAPSHOT_LOG_ENTRIES} older ${label}`);
241 }
242 const kept = entries.slice(-MAX_SNAPSHOT_LOG_ENTRIES);
243 if (kept.some((entry) => hasLongString(entry, MAX_SNAPSHOT_LOG_TEXT_CHARS))) {
244 omitted.push(`${label} text after ${MAX_SNAPSHOT_LOG_TEXT_CHARS} characters`);
245 }
246 return kept.map(cutEntryStrings);
247 };
248 if (
249 metadata.url.length > MAX_SNAPSHOT_IDENTIFIER_CHARS ||
250 metadata.title.length > MAX_SNAPSHOT_IDENTIFIER_CHARS
251 ) {
252 omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`);
253 }
254 if (
255 metadata.interactiveElements.some(
256 (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS,
257 )
258 ) {
259 omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`);
260 }
261 const bounded = {
262 ...withoutTree,
263 url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
264 title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS),
265 interactiveElements: metadata.interactiveElements.map((element) => ({
266 ...element,
267 name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS),
268 })),
269 consoleEntries: tail(metadata.consoleEntries, "console entries"),
270 networkEntries: tail(metadata.networkEntries, "network entries"),
271 actionTimeline: tail(metadata.actionTimeline, "action timeline entries"),
272 };
273
274 // Per-field character caps can still exceed the total byte ceiling.
275 const shedOrder = [
276 "actionTimeline",
277 "networkEntries",
278 "consoleEntries",
279 "interactiveElements",
280 ] as const;
281 const lists: Record<(typeof shedOrder)[number], ReadonlyArray<unknown>> = {
282 interactiveElements: bounded.interactiveElements,
283 consoleEntries: bounded.consoleEntries,
284 networkEntries: bounded.networkEntries,
285 actionTimeline: bounded.actionTimeline,
286 };
287 const dropped: Record<(typeof shedOrder)[number], number> = {
288 interactiveElements: 0,
289 consoleEntries: 0,
290 networkEntries: 0,
291 actionTimeline: 0,
292 };
293 let visibleTextChars = Math.min(metadata.visibleText.length, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS);
294 let ariaTreeChars = Math.min(ariaTree?.length ?? 0, 20_000);
295 const value = () => ({
296 ...bounded,
297 ...(ariaTree === undefined ? {} : { accessibilityTree: cutText(ariaTree, ariaTreeChars) }),
298 visibleText: cutText(metadata.visibleText, visibleTextChars),
299 ...lists,
300 });
301 let text = encodeJsonText(value());
302 while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) {
303 // Elements carry the locators, so they go last; logs shed newest-last.
304 const key =
305 shedOrder.find(
306 (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0,
307 ) ??
308 (visibleTextChars > 0
309 ? "visibleText"
310 : lists.interactiveElements.length > 0
311 ? "interactiveElements"
312 : ariaTreeChars > 0
313 ? "accessibilityTree"
314 : undefined);
315 if (key === undefined) break;
316 if (key === "visibleText") {
317 visibleTextChars = Math.floor(visibleTextChars / 2);
318 } else if (key === "accessibilityTree") {
319 ariaTreeChars = Math.floor(ariaTreeChars / 2);
320 } else {
321 const keep = Math.floor(lists[key].length / 2);
322 dropped[key] += lists[key].length - keep;
323 lists[key] =
324 keep === 0
325 ? []
326 : key === "interactiveElements"
327 ? lists[key].slice(0, keep)
328 : lists[key].slice(-keep);
329 }
330 text = encodeJsonText(value());
331 }
332 if (visibleTextChars < metadata.visibleText.length) {
333 omitted.push(
334 `visibleText after ${visibleTextChars} characters (use preview_evaluate for more)`,
335 );
336 }
337 if (ariaTree !== undefined && ariaTreeChars < ariaTree.length) {
338 omitted.push(`accessibilityTree after ${ariaTreeChars} characters`);
339 }
340 for (const key of shedOrder) {
341 if (dropped[key] > 0) {
342 omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);
343 }
344 }
345 return { value: value(), text, omitted };
346};
347
348export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(
349 "PreviewScreenshotSaveError",
350 { screenshotPath: Schema.String, cause: Schema.Defect() },
351) {
352 override get message(): string {
353 return `Could not save preview screenshot to ${this.screenshotPath}.`;
354 }
355}
356
357const MAX_SCREENSHOT_SITE_SLUG_LENGTH = 40;
358
359const screenshotSiteSlug = (rawUrl: string): string => {
360 try {
361 const slug = new URL(rawUrl).hostname
362 .toLowerCase()
363 .replace(/[^a-z0-9]+/g, "-")
364 .replace(/^-+|-+$/g, "")
365 .slice(0, MAX_SCREENSHOT_SITE_SLUG_LENGTH)
366 .replace(/-+$/g, "");
367 return slug || "site";
368 } catch {
369 return "site";
370 }
371};
372
373const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
374 pageUrl: string,
375 data: Uint8Array,
376) {
377 const config = yield* ServerConfig.ServerConfig;
378 const fileSystem = yield* FileSystem.FileSystem;
379 const path = yield* Path.Path;
380 const millis = yield* Clock.currentTimeMillis;
381 const crypto = yield* Crypto.Crypto;
382 const unique = (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).slice(0, 8);
383 const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${unique}.png`;
384 const screenshotPath = path.join(config.browserArtifactsDir, fileName);
385 yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
386 Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
387 Effect.mapError((cause) => new PreviewScreenshotSaveError({ screenshotPath, cause })),
388 );
389 return screenshotPath;
390});
391
392/** Decode with the advertised JSON codec, which permits null for optional fields that the raw schema rejects. */
393const decodeAsAdvertised = <Tools extends Record<string, Tool.Any>>(
394 toolkit: Toolkit.Toolkit<Tools>,
395): Toolkit.Toolkit<Tools> =>
396 Toolkit.make(
397 ...Object.values(toolkit.tools).map((tool) =>
398 tool.setParameters(Schema.toCodecJson(tool.parametersSchema)),
399 ),
400 ) as unknown as Toolkit.Toolkit<Tools>;
401
402const isPreviewAutomationError = Schema.is(PreviewAutomationError);
403
404const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
405 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
406 return Effect.failCause(cause).pipe(Effect.orDie);
407 }
408 const failures = cause.reasons.filter(Cause.isFailReason);
409 const firstFailure = failures[0]?.error;
410 const errorTag =
411 typeof firstFailure === "object" &&
412 firstFailure !== null &&
413 "_tag" in firstFailure &&
414 typeof firstFailure._tag === "string"
415 ? firstFailure._tag
416 : "PreviewSnapshotError";
417 // Preview errors contain server-authored recovery guidance, never page output.
418 const message = isPreviewAutomationError(firstFailure) ? firstFailure.message : undefined;
419 const result = new McpSchema.CallToolResult({
420 isError: true,
421 structuredContent: {
422 error: {
423 _tag: errorTag,
424 operation: "snapshot",
425 failureCount: failures.length,
426 ...(message === undefined ? {} : { message }),
427 },
428 },
429 // Some clients show only the text content and others only structuredContent, so both carry it.
430 content: [{ type: "text", text: `Preview snapshot failed: ${message ?? `${errorTag}.`}` }],
431 });
432 return Effect.logWarning("preview snapshot failed", {
433 operation: "snapshot",
434 errorTag,
435 failureCount: failures.length,
436 }).pipe(Effect.as(result));
437};
438
439const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
440 const server = yield* McpServer.McpServer;
441 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
442 const threads = yield* ThreadManagementService.ThreadManagementService;
443 const saveServices = yield* Effect.context<
444 ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto
445 >();
446 const built = yield* decodeAsAdvertised(PreviewSnapshotToolkit);
447 const tool = PreviewSnapshotTool;
448 yield* server.addTool({
449 tool: new McpSchema.Tool({
450 name: tool.name,
451 description: Tool.getDescription(tool),
452 inputSchema: Tool.getJsonSchema(tool),
453 annotations: {
454 ...Context.getOption(tool.annotations, Tool.Title).pipe(
455 Option.map((title) => ({ title })),
456 Option.getOrUndefined,
457 ),
458 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
459 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
460 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
461 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
462 },
463 }),
464 annotations: tool.annotations,
465 handle: (payload) =>
466 Effect.withFiber((fiber) => {
467 const invocation = Context.getUnsafe(
468 fiber.context,
469 McpInvocationContext.McpInvocationContext,
470 );
471 return built.handle("preview_snapshot", payload).pipe(
472 Stream.unwrap,
473 Stream.run(Sink.last()),
474 Effect.flatMap(Effect.fromOption),
475 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
476 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
477 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
478 Effect.flatMap(({ encodedResult }) =>
479 Effect.gen(function* () {
480 const snapshot = encodedResult as SnapshotMetadata & {
481 readonly url: string;
482 readonly screenshot: {
483 readonly mimeType: "image/png";
484 readonly data: string;
485 readonly width: number;
486 readonly height: number;
487 };
488 };
489 const { screenshot, ...page } = snapshot;
490 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
491 const screenshotPath =
492 payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
493 // Providers replay images on later requests, and some reject them; include images only when requested.
494 const includeImage = payload?.includeImage === true;
495 if (screenshotPath !== undefined && !includeImage) {
496 const saved = {
497 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
498 screenshotPath,
499 };
500 return new McpSchema.CallToolResult({
501 isError: false,
502 structuredContent: saved,
503 content: [{ type: "text", text: encodeJsonText(saved) }],
504 });
505 }
506 const metadata = {
507 ...page,
508 screenshot: {
509 mimeType: screenshot.mimeType,
510 width: screenshot.width,
511 height: screenshot.height,
512 },
513 ...(screenshotPath === undefined ? {} : { screenshotPath }),
514 };
515 const bounded = boundSnapshotMetadata(metadata);
516 return new McpSchema.CallToolResult({
517 isError: false,
518 structuredContent:
519 bounded.omitted.length === 0
520 ? bounded.value
521 : { ...bounded.value, omitted: bounded.omitted },
522 content: [
523 {
524 type: "text",
525 text: encodeJsonText({
526 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
527 }),
528 },
529 { type: "text", text: bounded.text },
530 ...(bounded.omitted.length === 0
531 ? []
532 : [
533 {
534 type: "text" as const,
535 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
536 },
537 ]),
538 ...(includeImage
539 ? [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]
540 : []),
541 ],
542 });
543 }),
544 ),
545 Effect.provide(saveServices),
546 Effect.matchCauseEffect({
547 onFailure: previewSnapshotFailure,
548 onSuccess: Effect.succeed,
549 }),
550 );
551 }),
552 });
553});
554
555interface ImageToolResult {
556 readonly screenshot: {
557 readonly mimeType: "image/png";
558 readonly data: string;
559 readonly width: number;
560 readonly height: number;
561 };
562 readonly [key: string]: unknown;
563}
564
565/** Expose only undescribed failures' tags; remote messages may contain renderer or device output. */
566const imageToolFailure =
567 <E>(toolName: string, operation: string, failureText: string | ((error: E) => string)) =>
568 (cause: Cause.Cause<E>) => {
569 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
570 return Effect.failCause(cause).pipe(Effect.orDie);
571 }
572 const failures = cause.reasons.filter(Cause.isFailReason);
573 const firstFailure = failures[0]?.error;
574 const errorTag =
575 typeof firstFailure === "object" &&
576 firstFailure !== null &&
577 "_tag" in firstFailure &&
578 typeof firstFailure._tag === "string"
579 ? firstFailure._tag
580 : `${toolName}Error`;
581 const message =
582 typeof failureText === "string" || failures[0] === undefined
583 ? undefined
584 : failureText(failures[0].error);
585 const result = new McpSchema.CallToolResult({
586 isError: true,
587 structuredContent: {
588 error: {
589 _tag: errorTag,
590 operation,
591 failureCount: failures.length,
592 ...(message === undefined ? {} : { message }),
593 },
594 },
595 // Some clients show only the text content and others only structuredContent, so both carry it.
596 content: [
597 {
598 type: "text",
599 text: typeof failureText === "string" ? failureText : (message ?? `${toolName} failed.`),
600 },
601 ],
602 });
603 return Effect.logWarning(`${toolName} failed`, {
604 operation,
605 errorTag,
606 failureCount: failures.length,
607 }).pipe(Effect.as(result));
608 };
609
610/**
611 * `McpServer.toolkit` serializes every result as JSON text, which is the wrong
612 * shape for a screenshot: the model needs image content.
613 */
614const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* <
615 T extends Tool.Any,
616 E,
617 R,
618>(
619 tool: T,
620 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
621 provide: (
622 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
623 ) => Effect.Effect<
624 { readonly encodedResult: unknown },
625 E,
626 McpInvocationContext.McpInvocationContext
627 >,
628 operation: string,
629 failureText: string | ((error: E) => string),
630) {
631 const server = yield* McpServer.McpServer;
632 yield* server.addTool({
633 tool: new McpSchema.Tool({
634 name: tool.name,
635 description: Tool.getDescription(tool),
636 inputSchema: Tool.getJsonSchema(tool),
637 annotations: {
638 ...Context.getOption(tool.annotations, Tool.Title).pipe(
639 Option.map((title) => ({ title })),
640 Option.getOrUndefined,
641 ),
642 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
643 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
644 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
645 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
646 },
647 }),
648 annotations: tool.annotations,
649 handle: (payload) =>
650 Effect.withFiber((fiber) => {
651 const invocation = Context.getUnsafe(
652 fiber.context,
653 McpInvocationContext.McpInvocationContext,
654 );
655 return provide(handle(payload as Tool.Parameters<T>)).pipe(
656 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
657 Effect.matchCauseEffect({
658 onFailure: imageToolFailure(tool.name, operation, failureText),
659 onSuccess: ({ encodedResult }) => {
660 const { screenshot, ...rest } = encodedResult as ImageToolResult;
661 const includeImage =
662 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
663 false;
664 const metadata = {
665 ...rest,
666 screenshot: {
667 mimeType: screenshot.mimeType,
668 width: screenshot.width,
669 height: screenshot.height,
670 },
671 };
672 return Effect.succeed(
673 new McpSchema.CallToolResult({
674 isError: false,
675 structuredContent: metadata,
676 content: [
677 { type: "text", text: JSON.stringify(metadata) },
678 ...(includeImage
679 ? [
680 {
681 type: "image" as const,
682 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
683 mimeType: screenshot.mimeType,
684 },
685 ]
686 : []),
687 ],
688 }),
689 );
690 },
691 }),
692 );
693 }),
694 });
695});
696
697const isDeviceToolError = Schema.is(DeviceToolError);
698
699const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
700 const devices = yield* DeviceService.DeviceService;
701 const threads = yield* ThreadManagementService.ThreadManagementService;
702 const built = yield* decodeAsAdvertised(DeviceScreenshotToolkit);
703 yield* registerImageTool(
704 DeviceScreenshotTool,
705 (payload) =>
706 built
707 .handle("device_screenshot", payload)
708 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
709 (effect) =>
710 effect.pipe(
711 Effect.provideService(DeviceService.DeviceService, devices),
712 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
713 ),
714 "screenshot",
715 (error) => {
716 if (!isDeviceToolError(error)) return "Device screenshot failed.";
717 return error._tag === "DeviceOperationError" && error.reason === "hub_rejected"
718 ? `${error.message} Call device_list to check the device state, and device_open if it needs to be reopened.`
719 : error.message;
720 },
721 );
722});
723
724const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
725
726const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
727 const htmlRender = yield* HtmlRender.HtmlRender;
728 const threads = yield* ThreadManagementService.ThreadManagementService;
729 const built = yield* decodeAsAdvertised(HtmlPreviewToolkit);
730 yield* registerImageTool(
731 HtmlPreviewTool,
732 (payload) =>
733 built
734 .handle("html_preview", payload)
735 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
736 (effect) =>
737 effect.pipe(
738 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
739 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
740 ),
741 "preview",
742
743 (error) =>
744 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
745 ? error.message
746 : "HTML preview failed.",
747 );
748});
749
750/**
751 * Tools that hand work to another thread's agent: they create it, message it,
752 * steer it, or move context into it. Their events name the receiving agent too.
753 */
754const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
755 "delegate_task",
756 "create_threads",
757 "t3_thread_launch",
758 "t3_thread_send",
759 "t3_thread_send_attachments",
760 "t3_thread_fork",
761 "t3_thread_merge_back",
762 "t3_queue_edit",
763 "t3_queue_promote_to_steer",
764 "t3_pending_request_respond",
765 "schedule_task",
766 "run_scheduled_task_now",
767]);
768
769/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */
770const INPUT_TARGET_TOOLS: ReadonlySet<string> = new Set([
771 "t3_queue_edit",
772 "t3_queue_promote_to_steer",
773 "t3_pending_request_respond",
774]);
775
776const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
777
778/** Thread ids a handoff tool result names: the thread that received the work. */
779const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
780 if (typeof content !== "object" || content === null) return [];
781 const record = content as Readonly<Record<string, unknown>>;
782 if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
783 const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
784 return key === undefined ? [] : [record[key] as string];
785};
786
787/**
788 * Thread ids that received a handoff. The input's `threadId` is used only after
789 * the call succeeded, so it is one the handler already resolved and authorized.
790 */
791const handoffTargetIds = (
792 tool: string,
793 args: unknown,
794 result: McpSchema.CallToolResult | undefined,
795): ReadonlyArray<string> => {
796 if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent);
797 if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
798 const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
799 return typeof threadId === "string" ? [threadId] : [];
800};
801
802/** Tool analytics must never include IDs, prompts or free text. */
803const withToolAnalytics =
804 /* Request instrumentation already owns the span; keep this helper in that context. */
805 Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
806 const server = yield* McpServer.McpServer;
807 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
808 if (Option.isNone(analytics)) return yield* registration;
809 const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
810 const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
811 const shellOf = (threadId: string) =>
812 Option.isNone(threads)
813 ? Effect.succeed(null)
814 : threads.value
815 .getThreadShell(ThreadId.make(threadId))
816 .pipe(Effect.orElseSucceed(() => null));
817 // Delegation depth: parents walked from the caller, capped.
818 const depthOf =
819 /* Request instrumentation already owns the span; keep this helper in that context. */
820 Effect.fnUntraced(function* (thread: AgentThread) {
821 let depth = 0;
822 let parentId =
823 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
824 while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
825 depth += 1;
826 const parent = yield* shellOf(parentId);
827 parentId =
828 parent?.lineage.relationshipToParent === "subagent"
829 ? parent.lineage.parentThreadId
830 : null;
831 }
832 return depth;
833 });
834 // Whether the caller's active run was started by a scheduled task.
835 const scheduledRunOf = (threadId: string, runId: RunId | null) =>
836 Option.isNone(threads) || runId === null
837 ? Effect.succeed(false)
838 : threads.value
839 .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
840 runIds: [runId],
841 messageRoles: ["user"],
842 })
843 .pipe(
844 Effect.map((records) => {
845 const run = records.runs.find((candidate) => candidate.id === runId);
846 return records.messages.some(
847 (message) =>
848 message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
849 );
850 }),
851 Effect.orElseSucceed(() => false),
852 );
853 const record =
854 /* Request instrumentation already owns the span; keep this helper in that context. */
855 Effect.fnUntraced(
856 function* (
857 tool: string,
858 args: unknown,
859 result: McpSchema.CallToolResult | undefined,
860 durationMs: number,
861 ) {
862 const handoff = HANDOFF_TOOLS.has(tool);
863 const outcome = toolOutcome(result);
864 // Agents call status, read, and preview tools in tight loops, so an
865 // event per successful call floods analytics. Only failures count there.
866 if (!handoff && outcome.outcome === "ok") return;
867 // Client credentials (no calling thread) report an unknown caller.
868 const invocation = Option.getOrUndefined(
869 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
870 )?.thread;
871 const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
872 // Only handoff tools pay for thread lookups; the rest report the
873 // caller's provider from the credential.
874 const caller =
875 handoff && invocation !== undefined
876 ? ((yield* shellOf(invocation.threadId)) ?? undefined)
877 : undefined;
878 const targetIds = handoff
879 ? [...new Set(handoffTargetIds(tool, args, result))].filter(
880 (threadId) => threadId !== invocation?.threadId,
881 )
882 : [];
883 const targets = yield* Effect.forEach(targetIds, shellOf);
884 for (const properties of agentToolProperties({
885 tool,
886 providers,
887 caller,
888 ...(invocation === undefined
889 ? {}
890 : { callerProviderInstanceId: invocation.providerInstanceId }),
891 ...(caller === undefined || invocation === undefined
892 ? {}
893 : {
894 callerDepth: yield* depthOf(caller),
895 callerScheduledRun: yield* scheduledRunOf(
896 invocation.threadId,
897 caller.activeRunId,
898 ),
899 }),
900 targets: targets.filter((thread) => thread !== null),
901 outcome,
902 ...(handoff
903 ? { settings: handoffSettings(tool, args, result?.structuredContent) }
904 : {}),
905 durationMs,
906 })) {
907 yield* analytics.value.record("mcp.tool.invoked", properties);
908 }
909 },
910 (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
911 );
912 const recordingServer = McpServer.McpServer.of({
913 ...server,
914 addTool: (options) =>
915 server.addTool({
916 ...options,
917 handle:
918 /* Request instrumentation already owns the span; keep this helper in that context. */
919 Effect.fnUntraced(function* (payload) {
920 const startedAt = yield* Clock.currentTimeMillis;
921 return yield* options.handle(payload).pipe(
922 Effect.onExit((exit) => {
923 const result = exit._tag === "Success" ? exit.value : undefined;
924 // A call that asks for input is retried with it, and that call is the one counted.
925 if (result instanceof McpSchema.InputRequired) return Effect.void;
926 // Handoff tools look up threads to record; the response must not wait on them.
927 return Clock.currentTimeMillis.pipe(
928 Effect.flatMap((endedAt) =>
929 record(options.tool.name, payload, result, endedAt - startedAt),
930 ),
931 Effect.forkDetach,
932 Effect.asVoid,
933 );
934 }),
935 );
936 }),
937 }),
938 });
939 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
940 });
941
942/**
943 * `McpServer.toolkit` asks for every service its tools declare when it
944 * registers them, but the auth middleware provides `McpInvocationContext` to
945 * each request instead. Registration must not get one: the services it
946 * captures would replace the request's.
947 */
948export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
949 toolkit: Toolkit.Toolkit<Tools>,
950 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
951) => {
952 const registration = Layer.effectDiscard(
953 withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
954 ).pipe(Layer.provide(McpServer.McpServer.layer));
955 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
956 const registered = registration as Layer.Layer<
957 never,
958 never,
959 Exclude<Layer.Services<typeof registration>, McpInvocationContext.McpInvocationContext>
960 >;
961 return registered.pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
962};
963
964const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
965 register: Effect.Effect<A, E, R>,
966 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
967) =>
968 Layer.effectDiscard(withToolAnalytics(register)).pipe(
969 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
970 );
971
972export const layerHtmlToolkit = Layer.mergeAll(
973 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
974 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
975).pipe(Layer.provide(HtmlRender.layer));
976
977const layerPreviewStandardToolkitRegistration = toolkitRegistration(
978 PreviewStandardToolkit,
979 PreviewHandlers.layerStandard,
980);
981
982const layerPreviewSnapshotRegistration = imageToolRegistration(
983 registerPreviewSnapshot(),
984 PreviewHandlers.layerSnapshot,
985);
986
987export const layerPreviewToolkit = Layer.mergeAll(
988 layerPreviewStandardToolkitRegistration,
989 layerPreviewSnapshotRegistration,
990);
991
992export const layerOrchestratorToolkit = toolkitRegistration(
993 OrchestratorToolkit,
994 OrchestratorHandlers.layer,
995).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
996
997export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
998
999const layerWorktreeToolkitRegistration = toolkitRegistration(
1000 WorktreeToolkit,
1001 WorktreeHandlers.layer,
1002).pipe(Layer.provide(WorktreeMcpService.layer));
1003
1004const layerPreviewControlsRegistration = toolkitRegistration(
1005 PreviewControlsToolkit,
1006 PreviewControlsHandlers.layer,
1007);
1008
1009const layerEnvironmentToolkit = toolkitRegistration(
1010 EnvironmentToolkit,
1011 EnvironmentHandlers.layer,
1012).pipe(Layer.provide(ThreadCommandExecutor.layer));
1013
1014const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1015
1016export const layerAttachmentToolkit = toolkitRegistration(
1017 AttachmentToolkit,
1018 AttachmentHandlers.layer,
1019);
1020
1021export const layerPullRequestsToolkit = toolkitRegistration(
1022 PullRequestsToolkit,
1023 PullRequestsHandlers.layer,
1024);
1025
1026const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1027 DeviceStandardToolkit,
1028 DeviceHandlers.layerStandard,
1029);
1030
1031const layerDeviceScreenshotRegistration = imageToolRegistration(
1032 registerDeviceScreenshot(),
1033 DeviceHandlers.layerScreenshot,
1034);
1035
1036export const layerDeviceToolkit = Layer.mergeAll(
1037 layerDeviceStandardToolkitRegistration,
1038 layerDeviceScreenshotRegistration,
1039);
1040
1041export const layerMcpTransport = McpServer.layerHttp({
1042 name: "T3 Code",
1043 version: packageJson.version,
1044 path: "/mcp",
1045 protocols: [McpProtocol.v2025_06_18],
1046 allowSessionTermination: true,
1047}).pipe(Layer.provide(layerMcpAuthMiddleware));
1048
1049export const layer = Layer.mergeAll(
1050 layerPreviewToolkit,
1051 layerOrchestratorToolkit,
1052 layerThreadToolkit,
1053 layerAttachmentToolkit,
1054 layerProjectRegistration,
1055 layerEnvironmentToolkit,
1056 layerPreviewControlsRegistration,
1057 layerWorktreeToolkitRegistration,
1058 layerPullRequestsToolkit,
1059 layerDeviceToolkit,
1060 layerHtmlToolkit,
1061).pipe(Layer.provideMerge(layerMcpTransport));