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 = Effect.fn("previewSnapshotFailure")(function <E>(
404 cause: Cause.Cause<E>,
405) {
406 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
407 return Effect.failCause(cause).pipe(Effect.orDie);
408 }
409 const failures = cause.reasons.filter(Cause.isFailReason);
410 const firstFailure = failures[0]?.error;
411 const errorTag =
412 typeof firstFailure === "object" &&
413 firstFailure !== null &&
414 "_tag" in firstFailure &&
415 typeof firstFailure._tag === "string"
416 ? firstFailure._tag
417 : "PreviewSnapshotError";
418 // Preview errors contain server-authored recovery guidance, never page output.
419 const message = isPreviewAutomationError(firstFailure) ? firstFailure.message : undefined;
420 const result = new McpSchema.CallToolResult({
421 isError: true,
422 structuredContent: {
423 error: {
424 _tag: errorTag,
425 operation: "snapshot",
426 failureCount: failures.length,
427 ...(message === undefined ? {} : { message }),
428 },
429 },
430 // Some clients show only the text content and others only structuredContent, so both carry it.
431 content: [{ type: "text", text: `Preview snapshot failed: ${message ?? `${errorTag}.`}` }],
432 });
433 return Effect.logWarning("preview snapshot failed", {
434 operation: "snapshot",
435 errorTag,
436 failureCount: failures.length,
437 }).pipe(Effect.as(result));
438});
439
440const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
441 const server = yield* McpServer.McpServer;
442 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
443 const threads = yield* ThreadManagementService.ThreadManagementService;
444 const saveServices = yield* Effect.context<
445 ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto
446 >();
447 const built = yield* decodeAsAdvertised(PreviewSnapshotToolkit);
448 const tool = PreviewSnapshotTool;
449 yield* server.addTool({
450 tool: new McpSchema.Tool({
451 name: tool.name,
452 description: Tool.getDescription(tool),
453 inputSchema: Tool.getJsonSchema(tool),
454 annotations: {
455 ...Context.getOption(tool.annotations, Tool.Title).pipe(
456 Option.map((title) => ({ title })),
457 Option.getOrUndefined,
458 ),
459 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
460 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
461 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
462 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
463 },
464 }),
465 annotations: tool.annotations,
466 handle: (payload) =>
467 Effect.withFiber((fiber) => {
468 const invocation = Context.getUnsafe(
469 fiber.context,
470 McpInvocationContext.McpInvocationContext,
471 );
472 return built.handle("preview_snapshot", payload).pipe(
473 Stream.unwrap,
474 Stream.run(Sink.last()),
475 Effect.flatMap(Effect.fromOption),
476 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
477 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
478 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
479 Effect.flatMap(({ encodedResult }) =>
480 Effect.gen(function* () {
481 const snapshot = encodedResult as SnapshotMetadata & {
482 readonly url: string;
483 readonly screenshot: {
484 readonly mimeType: "image/png";
485 readonly data: string;
486 readonly width: number;
487 readonly height: number;
488 };
489 };
490 const { screenshot, ...page } = snapshot;
491 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
492 const screenshotPath =
493 payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
494 // Providers replay images on later requests, and some reject them; include images only when requested.
495 const includeImage = payload?.includeImage === true;
496 if (screenshotPath !== undefined && !includeImage) {
497 const saved = {
498 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
499 screenshotPath,
500 };
501 return new McpSchema.CallToolResult({
502 isError: false,
503 structuredContent: saved,
504 content: [{ type: "text", text: encodeJsonText(saved) }],
505 });
506 }
507 const metadata = {
508 ...page,
509 screenshot: {
510 mimeType: screenshot.mimeType,
511 width: screenshot.width,
512 height: screenshot.height,
513 },
514 ...(screenshotPath === undefined ? {} : { screenshotPath }),
515 };
516 const bounded = boundSnapshotMetadata(metadata);
517 return new McpSchema.CallToolResult({
518 isError: false,
519 structuredContent:
520 bounded.omitted.length === 0
521 ? bounded.value
522 : { ...bounded.value, omitted: bounded.omitted },
523 content: [
524 {
525 type: "text",
526 text: encodeJsonText({
527 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
528 }),
529 },
530 { type: "text", text: bounded.text },
531 ...(bounded.omitted.length === 0
532 ? []
533 : [
534 {
535 type: "text" as const,
536 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
537 },
538 ]),
539 ...(includeImage
540 ? [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]
541 : []),
542 ],
543 });
544 }),
545 ),
546 Effect.provide(saveServices),
547 Effect.matchCauseEffect({
548 onFailure: previewSnapshotFailure,
549 onSuccess: Effect.succeed,
550 }),
551 );
552 }),
553 });
554});
555
556interface ImageToolResult {
557 readonly screenshot: {
558 readonly mimeType: "image/png";
559 readonly data: string;
560 readonly width: number;
561 readonly height: number;
562 };
563 readonly [key: string]: unknown;
564}
565
566/** Expose only undescribed failures' tags; remote messages may contain renderer or device output. */
567const imageToolFailure =
568 <E>(toolName: string, operation: string, failureText: string | ((error: E) => string)) =>
569 (cause: Cause.Cause<E>) => {
570 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
571 return Effect.failCause(cause).pipe(Effect.orDie);
572 }
573 const failures = cause.reasons.filter(Cause.isFailReason);
574 const firstFailure = failures[0]?.error;
575 const errorTag =
576 typeof firstFailure === "object" &&
577 firstFailure !== null &&
578 "_tag" in firstFailure &&
579 typeof firstFailure._tag === "string"
580 ? firstFailure._tag
581 : `${toolName}Error`;
582 const message =
583 typeof failureText === "string" || failures[0] === undefined
584 ? undefined
585 : failureText(failures[0].error);
586 const result = new McpSchema.CallToolResult({
587 isError: true,
588 structuredContent: {
589 error: {
590 _tag: errorTag,
591 operation,
592 failureCount: failures.length,
593 ...(message === undefined ? {} : { message }),
594 },
595 },
596 // Some clients show only the text content and others only structuredContent, so both carry it.
597 content: [
598 {
599 type: "text",
600 text: typeof failureText === "string" ? failureText : (message ?? `${toolName} failed.`),
601 },
602 ],
603 });
604 return Effect.logWarning(`${toolName} failed`, {
605 operation,
606 errorTag,
607 failureCount: failures.length,
608 }).pipe(Effect.as(result));
609 };
610
611/**
612 * `McpServer.toolkit` serializes every result as JSON text, which is the wrong
613 * shape for a screenshot: the model needs image content.
614 */
615const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* <
616 T extends Tool.Any,
617 E,
618 R,
619>(
620 tool: T,
621 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
622 provide: (
623 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
624 ) => Effect.Effect<
625 { readonly encodedResult: unknown },
626 E,
627 McpInvocationContext.McpInvocationContext
628 >,
629 operation: string,
630 failureText: string | ((error: E) => string),
631) {
632 const server = yield* McpServer.McpServer;
633 yield* server.addTool({
634 tool: new McpSchema.Tool({
635 name: tool.name,
636 description: Tool.getDescription(tool),
637 inputSchema: Tool.getJsonSchema(tool),
638 annotations: {
639 ...Context.getOption(tool.annotations, Tool.Title).pipe(
640 Option.map((title) => ({ title })),
641 Option.getOrUndefined,
642 ),
643 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
644 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
645 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
646 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
647 },
648 }),
649 annotations: tool.annotations,
650 handle: (payload) =>
651 Effect.withFiber((fiber) => {
652 const invocation = Context.getUnsafe(
653 fiber.context,
654 McpInvocationContext.McpInvocationContext,
655 );
656 return provide(handle(payload as Tool.Parameters<T>)).pipe(
657 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
658 Effect.matchCauseEffect({
659 onFailure: imageToolFailure(tool.name, operation, failureText),
660 onSuccess: ({ encodedResult }) => {
661 const { screenshot, ...rest } = encodedResult as ImageToolResult;
662 const includeImage =
663 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
664 false;
665 const metadata = {
666 ...rest,
667 screenshot: {
668 mimeType: screenshot.mimeType,
669 width: screenshot.width,
670 height: screenshot.height,
671 },
672 };
673 return Effect.succeed(
674 new McpSchema.CallToolResult({
675 isError: false,
676 structuredContent: metadata,
677 content: [
678 { type: "text", text: JSON.stringify(metadata) },
679 ...(includeImage
680 ? [
681 {
682 type: "image" as const,
683 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
684 mimeType: screenshot.mimeType,
685 },
686 ]
687 : []),
688 ],
689 }),
690 );
691 },
692 }),
693 );
694 }),
695 });
696});
697
698const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
699 const devices = yield* DeviceService.DeviceService;
700 const threads = yield* ThreadManagementService.ThreadManagementService;
701 const built = yield* decodeAsAdvertised(DeviceScreenshotToolkit);
702 yield* registerImageTool(
703 DeviceScreenshotTool,
704 (payload) =>
705 built
706 .handle("device_screenshot", payload)
707 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
708 (effect) =>
709 effect.pipe(
710 Effect.provideService(DeviceService.DeviceService, devices),
711 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
712 ),
713 "screenshot",
714 "Device screenshot failed.",
715 );
716});
717
718const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
719
720const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
721 const htmlRender = yield* HtmlRender.HtmlRender;
722 const threads = yield* ThreadManagementService.ThreadManagementService;
723 const built = yield* decodeAsAdvertised(HtmlPreviewToolkit);
724 yield* registerImageTool(
725 HtmlPreviewTool,
726 (payload) =>
727 built
728 .handle("html_preview", payload)
729 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
730 (effect) =>
731 effect.pipe(
732 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
733 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
734 ),
735 "preview",
736
737 (error) =>
738 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
739 ? error.message
740 : "HTML preview failed.",
741 );
742});
743
744/**
745 * Tools that hand work to another thread's agent: they create it, message it,
746 * steer it, or move context into it. Their events name the receiving agent too.
747 */
748const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
749 "delegate_task",
750 "create_threads",
751 "t3_thread_launch",
752 "t3_thread_send",
753 "t3_thread_send_attachments",
754 "t3_thread_fork",
755 "t3_thread_merge_back",
756 "t3_queue_edit",
757 "t3_queue_promote_to_steer",
758 "t3_pending_request_respond",
759 "schedule_task",
760 "run_scheduled_task_now",
761]);
762
763/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */
764const INPUT_TARGET_TOOLS: ReadonlySet<string> = new Set([
765 "t3_queue_edit",
766 "t3_queue_promote_to_steer",
767 "t3_pending_request_respond",
768]);
769
770const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
771
772/** Thread ids a handoff tool result names: the thread that received the work. */
773const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
774 if (typeof content !== "object" || content === null) return [];
775 const record = content as Readonly<Record<string, unknown>>;
776 if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
777 const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
778 return key === undefined ? [] : [record[key] as string];
779};
780
781/**
782 * Thread ids that received a handoff. The input's `threadId` is used only after
783 * the call succeeded, so it is one the handler already resolved and authorized.
784 */
785const handoffTargetIds = (
786 tool: string,
787 args: unknown,
788 result: McpSchema.CallToolResult | undefined,
789): ReadonlyArray<string> => {
790 if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent);
791 if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
792 const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
793 return typeof threadId === "string" ? [threadId] : [];
794};
795
796/** Tool analytics must never include IDs, prompts or free text. */
797const withToolAnalytics =
798 /* Request instrumentation already owns the span; keep this helper in that context. */
799 Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
800 const server = yield* McpServer.McpServer;
801 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
802 if (Option.isNone(analytics)) return yield* registration;
803 const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
804 const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
805 const shellOf = (threadId: string) =>
806 Option.isNone(threads)
807 ? Effect.succeed(null)
808 : threads.value
809 .getThreadShell(ThreadId.make(threadId))
810 .pipe(Effect.orElseSucceed(() => null));
811 // Delegation depth: parents walked from the caller, capped.
812 const depthOf =
813 /* Request instrumentation already owns the span; keep this helper in that context. */
814 Effect.fnUntraced(function* (thread: AgentThread) {
815 let depth = 0;
816 let parentId =
817 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
818 while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
819 depth += 1;
820 const parent = yield* shellOf(parentId);
821 parentId =
822 parent?.lineage.relationshipToParent === "subagent"
823 ? parent.lineage.parentThreadId
824 : null;
825 }
826 return depth;
827 });
828 // Whether the caller's active run was started by a scheduled task.
829 const scheduledRunOf = (threadId: string, runId: RunId | null) =>
830 Option.isNone(threads) || runId === null
831 ? Effect.succeed(false)
832 : threads.value
833 .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
834 runIds: [runId],
835 messageRoles: ["user"],
836 })
837 .pipe(
838 Effect.map((records) => {
839 const run = records.runs.find((candidate) => candidate.id === runId);
840 return records.messages.some(
841 (message) =>
842 message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
843 );
844 }),
845 Effect.orElseSucceed(() => false),
846 );
847 const record =
848 /* Request instrumentation already owns the span; keep this helper in that context. */
849 Effect.fnUntraced(
850 function* (
851 tool: string,
852 args: unknown,
853 result: McpSchema.CallToolResult | undefined,
854 durationMs: number,
855 ) {
856 const handoff = HANDOFF_TOOLS.has(tool);
857 const outcome = toolOutcome(result);
858 // Agents call status, read, and preview tools in tight loops, so an
859 // event per successful call floods analytics. Only failures count there.
860 if (!handoff && outcome.outcome === "ok") return;
861 // Client credentials (no calling thread) report an unknown caller.
862 const invocation = Option.getOrUndefined(
863 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
864 )?.thread;
865 const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
866 // Only handoff tools pay for thread lookups; the rest report the
867 // caller's provider from the credential.
868 const caller =
869 handoff && invocation !== undefined
870 ? ((yield* shellOf(invocation.threadId)) ?? undefined)
871 : undefined;
872 const targetIds = handoff
873 ? [...new Set(handoffTargetIds(tool, args, result))].filter(
874 (threadId) => threadId !== invocation?.threadId,
875 )
876 : [];
877 const targets = yield* Effect.forEach(targetIds, shellOf);
878 for (const properties of agentToolProperties({
879 tool,
880 providers,
881 caller,
882 ...(invocation === undefined
883 ? {}
884 : { callerProviderInstanceId: invocation.providerInstanceId }),
885 ...(caller === undefined || invocation === undefined
886 ? {}
887 : {
888 callerDepth: yield* depthOf(caller),
889 callerScheduledRun: yield* scheduledRunOf(
890 invocation.threadId,
891 caller.activeRunId,
892 ),
893 }),
894 targets: targets.filter((thread) => thread !== null),
895 outcome,
896 ...(handoff
897 ? { settings: handoffSettings(tool, args, result?.structuredContent) }
898 : {}),
899 durationMs,
900 })) {
901 yield* analytics.value.record("mcp.tool.invoked", properties);
902 }
903 },
904 (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
905 );
906 const recordingServer = McpServer.McpServer.of({
907 ...server,
908 addTool: Effect.fn("McpServer.addTool")(function (options) {
909 return server.addTool({
910 ...options,
911 handle:
912 /* Request instrumentation already owns the span; keep this helper in that context. */
913 Effect.fnUntraced(function* (payload) {
914 const startedAt = yield* Clock.currentTimeMillis;
915 return yield* options.handle(payload).pipe(
916 Effect.onExit((exit) => {
917 const result = exit._tag === "Success" ? exit.value : undefined;
918 // A call that asks for input is retried with it, and that call is the one counted.
919 if (result instanceof McpSchema.InputRequired) return Effect.void;
920 // Handoff tools look up threads to record; the response must not wait on them.
921 return Clock.currentTimeMillis.pipe(
922 Effect.flatMap((endedAt) =>
923 record(options.tool.name, payload, result, endedAt - startedAt),
924 ),
925 Effect.forkDetach,
926 Effect.asVoid,
927 );
928 }),
929 );
930 }),
931 });
932 }),
933 });
934 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
935 });
936
937/**
938 * `McpServer.toolkit` asks for every service its tools declare when it
939 * registers them, but the auth middleware provides `McpInvocationContext` to
940 * each request instead. Registration must not get one: the services it
941 * captures would replace the request's.
942 */
943export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
944 toolkit: Toolkit.Toolkit<Tools>,
945 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
946) => {
947 const registration = Layer.effectDiscard(
948 withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
949 ).pipe(Layer.provide(McpServer.McpServer.layer));
950 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
951 const registered = registration as Layer.Layer<
952 never,
953 never,
954 Exclude<Layer.Services<typeof registration>, McpInvocationContext.McpInvocationContext>
955 >;
956 return registered.pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
957};
958
959const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
960 register: Effect.Effect<A, E, R>,
961 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
962) =>
963 Layer.effectDiscard(withToolAnalytics(register)).pipe(
964 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
965 );
966
967export const layerHtmlToolkit = Layer.mergeAll(
968 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
969 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
970).pipe(Layer.provide(HtmlRender.layer));
971
972const layerPreviewStandardToolkitRegistration = toolkitRegistration(
973 PreviewStandardToolkit,
974 PreviewHandlers.layerStandard,
975);
976
977const layerPreviewSnapshotRegistration = imageToolRegistration(
978 registerPreviewSnapshot(),
979 PreviewHandlers.layerSnapshot,
980);
981
982export const layerPreviewToolkit = Layer.mergeAll(
983 layerPreviewStandardToolkitRegistration,
984 layerPreviewSnapshotRegistration,
985);
986
987export const layerOrchestratorToolkit = toolkitRegistration(
988 OrchestratorToolkit,
989 OrchestratorHandlers.layer,
990).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
991
992export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
993
994const layerWorktreeToolkitRegistration = toolkitRegistration(
995 WorktreeToolkit,
996 WorktreeHandlers.layer,
997).pipe(Layer.provide(WorktreeMcpService.layer));
998
999const layerPreviewControlsRegistration = toolkitRegistration(
1000 PreviewControlsToolkit,
1001 PreviewControlsHandlers.layer,
1002);
1003
1004const layerEnvironmentToolkit = toolkitRegistration(
1005 EnvironmentToolkit,
1006 EnvironmentHandlers.layer,
1007).pipe(Layer.provide(ThreadCommandExecutor.layer));
1008
1009const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1010
1011export const layerAttachmentToolkit = toolkitRegistration(
1012 AttachmentToolkit,
1013 AttachmentHandlers.layer,
1014);
1015
1016export const layerPullRequestsToolkit = toolkitRegistration(
1017 PullRequestsToolkit,
1018 PullRequestsHandlers.layer,
1019);
1020
1021const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1022 DeviceStandardToolkit,
1023 DeviceHandlers.layerStandard,
1024);
1025
1026const layerDeviceScreenshotRegistration = imageToolRegistration(
1027 registerDeviceScreenshot(),
1028 DeviceHandlers.layerScreenshot,
1029);
1030
1031export const layerDeviceToolkit = Layer.mergeAll(
1032 layerDeviceStandardToolkitRegistration,
1033 layerDeviceScreenshotRegistration,
1034);
1035
1036export const layerMcpTransport = McpServer.layerHttp({
1037 name: "T3 Code",
1038 version: packageJson.version,
1039 path: "/mcp",
1040 protocols: [McpProtocol.v2025_06_18],
1041 allowSessionTermination: true,
1042}).pipe(Layer.provide(layerMcpAuthMiddleware));
1043
1044export const layer = Layer.mergeAll(
1045 layerPreviewToolkit,
1046 layerOrchestratorToolkit,
1047 layerThreadToolkit,
1048 layerAttachmentToolkit,
1049 layerProjectRegistration,
1050 layerEnvironmentToolkit,
1051 layerPreviewControlsRegistration,
1052 layerWorktreeToolkitRegistration,
1053 layerPullRequestsToolkit,
1054 layerDeviceToolkit,
1055 layerHtmlToolkit,
1056).pipe(Layer.provideMerge(layerMcpTransport));