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

McpHttpServer.ts

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