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

McpHttpServer.ts

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