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