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