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