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