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

McpHttpServer.ts

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