Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpHttpServer.ts

1,162 lines44.4 KB

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 }
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;
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 isDeviceToolError(error) || isOrchestratorMcpFailure(error)
771 ? error.message
772 : "Device screenshot failed.",
773 );
774});
775​
776const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
777const isDeviceToolError = Schema.is(DeviceToolError);
778​
779const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
780 const htmlRender = yield* HtmlRender.HtmlRender;
781 const threads = yield* ThreadManagementService.ThreadManagementService;
782 const built = yield* decodeAsAdvertised(HtmlPreviewToolkit);
783 yield* registerImageTool(
784 HtmlPreviewTool,
785 (payload) =>
786 built
787 .handle("html_preview", payload)
788 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
789 (effect) =>
790 effect.pipe(
791 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
792 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
793 ),
794 "preview",
795​
796 (error) =>
797 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
798 ? error.message
799 : "HTML preview failed.",
800 );
801});
802​
803/**
804 * Tools that hand work to another thread's agent: they create it, message it,
805 * steer it, or move context into it. Their events name the receiving agent too.
806 */
807const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
808 "delegate_task",
809 "create_threads",
810 "t3_thread_launch",
811 "t3_thread_send",
812 "t3_thread_send_attachments",
813 "schedule_task",
814 "run_scheduled_task_now",
815]);
816​
817/** Tool actions that hand work over with only a `{ sequence }` result; the input names the thread. */
818const INPUT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
819 t3_queue: new Set(["edit", "promote_to_steer"]),
820 t3_pending_request: new Set(["respond"]),
821};
822​
823/** Tool actions that hand work over and name the receiving thread in their result. */
824const RESULT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
825 t3_thread_transfer: new Set(["fork", "merge_back"]),
826};
827​
828const hasAction = (
829 actions: Readonly<Record<string, ReadonlySet<string>>>,
830 tool: string,
831 args: unknown,
832) =>
833 actions[tool]?.has(String((args as { readonly action?: unknown } | null | undefined)?.action)) ===
834 true;
835​
836const isInputTargetHandoff = (tool: string, args: unknown) =>
837 hasAction(INPUT_TARGET_ACTIONS, tool, args);
838​
839const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
840​
841/** Thread ids a handoff tool result names: the thread that received the work. */
842const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
843 if (typeof content !== "object" || content === null) return [];
844 const record = content as Readonly<Record<string, unknown>>;
845 if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
846 const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
847 return key === undefined ? [] : [record[key] as string];
848};
849​
850/**
851 * Thread ids that received a handoff. The input's `threadId` is used only after
852 * the call succeeded, so it is one the handler already resolved and authorized.
853 */
854const handoffTargetIds = (
855 tool: string,
856 args: unknown,
857 result: McpSchema.CallToolResult | undefined,
858): ReadonlyArray<string> => {
859 if (!isInputTargetHandoff(tool, args)) return resultThreadIds(result?.structuredContent);
860 if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
861 const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
862 return typeof threadId === "string" ? [threadId] : [];
863};
864​
865/** Tool analytics must never include IDs, prompts or free text. */
866const withToolAnalytics =
867 /* Request instrumentation already owns the span; keep this helper in that context. */
868 Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
869 const server = yield* McpServer.McpServer;
870 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
871 if (Option.isNone(analytics)) return yield* registration;
872 const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
873 const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
874 const shellOf = (threadId: string) =>
875 Option.isNone(threads)
876 ? Effect.succeed(null)
877 : threads.value
878 .getThreadShell(ThreadId.make(threadId))
879 .pipe(Effect.orElseSucceed(() => null));
880 // Delegation depth: parents walked from the caller, capped.
881 const depthOf =
882 /* Request instrumentation already owns the span; keep this helper in that context. */
883 Effect.fnUntraced(function* (thread: AgentThread) {
884 let depth = 0;
885 let parentId =
886 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
887 while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
888 depth += 1;
889 const parent = yield* shellOf(parentId);
890 parentId =
891 parent?.lineage.relationshipToParent === "subagent"
892 ? parent.lineage.parentThreadId
893 : null;
894 }
895 return depth;
896 });
897 // Whether the caller's active run was started by a scheduled task.
898 const scheduledRunOf = (threadId: string, runId: RunId | null) =>
899 Option.isNone(threads) || runId === null
900 ? Effect.succeed(false)
901 : threads.value
902 .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
903 runIds: [runId],
904 messageRoles: ["user"],
905 })
906 .pipe(
907 Effect.map((records) => {
908 const run = records.runs.find((candidate) => candidate.id === runId);
909 return records.messages.some(
910 (message) =>
911 message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
912 );
913 }),
914 Effect.orElseSucceed(() => false),
915 );
916 const record =
917 /* Request instrumentation already owns the span; keep this helper in that context. */
918 Effect.fnUntraced(
919 function* (
920 tool: string,
921 args: unknown,
922 result: McpSchema.CallToolResult | undefined,
923 durationMs: number,
924 ) {
925 const handoff =
926 HANDOFF_TOOLS.has(tool) ||
927 isInputTargetHandoff(tool, args) ||
928 hasAction(RESULT_TARGET_ACTIONS, tool, args);
929 const outcome = toolOutcome(result);
930 // Agents call status, read, and preview tools in tight loops, so an
931 // event per successful call floods analytics. Only failures count there.
932 if (!handoff && outcome.outcome === "ok") return;
933 // Client credentials (no calling thread) report an unknown caller.
934 const invocation = Option.getOrUndefined(
935 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
936 )?.thread;
937 const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
938 // Only handoff tools pay for thread lookups; the rest report the
939 // caller's provider from the credential.
940 const caller =
941 handoff && invocation !== undefined
942 ? ((yield* shellOf(invocation.threadId)) ?? undefined)
943 : undefined;
944 const targetIds = handoff
945 ? [...new Set(handoffTargetIds(tool, args, result))].filter(
946 (threadId) => threadId !== invocation?.threadId,
947 )
948 : [];
949 const targets = yield* Effect.forEach(targetIds, shellOf);
950 for (const properties of agentToolProperties({
951 tool,
952 providers,
953 caller,
954 ...(invocation === undefined
955 ? {}
956 : { callerProviderInstanceId: invocation.providerInstanceId }),
957 ...(caller === undefined || invocation === undefined
958 ? {}
959 : {
960 callerDepth: yield* depthOf(caller),
961 callerScheduledRun: yield* scheduledRunOf(
962 invocation.threadId,
963 caller.activeRunId,
964 ),
965 }),
966 targets: targets.filter((thread) => thread !== null),
967 outcome,
968 ...(handoff
969 ? { settings: handoffSettings(tool, args, result?.structuredContent) }
970 : {}),
971 durationMs,
972 })) {
973 yield* analytics.value.record("mcp.tool.invoked", properties);
974 }
975 },
976 (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
977 );
978 const recordingServer = McpServer.McpServer.of({
979 ...server,
980 addTool: Effect.fn("McpServer.addTool")(function (options) {
981 return server.addTool({
982 ...options,
983 handle:
984 /* Request instrumentation already owns the span; keep this helper in that context. */
985 Effect.fnUntraced(function* (payload) {
986 const startedAt = yield* Clock.currentTimeMillis;
987 return yield* options.handle(payload).pipe(
988 Effect.onExit((exit) => {
989 const result = exit._tag === "Success" ? exit.value : undefined;
990 // A call that asks for input is retried with it, and that call is the one counted.
991 if (result instanceof McpSchema.InputRequired) return Effect.void;
992 // Handoff tools look up threads to record; the response must not wait on them.
993 return Clock.currentTimeMillis.pipe(
994 Effect.flatMap((endedAt) =>
995 record(options.tool.name, payload, result, endedAt - startedAt),
996 ),
997 Effect.forkDetach,
998 Effect.asVoid,
999 );
1000 }),
1001 );
1002 }),
1003 });
1004 }),
1005 });
1006 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
1007 });
1008​
1009/** `McpServer.registerToolkit` advertises the full codec schema; agents get the compact one. */
1010const withAdvertisedSchemas = Effect.fn("McpHttpServer.withAdvertisedSchemas")(function* <
1011 Tools extends Record<string, Tool.Any>,
1012 A,
1013 E,
1014 R,
1015>(toolkit: Toolkit.Toolkit<Tools>, registration: Effect.Effect<A, E, R>) {
1016 const server = yield* McpServer.McpServer;
1017 const tools: Record<string, Tool.Any> = toolkit.tools;
1018 const advertisingServer = McpServer.McpServer.of({
1019 ...server,
1020 addTool: Effect.fn("McpServer.addTool")(function (options) {
1021 const tool = tools[options.tool.name];
1022 return server.addTool(
1023 tool === undefined
1024 ? options
1025 : {
1026 ...options,
1027 tool: new McpSchema.Tool({
1028 ...options.tool,
1029 inputSchema: advertisedJsonSchema(tool),
1030 }),
1031 },
1032 );
1033 }),
1034 });
1035 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, advertisingServer));
1036});
1037​
1038/**
1039 * `McpServer.toolkit` asks for every service its tools declare when it
1040 * registers them, but the auth middleware provides `McpInvocationContext` to
1041 * each request instead. Registration must not get one: the services it
1042 * captures would replace the request's.
1043 */
1044export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
1045 toolkit: Toolkit.Toolkit<Tools>,
1046 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
1047) => {
1048 const registration = Layer.effectDiscard(
1049 withToolAnalytics(
1050 withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
1051 ),
1052 ).pipe(Layer.provide(McpServer.McpServer.layer));
1053 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
1054 const registered = registration as Layer.Layer<
1055 never,
1056 never,
1057 Exclude<Layer.Services<typeof registration>, McpInvocationContext.McpInvocationContext>
1058 >;
1059 return registered.pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
1061​
1062const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
1063 register: Effect.Effect<A, E, R>,
1064 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
1065) =>
1066 Layer.effectDiscard(withToolAnalytics(register)).pipe(
1067 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
1068 );
1069​
1070export const layerHtmlToolkit = Layer.mergeAll(
1071 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
1072 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
1073).pipe(Layer.provide(HtmlRender.layer));
1074​
1075const layerPreviewStandardToolkitRegistration = toolkitRegistration(
1076 PreviewStandardToolkit,
1077 PreviewHandlers.layerStandard,
1079​
1080const layerPreviewSnapshotRegistration = imageToolRegistration(
1081 registerPreviewSnapshot(),
1082 PreviewHandlers.layerSnapshot,
1084​
1085export const layerPreviewToolkit = Layer.mergeAll(
1086 layerPreviewStandardToolkitRegistration,
1087 layerPreviewSnapshotRegistration,
1089​
1090export const layerOrchestratorToolkit = toolkitRegistration(
1091 OrchestratorToolkit,
1092 OrchestratorHandlers.layer,
1093).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
1094​
1095export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
1096​
1097const layerWorktreeToolkitRegistration = toolkitRegistration(
1098 WorktreeToolkit,
1099 WorktreeHandlers.layer,
1100).pipe(Layer.provide(WorktreeMcpService.layer));
1101​
1102const layerPreviewControlsRegistration = toolkitRegistration(
1103 PreviewControlsToolkit,
1104 PreviewControlsHandlers.layer,
1106​
1107const layerEnvironmentToolkit = toolkitRegistration(
1108 EnvironmentToolkit,
1109 EnvironmentHandlers.layer,
1110).pipe(Layer.provide(ThreadCommandExecutor.layer));
1111​
1112export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1113​
1114export const layerAttachmentToolkit = toolkitRegistration(
1115 AttachmentToolkit,
1116 AttachmentHandlers.layer,
1118​
1119export const layerPullRequestsToolkit = toolkitRegistration(
1120 PullRequestsToolkit,
1121 PullRequestsHandlers.layer,
1123​
1124const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1125 DeviceStandardToolkit,
1126 DeviceHandlers.layerStandard,
1128​
1129const layerDeviceScreenshotRegistration = imageToolRegistration(
1130 registerDeviceScreenshot(),
1131 DeviceHandlers.layerScreenshot,
1133​
1134export const layerDeviceToolkit = Layer.mergeAll(
1135 layerDeviceStandardToolkitRegistration,
1136 layerDeviceScreenshotRegistration,
1138​
1139export const layerMcpTransport = McpServer.layerHttp({
1140 name: "T3 Code",
1141 version: packageJson.version,
1142 path: "/mcp",
1143 protocols: [McpProtocol.v2025_06_18],
1144 allowSessionTermination: true,
1145}).pipe(Layer.provide(layerMcpAuthMiddleware));
1146​
1147/** Every tool the T3 MCP server advertises. AgentContextBudget.test.ts measures this set. */
1148export const layerTools = Layer.mergeAll(
1149 layerPreviewToolkit,
1150 layerOrchestratorToolkit,
1151 layerThreadToolkit,
1152 layerAttachmentToolkit,
1153 layerProjectRegistration,
1154 layerEnvironmentToolkit,
1155 layerPreviewControlsRegistration,
1156 layerWorktreeToolkitRegistration,
1157 layerPullRequestsToolkit,
1158 layerDeviceToolkit,
1159 layerHtmlToolkit,
1161​
1162export const layer = layerTools.pipe(Layer.provideMerge(layerMcpTransport));