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