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

McpHttpServer.ts

847 lines31.9 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, type Toolkit } from "effect/ai";
15import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16import { OrchestratorMcpFailure, PreviewAutomationError } from "@t3tools/contracts";
17​
18import packageJson from "../../package.json" with { type: "json" };
19import * as ServerConfig from "../config.ts";
20import * as DeviceService from "../device/DeviceService.ts";
21import * as HtmlRender from "../htmlRender/HtmlRender.ts";
22import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
23import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
24import * as McpInvocationContext from "./McpInvocationContext.ts";
25import * as McpToolAccess from "./McpToolAccess.ts";
26import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
27import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
28import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
29import { EnvironmentToolkit } from "./toolkits/environment/tools.ts";
30import * as EnvironmentHandlers from "./toolkits/environment/handlers.ts";
31import { ProjectToolkit } from "./toolkits/project/tools.ts";
32import * as ProjectHandlers from "./toolkits/project/handlers.ts";
33import { AttachmentToolkit } from "./toolkits/attachment/tools.ts";
34import * as AttachmentHandlers from "./toolkits/attachment/handlers.ts";
35import { ThreadToolkit } from "./toolkits/thread/tools.ts";
36import * as ThreadHandlers from "./toolkits/thread/handlers.ts";
37import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
38import * as McpSessionRegistry from "./McpSessionRegistry.ts";
39import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
40import * as OrchestratorHandlers from "./toolkits/orchestrator/handlers.ts";
41import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
42import * as PreviewHandlers from "./toolkits/preview/handlers.ts";
43import {
44 PreviewSnapshotTool,
45 PreviewSnapshotToolkit,
46 PreviewStandardToolkit,
47} from "./toolkits/preview/tools.ts";
48import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
49import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
50import * as WorktreeMcpService from "./WorktreeMcpService.ts";
51import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
52import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
53import * as DeviceHandlers from "./toolkits/device/handlers.ts";
54import {
55 DeviceScreenshotTool,
56 DeviceScreenshotToolkit,
57 DeviceStandardToolkit,
58} from "./toolkits/device/tools.ts";
59import * as HtmlHandlers from "./toolkits/html/handlers.ts";
60import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts";
61​
62const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) =>
63 HttpServerRequest.toURL(request).pipe(
64 Option.map((url) => `${url.origin}/.well-known/oauth-protected-resource/mcp`),
65 );
66​
67/**
68 * Agents T3 Code launched carry a registry token and must never be sent into an
69 * OAuth flow when it dies: they cannot open a browser, and a sign-in would mint
70 * a credential that outlives their session.
71 */
72const unauthorized = (input: {
73 readonly request: HttpServerRequest.HttpServerRequest;
74 readonly presentedToken: boolean;
75 readonly offerOAuth: boolean;
76}) => {
77 const metadataUrl = input.offerOAuth
78 ? Option.getOrUndefined(mcpResourceMetadataUrl(input.request))
79 : undefined;
80 const challenge = [
81 "Bearer",
82 [
83 ...(metadataUrl === undefined ? [] : [`resource_metadata="${metadataUrl}"`]),
84 ...(input.presentedToken ? ['error="invalid_token"'] : []),
85 ].join(", "),
86 ]
87 .filter((part) => part.length > 0)
88 .join(" ");
89 return HttpServerResponse.jsonUnsafe(
90 {
91 error: "invalid_mcp_credential",
92 message: "A valid T3 Code MCP credential is required.",
93 },
94 {
95 status: 401,
96 headers: {
97 "cache-control": "no-store",
98 "www-authenticate": challenge,
99 },
100 },
101 );
102};
103​
104export class McpClientAuthenticator extends Context.Service<
105 McpClientAuthenticator,
106 {
107 readonly authenticate: (
108 request: HttpServerRequest.HttpServerRequest,
109 ) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
110 }
111>()("t3/mcp/McpHttpServer/McpClientAuthenticator") {}
112​
113type AuthenticatedHttpEffect = Effect.Effect<
114 HttpServerResponse.HttpServerResponse,
115 Types.unhandled,
116 McpInvocationContext.McpInvocationContext
117>;
118​
119type McpAuthMiddleware = (
120 httpEffect: AuthenticatedHttpEffect,
121) => Effect.Effect<
122 HttpServerResponse.HttpServerResponse,
123 Types.unhandled,
124 HttpServerRequest.HttpServerRequest
125>;
126​
127export const normalizeMcpHttpResponse = (
128 response: HttpServerResponse.HttpServerResponse,
129): HttpServerResponse.HttpServerResponse => {
130 const bodyIsEmpty =
131 response.body._tag === "Empty" ||
132 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
133 (response.body._tag === "Raw" && response.body.contentLength === 0);
134 return response.status === 200 && bodyIsEmpty
135 ? HttpServerResponse.setStatus(response, 202)
136 : response;
137};
138​
139// Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
140const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
141​
142const makeMcpAuthMiddleware = Effect.gen(function* () {
143 const registry = yield* McpSessionRegistry.McpSessionRegistry;
144 const clients = yield* Effect.serviceOption(McpClientAuthenticator);
145 return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
146 const request = yield* HttpServerRequest.HttpServerRequest;
147 const authorization = request.headers.authorization;
148 const token =
149 authorization?.startsWith("Bearer ") === true
150 ? authorization.slice("Bearer ".length).trim()
151 : "";
152 const invocation =
153 (yield* registry.resolve(token)) ??
154 (Option.isSome(clients) && token.length > 0
155 ? yield* clients.value.authenticate(request)
156 : undefined);
157 if (!invocation) {
158 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
159 reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
160 });
161 return unauthorized({
162 request,
163 presentedToken: token.length > 0,
164 offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
165 });
166 }
167 return yield* httpEffect.pipe(
168 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
169 Effect.map(normalizeMcpHttpResponse),
170 );
171 }) satisfies McpAuthMiddleware;
172}).pipe(Effect.withSpan("McpHttpServer.makeAuthMiddleware"));
173​
174const layerMcpAuthMiddleware = HttpRouter.middleware<{
175 provides: McpInvocationContext.McpInvocationContext;
176}>()(makeMcpAuthMiddleware).layer;
177​
178/**
179 * Claude Code moves an MCP result above its output limit to a file and hands
180 * the agent a notice instead, so a snapshot that carries the full accessibility
181 * tree and page text loses its locators too. Claude Code also shows the model
182 * `structuredContent` in place of the text blocks when a result has both, so
183 * both carry the same bounded snapshot.
184 */
185export const MAX_SNAPSHOT_TEXT_BYTES = 20_000;
186const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;
187const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;
188const MAX_SNAPSHOT_LOG_ENTRIES = 40;
189const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500;
190const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048;
191​
192const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
193const utf8Length = (text: string) => Buffer.byteLength(text, "utf8");
194const cutText = (text: string, max: number) =>
195 text.length > max ? `${text.slice(0, max)}…` : text;
196​
197const cutEntryStrings = <A>(entry: A): A =>
198 typeof entry === "object" && entry !== null
199 ? (Object.fromEntries(
200 Object.entries(entry).map(([key, value]) => [
201 key,
202 typeof value === "string" ? cutText(value, MAX_SNAPSHOT_LOG_TEXT_CHARS) : value,
203 ]),
204 ) as A)
205 : entry;
206​
207const hasLongString = (entry: unknown, max: number) =>
208 typeof entry === "object" &&
209 entry !== null &&
210 Object.values(entry).some((value) => typeof value === "string" && value.length > max);
211​
212type SnapshotMetadata = {
213 readonly url: string;
214 readonly title: string;
215 readonly visibleText: string;
216 readonly interactiveElements: ReadonlyArray<{
217 readonly name: string;
218 readonly [key: string]: unknown;
219 }>;
220 readonly consoleEntries: ReadonlyArray<unknown>;
221 readonly networkEntries: ReadonlyArray<unknown>;
222 readonly actionTimeline: ReadonlyArray<unknown>;
223 readonly [key: string]: unknown;
224};
225​
226const boundSnapshotMetadata = (metadata: SnapshotMetadata) => {
227 const omitted: Array<string> = [];
228 const { accessibilityTree, ...withoutTree } = metadata;
229 const ariaTree = typeof accessibilityTree === "string" ? accessibilityTree : undefined;
230 if (accessibilityTree !== undefined && ariaTree === undefined) {
231 omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)");
232 }
233 const tail = <A>(entries: ReadonlyArray<A>, label: string) => {
234 if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) {
235 omitted.push(`${entries.length - MAX_SNAPSHOT_LOG_ENTRIES} older ${label}`);
236 }
237 const kept = entries.slice(-MAX_SNAPSHOT_LOG_ENTRIES);
238 if (kept.some((entry) => hasLongString(entry, MAX_SNAPSHOT_LOG_TEXT_CHARS))) {
239 omitted.push(`${label} text after ${MAX_SNAPSHOT_LOG_TEXT_CHARS} characters`);
240 }
241 return kept.map(cutEntryStrings);
242 };
243 if (
244 metadata.url.length > MAX_SNAPSHOT_IDENTIFIER_CHARS ||
245 metadata.title.length > MAX_SNAPSHOT_IDENTIFIER_CHARS
246 ) {
247 omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`);
248 }
249 if (
250 metadata.interactiveElements.some(
251 (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS,
252 )
253 ) {
254 omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`);
255 }
256 const bounded = {
257 ...withoutTree,
258 url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
259 title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS),
260 interactiveElements: metadata.interactiveElements.map((element) => ({
261 ...element,
262 name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS),
263 })),
264 consoleEntries: tail(metadata.consoleEntries, "console entries"),
265 networkEntries: tail(metadata.networkEntries, "network entries"),
266 actionTimeline: tail(metadata.actionTimeline, "action timeline entries"),
267 };
268​
269 // Per-field caps do not sum below the ceiling: three log arrays of 40 capped
270 // entries alone can pass 60 KB, and the caps count characters, not bytes.
271 const shedOrder = [
272 "actionTimeline",
273 "networkEntries",
274 "consoleEntries",
275 "interactiveElements",
276 ] as const;
277 const lists: Record<(typeof shedOrder)[number], ReadonlyArray<unknown>> = {
278 interactiveElements: bounded.interactiveElements,
279 consoleEntries: bounded.consoleEntries,
280 networkEntries: bounded.networkEntries,
281 actionTimeline: bounded.actionTimeline,
282 };
283 const dropped: Record<(typeof shedOrder)[number], number> = {
284 interactiveElements: 0,
285 consoleEntries: 0,
286 networkEntries: 0,
287 actionTimeline: 0,
288 };
289 let visibleTextChars = Math.min(metadata.visibleText.length, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS);
290 let ariaTreeChars = Math.min(ariaTree?.length ?? 0, 20_000);
291 const value = () => ({
292 ...bounded,
293 ...(ariaTree === undefined ? {} : { accessibilityTree: cutText(ariaTree, ariaTreeChars) }),
294 visibleText: cutText(metadata.visibleText, visibleTextChars),
295 ...lists,
296 });
297 let text = encodeJsonText(value());
298 while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) {
299 // Elements carry the locators, so they go last; logs shed newest-last.
300 const key =
301 shedOrder.find(
302 (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0,
303 ) ??
304 (visibleTextChars > 0
305 ? "visibleText"
306 : lists.interactiveElements.length > 0
307 ? "interactiveElements"
308 : ariaTreeChars > 0
309 ? "accessibilityTree"
310 : undefined);
311 if (key === undefined) break;
312 if (key === "visibleText") {
313 visibleTextChars = Math.floor(visibleTextChars / 2);
314 } else if (key === "accessibilityTree") {
315 ariaTreeChars = Math.floor(ariaTreeChars / 2);
316 } else {
317 const keep = Math.floor(lists[key].length / 2);
318 dropped[key] += lists[key].length - keep;
319 // slice(-0) keeps everything, so spell out the empty case.
320 lists[key] =
321 keep === 0
322 ? []
323 : key === "interactiveElements"
324 ? lists[key].slice(0, keep)
325 : lists[key].slice(-keep);
326 }
327 text = encodeJsonText(value());
328 }
329 if (visibleTextChars < metadata.visibleText.length) {
330 omitted.push(
331 `visibleText after ${visibleTextChars} characters (use preview_evaluate for more)`,
332 );
333 }
334 if (ariaTree !== undefined && ariaTreeChars < ariaTree.length) {
335 omitted.push(`accessibilityTree after ${ariaTreeChars} characters`);
336 }
337 for (const key of shedOrder) {
338 if (dropped[key] > 0) {
339 omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);
340 }
341 }
342 return { value: value(), text, omitted };
343};
344​
345export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(
346 "PreviewScreenshotSaveError",
347 { screenshotPath: Schema.String, cause: Schema.Defect() },
348) {
349 override get message(): string {
350 return `Could not save preview screenshot to ${this.screenshotPath}.`;
351 }
353​
354const MAX_SCREENSHOT_SITE_SLUG_LENGTH = 40;
355​
356const screenshotSiteSlug = (rawUrl: string): string => {
357 try {
358 const slug = new URL(rawUrl).hostname
359 .toLowerCase()
360 .replace(/[^a-z0-9]+/g, "-")
361 .replace(/^-+|-+$/g, "")
362 .slice(0, MAX_SCREENSHOT_SITE_SLUG_LENGTH)
363 .replace(/-+$/g, "");
364 return slug || "site";
365 } catch {
366 return "site";
367 }
368};
369​
370const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
371 pageUrl: string,
372 data: Uint8Array,
373) {
374 const config = yield* ServerConfig.ServerConfig;
375 const fileSystem = yield* FileSystem.FileSystem;
376 const path = yield* Path.Path;
377 const millis = yield* Clock.currentTimeMillis;
378 const crypto = yield* Crypto.Crypto;
379 const unique = (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).slice(0, 8);
380 const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${unique}.png`;
381 const screenshotPath = path.join(config.browserArtifactsDir, fileName);
382 yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
383 Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
384 Effect.mapError((cause) => new PreviewScreenshotSaveError({ screenshotPath, cause })),
385 );
386 return screenshotPath;
387});
388​
389const isPreviewAutomationError = Schema.is(PreviewAutomationError);
390​
391const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
392 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
393 return Effect.failCause(cause).pipe(Effect.orDie);
394 }
395 const failures = cause.reasons.filter(Cause.isFailReason);
396 const firstFailure = failures[0]?.error;
397 const errorTag =
398 typeof firstFailure === "object" &&
399 firstFailure !== null &&
400 "_tag" in firstFailure &&
401 typeof firstFailure._tag === "string"
402 ? firstFailure._tag
403 : "PreviewSnapshotError";
404 // Preview errors build their message on the server, never from page output,
405 // and it tells the agent what to do next, such as falling back to a shell browser.
406 const message = isPreviewAutomationError(firstFailure) ? firstFailure.message : undefined;
407 const result = new McpSchema.CallToolResult({
408 isError: true,
409 structuredContent: {
410 error: {
411 _tag: errorTag,
412 operation: "snapshot",
413 failureCount: failures.length,
414 ...(message === undefined ? {} : { message }),
415 },
416 },
417 // Some clients show only the text content and others only structuredContent, so both carry it.
418 content: [{ type: "text", text: `Preview snapshot failed: ${message ?? `${errorTag}.`}` }],
419 });
420 return Effect.logWarning("preview snapshot failed", {
421 operation: "snapshot",
422 errorTag,
423 failureCount: failures.length,
424 }).pipe(Effect.as(result));
425};
426​
427const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
428 const server = yield* McpServer.McpServer;
429 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
430 const threads = yield* ThreadManagementService.ThreadManagementService;
431 const saveServices = yield* Effect.context<
432 ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto
433 >();
434 const built = yield* PreviewSnapshotToolkit;
435 const tool = PreviewSnapshotTool;
436 yield* server.addTool({
437 tool: new McpSchema.Tool({
438 name: tool.name,
439 description: Tool.getDescription(tool),
440 inputSchema: Tool.getJsonSchema(tool),
441 annotations: {
442 ...Context.getOption(tool.annotations, Tool.Title).pipe(
443 Option.map((title) => ({ title })),
444 Option.getOrUndefined,
445 ),
446 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
447 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
448 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
449 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
450 },
451 }),
452 annotations: tool.annotations,
453 handle: (payload) =>
454 Effect.withFiber((fiber) => {
455 const invocation = Context.getUnsafe(
456 fiber.context,
457 McpInvocationContext.McpInvocationContext,
458 );
459 return built.handle("preview_snapshot", payload).pipe(
460 Stream.unwrap,
461 Stream.run(Sink.last()),
462 Effect.flatMap(Effect.fromOption),
463 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
464 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
465 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
466 Effect.flatMap(({ encodedResult }) =>
467 Effect.gen(function* () {
468 const snapshot = encodedResult as SnapshotMetadata & {
469 readonly url: string;
470 readonly screenshot: {
471 readonly mimeType: "image/png";
472 readonly data: string;
473 readonly width: number;
474 readonly height: number;
475 };
476 };
477 const { screenshot, ...page } = snapshot;
478 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
479 const screenshotPath =
480 payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
481 // Images stay out of tool history unless asked for: providers replay them on every
482 // later request, and some reject inline images outright.
483 const includeImage = payload?.includeImage === true;
484 if (screenshotPath !== undefined && !includeImage) {
485 const saved = {
486 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
487 screenshotPath,
488 };
489 return new McpSchema.CallToolResult({
490 isError: false,
491 structuredContent: saved,
492 content: [{ type: "text", text: encodeJsonText(saved) }],
493 });
494 }
495 const metadata = {
496 ...page,
497 screenshot: {
498 mimeType: screenshot.mimeType,
499 width: screenshot.width,
500 height: screenshot.height,
501 },
502 ...(screenshotPath === undefined ? {} : { screenshotPath }),
503 };
504 const bounded = boundSnapshotMetadata(metadata);
505 return new McpSchema.CallToolResult({
506 isError: false,
507 structuredContent:
508 bounded.omitted.length === 0
509 ? bounded.value
510 : { ...bounded.value, omitted: bounded.omitted },
511 content: [
512 {
513 type: "text",
514 text: encodeJsonText({
515 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
516 }),
517 },
518 { type: "text", text: bounded.text },
519 ...(bounded.omitted.length === 0
520 ? []
521 : [
522 {
523 type: "text" as const,
524 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
525 },
526 ]),
527 ...(includeImage
528 ? [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]
529 : []),
530 ],
531 });
532 }),
533 ),
534 Effect.provide(saveServices),
535 Effect.matchCauseEffect({
536 onFailure: previewSnapshotFailure,
537 onSuccess: Effect.succeed,
538 }),
539 );
540 }),
541 });
542});
543​
544interface ImageToolResult {
545 readonly screenshot: {
546 readonly mimeType: "image/png";
547 readonly data: string;
548 readonly width: number;
549 readonly height: number;
550 };
551 readonly [key: string]: unknown;
553​
554/**
555 * Failures surface only their tag unless the tool describes them: the remote
556 * message may carry renderer or device output the agent should not see, and the
557 * tag is what it can act on.
558 */
559const imageToolFailure =
560 <E>(toolName: string, operation: string, failureText: string | ((error: E) => string)) =>
561 (cause: Cause.Cause<E>) => {
562 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
563 return Effect.failCause(cause).pipe(Effect.orDie);
564 }
565 const failures = cause.reasons.filter(Cause.isFailReason);
566 const firstFailure = failures[0]?.error;
567 const errorTag =
568 typeof firstFailure === "object" &&
569 firstFailure !== null &&
570 "_tag" in firstFailure &&
571 typeof firstFailure._tag === "string"
572 ? firstFailure._tag
573 : `${toolName}Error`;
574 const message =
575 typeof failureText === "string" || failures[0] === undefined
576 ? undefined
577 : failureText(failures[0].error);
578 const result = new McpSchema.CallToolResult({
579 isError: true,
580 structuredContent: {
581 error: {
582 _tag: errorTag,
583 operation,
584 failureCount: failures.length,
585 ...(message === undefined ? {} : { message }),
586 },
587 },
588 // Some clients show only the text content and others only structuredContent, so both carry it.
589 content: [
590 {
591 type: "text",
592 text: typeof failureText === "string" ? failureText : (message ?? `${toolName} failed.`),
593 },
594 ],
595 });
596 return Effect.logWarning(`${toolName} failed`, {
597 operation,
598 errorTag,
599 failureCount: failures.length,
600 }).pipe(Effect.as(result));
601 };
602​
603/**
604 * `McpServer.toolkit` serializes every result as JSON text, which is the wrong
605 * shape for a screenshot: the model needs image content.
606 */
607const registerImageTool = <T extends Tool.Any, E, R>(
608 tool: T,
609 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
610 provide: (
611 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
612 ) => Effect.Effect<
613 { readonly encodedResult: unknown },
614 E,
615 McpInvocationContext.McpInvocationContext
616 >,
617 operation: string,
618 failureText: string | ((error: E) => string),
619) =>
620 Effect.gen(function* () {
621 const server = yield* McpServer.McpServer;
622 yield* server.addTool({
623 tool: new McpSchema.Tool({
624 name: tool.name,
625 description: Tool.getDescription(tool),
626 inputSchema: Tool.getJsonSchema(tool),
627 annotations: {
628 ...Context.getOption(tool.annotations, Tool.Title).pipe(
629 Option.map((title) => ({ title })),
630 Option.getOrUndefined,
631 ),
632 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
633 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
634 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
635 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
636 },
637 }),
638 annotations: tool.annotations,
639 handle: (payload) =>
640 Effect.withFiber((fiber) => {
641 const invocation = Context.getUnsafe(
642 fiber.context,
643 McpInvocationContext.McpInvocationContext,
644 );
645 return provide(handle(payload as Tool.Parameters<T>)).pipe(
646 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
647 Effect.matchCauseEffect({
648 onFailure: imageToolFailure(tool.name, operation, failureText),
649 onSuccess: ({ encodedResult }) => {
650 const { screenshot, ...rest } = encodedResult as ImageToolResult;
651 const includeImage =
652 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
653 false;
654 const metadata = {
655 ...rest,
656 screenshot: {
657 mimeType: screenshot.mimeType,
658 width: screenshot.width,
659 height: screenshot.height,
660 },
661 };
662 return Effect.succeed(
663 new McpSchema.CallToolResult({
664 isError: false,
665 structuredContent: metadata,
666 content: [
667 { type: "text", text: JSON.stringify(metadata) },
668 ...(includeImage
669 ? [
670 {
671 type: "image" as const,
672 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
673 mimeType: screenshot.mimeType,
674 },
675 ]
676 : []),
677 ],
678 }),
679 );
680 },
681 }),
682 );
683 }),
684 });
685 });
686​
687const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
688 const devices = yield* DeviceService.DeviceService;
689 const threads = yield* ThreadManagementService.ThreadManagementService;
690 const built = yield* DeviceScreenshotToolkit;
691 yield* registerImageTool(
692 DeviceScreenshotTool,
693 (payload) =>
694 built
695 .handle("device_screenshot", payload)
696 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
697 (effect) =>
698 effect.pipe(
699 Effect.provideService(DeviceService.DeviceService, devices),
700 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
701 ),
702 "screenshot",
703 "Device screenshot failed.",
704 );
705});
706​
707const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
708​
709const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
710 const htmlRender = yield* HtmlRender.HtmlRender;
711 const threads = yield* ThreadManagementService.ThreadManagementService;
712 const built = yield* HtmlPreviewToolkit;
713 yield* registerImageTool(
714 HtmlPreviewTool,
715 (payload) =>
716 built
717 .handle("html_preview", payload)
718 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
719 (effect) =>
720 effect.pipe(
721 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
722 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
723 ),
724 "preview",
725​
726 (error) =>
727 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
728 ? error.message
729 : "HTML preview failed.",
730 );
731});
732​
733/**
734 * `McpServer.toolkit` asks for every service its tools declare when it
735 * registers them, but the auth middleware provides `McpInvocationContext` to
736 * each request instead. Registration must not get one: the services it
737 * captures would replace the request's.
738 */
739export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
740 toolkit: Toolkit.Toolkit<Tools>,
741 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
742) => {
743 const registration = McpServer.toolkit(toolkit);
744 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
745 const registered = registration as Layer.Layer<
746 never,
747 never,
748 Exclude<Layer.Services<typeof registration>, McpInvocationContext.McpInvocationContext>
749 >;
750 return registered.pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
751};
752​
753const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
754 register: Effect.Effect<A, E, R>,
755 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
756) => Layer.effectDiscard(register).pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
757​
758export const layerHtmlToolkit = Layer.mergeAll(
759 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
760 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
761).pipe(Layer.provide(HtmlRender.layer));
762​
763const layerPreviewStandardToolkitRegistration = toolkitRegistration(
764 PreviewStandardToolkit,
765 PreviewHandlers.layerStandard,
766);
767​
768const layerPreviewSnapshotRegistration = imageToolRegistration(
769 registerPreviewSnapshot(),
770 PreviewHandlers.layerSnapshot,
771);
772​
773export const layerPreviewToolkit = Layer.mergeAll(
774 layerPreviewStandardToolkitRegistration,
775 layerPreviewSnapshotRegistration,
776);
777​
778export const layerOrchestratorToolkit = toolkitRegistration(
779 OrchestratorToolkit,
780 OrchestratorHandlers.layer,
781).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
782​
783export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
784​
785const layerWorktreeToolkitRegistration = toolkitRegistration(
786 WorktreeToolkit,
787 WorktreeHandlers.layer,
788).pipe(Layer.provide(WorktreeMcpService.layer));
789​
790const layerPreviewControlsRegistration = toolkitRegistration(
791 PreviewControlsToolkit,
792 PreviewControlsHandlers.layer,
793);
794​
795export const layerEnvironmentToolkit = toolkitRegistration(
796 EnvironmentToolkit,
797 EnvironmentHandlers.layer,
798).pipe(Layer.provide(ThreadCommandExecutor.layer));
799​
800const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
801​
802export const layerAttachmentToolkit = toolkitRegistration(
803 AttachmentToolkit,
804 AttachmentHandlers.layer,
805);
806​
807export const layerPullRequestsToolkit = toolkitRegistration(
808 PullRequestsToolkit,
809 PullRequestsHandlers.layer,
810);
811​
812const layerDeviceStandardToolkitRegistration = toolkitRegistration(
813 DeviceStandardToolkit,
814 DeviceHandlers.layerStandard,
815);
816​
817const layerDeviceScreenshotRegistration = imageToolRegistration(
818 registerDeviceScreenshot(),
819 DeviceHandlers.layerScreenshot,
820);
821​
822export const layerDeviceToolkit = Layer.mergeAll(
823 layerDeviceStandardToolkitRegistration,
824 layerDeviceScreenshotRegistration,
825);
826​
827export const layerMcpTransport = McpServer.layerHttp({
828 name: "T3 Code",
829 version: packageJson.version,
830 path: "/mcp",
831 protocols: [McpProtocol.v2025_06_18],
832 allowSessionTermination: true,
833}).pipe(Layer.provide(layerMcpAuthMiddleware));
834​
835export const layer = Layer.mergeAll(
836 layerPreviewToolkit,
837 layerOrchestratorToolkit,
838 layerThreadToolkit,
839 layerAttachmentToolkit,
840 layerProjectRegistration,
841 layerEnvironmentToolkit,
842 layerPreviewControlsRegistration,
843 layerWorktreeToolkitRegistration,
844 layerPullRequestsToolkit,
845 layerDeviceToolkit,
846 layerHtmlToolkit,
847).pipe(Layer.provideMerge(layerMcpTransport));