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

McpHttpServer.ts

1,080 lines41.3 KB

1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import type * as Types from "effect/Types";
14import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
15import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16import {
17 OrchestratorMcpFailure,
18 PreviewAutomationError,
19 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 = Effect.fn("McpHttpServer.registerImageTool")(function* <
638 T extends Tool.Any,
639 E,
640 R,
641>(
642 tool: T,
643 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
644 provide: (
645 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
646 ) => Effect.Effect<
647 { readonly encodedResult: unknown },
648 E,
649 McpInvocationContext.McpInvocationContext
650 >,
651 operation: string,
652 failureText: string | ((error: E) => string),
653) {
654 const server = yield* McpServer.McpServer;
655 yield* server.addTool({
656 tool: new McpSchema.Tool({
657 name: tool.name,
658 description: Tool.getDescription(tool),
659 inputSchema: Tool.getJsonSchema(tool),
660 annotations: {
661 ...Context.getOption(tool.annotations, Tool.Title).pipe(
662 Option.map((title) => ({ title })),
663 Option.getOrUndefined,
664 ),
665 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
666 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
667 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
668 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
669 },
670 }),
671 annotations: tool.annotations,
672 handle: (payload) =>
673 Effect.withFiber((fiber) => {
674 const invocation = Context.getUnsafe(
675 fiber.context,
676 McpInvocationContext.McpInvocationContext,
677 );
678 return provide(handle(payload as Tool.Parameters<T>)).pipe(
679 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
680 Effect.matchCauseEffect({
681 onFailure: imageToolFailure(tool.name, operation, failureText),
682 onSuccess: ({ encodedResult }) => {
683 const { screenshot, ...rest } = encodedResult as ImageToolResult;
684 const includeImage =
685 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
686 false;
687 const metadata = {
688 ...rest,
689 screenshot: {
690 mimeType: screenshot.mimeType,
691 width: screenshot.width,
692 height: screenshot.height,
693 },
694 };
695 return Effect.succeed(
696 new McpSchema.CallToolResult({
697 isError: false,
698 structuredContent: metadata,
699 content: [
700 { type: "text", text: JSON.stringify(metadata) },
701 ...(includeImage
702 ? [
703 {
704 type: "image" as const,
705 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
706 mimeType: screenshot.mimeType,
707 },
708 ]
709 : []),
710 ],
711 }),
712 );
713 },
714 }),
715 );
716 }),
717 });
718});
719​
720const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
721 const devices = yield* DeviceService.DeviceService;
722 const threads = yield* ThreadManagementService.ThreadManagementService;
723 const built = yield* decodeAsAdvertised(DeviceScreenshotToolkit);
724 yield* registerImageTool(
725 DeviceScreenshotTool,
726 (payload) =>
727 built
728 .handle("device_screenshot", payload)
729 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
730 (effect) =>
731 effect.pipe(
732 Effect.provideService(DeviceService.DeviceService, devices),
733 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
734 ),
735 "screenshot",
736 "Device screenshot failed.",
737 );
738});
739​
740const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
741​
742const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
743 const htmlRender = yield* HtmlRender.HtmlRender;
744 const threads = yield* ThreadManagementService.ThreadManagementService;
745 const built = yield* decodeAsAdvertised(HtmlPreviewToolkit);
746 yield* registerImageTool(
747 HtmlPreviewTool,
748 (payload) =>
749 built
750 .handle("html_preview", payload)
751 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
752 (effect) =>
753 effect.pipe(
754 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
755 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
756 ),
757 "preview",
758​
759 (error) =>
760 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
761 ? error.message
762 : "HTML preview failed.",
763 );
764});
765​
766/**
767 * Tools that hand work to another thread's agent: they create it, message it,
768 * steer it, or move context into it. Their events name the receiving agent too.
769 */
770const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
771 "delegate_task",
772 "create_threads",
773 "t3_thread_launch",
774 "t3_thread_send",
775 "t3_thread_send_attachments",
776 "t3_thread_fork",
777 "t3_thread_merge_back",
778 "t3_queue_edit",
779 "t3_queue_promote_to_steer",
780 "t3_pending_request_respond",
781 "schedule_task",
782 "run_scheduled_task_now",
783]);
784​
785/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */
786const INPUT_TARGET_TOOLS: ReadonlySet<string> = new Set([
787 "t3_queue_edit",
788 "t3_queue_promote_to_steer",
789 "t3_pending_request_respond",
790]);
791​
792const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
793​
794/** Thread ids a handoff tool result names: the thread that received the work. */
795const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
796 if (typeof content !== "object" || content === null) return [];
797 const record = content as Readonly<Record<string, unknown>>;
798 if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
799 const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
800 return key === undefined ? [] : [record[key] as string];
801};
802​
803/**
804 * Thread ids that received a handoff. The input's `threadId` is used only after
805 * the call succeeded, so it is one the handler already resolved and authorized.
806 */
807const handoffTargetIds = (
808 tool: string,
809 args: unknown,
810 result: McpSchema.CallToolResult | undefined,
811): ReadonlyArray<string> => {
812 if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent);
813 if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
814 const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
815 return typeof threadId === "string" ? [threadId] : [];
816};
817​
818/**
819 * Runs a tool registration against a server that records one anonymous
820 * `mcp.tool.invoked` event per call: the tool, the calling agent's provider,
821 * the outcome with its failure code, and the duration. A handoff tool also
822 * reports the caller's model, origin, and delegation depth, the settings the
823 * agent chose, and the provider, model, and modes of each thread that received
824 * the work. Ids, prompts, and free text are never recorded.
825 */
826const withToolAnalytics =
827 /* Request instrumentation already owns the span; keep this helper in that context. */
828 Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
829 const server = yield* McpServer.McpServer;
830 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
831 if (Option.isNone(analytics)) return yield* registration;
832 const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
833 const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
834 const shellOf = (threadId: string) =>
835 Option.isNone(threads)
836 ? Effect.succeed(null)
837 : threads.value
838 .getThreadShell(ThreadId.make(threadId))
839 .pipe(Effect.orElseSucceed(() => null));
840 // Delegation depth: parents walked from the caller, capped.
841 const depthOf =
842 /* Request instrumentation already owns the span; keep this helper in that context. */
843 Effect.fnUntraced(function* (thread: AgentThread) {
844 let depth = 0;
845 let parentId =
846 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
847 while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
848 depth += 1;
849 const parent = yield* shellOf(parentId);
850 parentId =
851 parent?.lineage.relationshipToParent === "subagent"
852 ? parent.lineage.parentThreadId
853 : null;
854 }
855 return depth;
856 });
857 // Whether the caller's active run was started by a scheduled task.
858 const scheduledRunOf = (threadId: string, runId: RunId | null) =>
859 Option.isNone(threads) || runId === null
860 ? Effect.succeed(false)
861 : threads.value
862 .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
863 runIds: [runId],
864 messageRoles: ["user"],
865 })
866 .pipe(
867 Effect.map((records) => {
868 const run = records.runs.find((candidate) => candidate.id === runId);
869 return records.messages.some(
870 (message) =>
871 message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
872 );
873 }),
874 Effect.orElseSucceed(() => false),
875 );
876 const record =
877 /* Request instrumentation already owns the span; keep this helper in that context. */
878 Effect.fnUntraced(
879 function* (
880 tool: string,
881 args: unknown,
882 result: McpSchema.CallToolResult | undefined,
883 durationMs: number,
884 ) {
885 // Client credentials (no calling thread) report an unknown caller.
886 const invocation = Option.getOrUndefined(
887 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
888 )?.thread;
889 const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
890 // Only handoff tools pay for thread lookups; the rest report the
891 // caller's provider from the credential.
892 const handoff = HANDOFF_TOOLS.has(tool);
893 const caller =
894 handoff && invocation !== undefined
895 ? ((yield* shellOf(invocation.threadId)) ?? undefined)
896 : undefined;
897 const targetIds = handoff
898 ? [...new Set(handoffTargetIds(tool, args, result))].filter(
899 (threadId) => threadId !== invocation?.threadId,
900 )
901 : [];
902 const targets = yield* Effect.forEach(targetIds, shellOf);
903 for (const properties of agentToolProperties({
904 tool,
905 providers,
906 caller,
907 ...(invocation === undefined
908 ? {}
909 : { callerProviderInstanceId: invocation.providerInstanceId }),
910 ...(caller === undefined || invocation === undefined
911 ? {}
912 : {
913 callerDepth: yield* depthOf(caller),
914 callerScheduledRun: yield* scheduledRunOf(
915 invocation.threadId,
916 caller.activeRunId,
917 ),
918 }),
919 targets: targets.filter((thread) => thread !== null),
920 outcome: toolOutcome(result),
921 ...(handoff
922 ? { settings: handoffSettings(tool, args, result?.structuredContent) }
923 : {}),
924 durationMs,
925 })) {
926 yield* analytics.value.record("mcp.tool.invoked", properties);
927 }
928 },
929 (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
930 );
931 const recordingServer = McpServer.McpServer.of({
932 ...server,
933 addTool: (options) =>
934 server.addTool({
935 ...options,
936 handle:
937 /* Request instrumentation already owns the span; keep this helper in that context. */
938 Effect.fnUntraced(function* (payload) {
939 const startedAt = yield* Clock.currentTimeMillis;
940 return yield* options.handle(payload).pipe(
941 Effect.onExit((exit) => {
942 const result = exit._tag === "Success" ? exit.value : undefined;
943 // A call that asks for input is retried with it, and that call is the one counted.
944 if (result instanceof McpSchema.InputRequired) return Effect.void;
945 // Handoff tools look up threads to record; the response must not wait on them.
946 return Clock.currentTimeMillis.pipe(
947 Effect.flatMap((endedAt) =>
948 record(options.tool.name, payload, result, endedAt - startedAt),
949 ),
950 Effect.forkDetach,
951 Effect.asVoid,
952 );
953 }),
954 );
955 }),
956 }),
957 });
958 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
959 });
960​
961/**
962 * `McpServer.toolkit` asks for every service its tools declare when it
963 * registers them, but the auth middleware provides `McpInvocationContext` to
964 * each request instead. Registration must not get one: the services it
965 * captures would replace the request's.
966 */
967export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
968 toolkit: Toolkit.Toolkit<Tools>,
969 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
970) => {
971 const registration = Layer.effectDiscard(
972 withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
973 ).pipe(Layer.provide(McpServer.McpServer.layer));
974 // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
975 const registered = registration as Layer.Layer<
976 never,
977 never,
978 Exclude<Layer.Services<typeof registration>, McpInvocationContext.McpInvocationContext>
979 >;
980 return registered.pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
981};
982​
983const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
984 register: Effect.Effect<A, E, R>,
985 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
986) =>
987 Layer.effectDiscard(withToolAnalytics(register)).pipe(
988 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
989 );
990​
991export const layerHtmlToolkit = Layer.mergeAll(
992 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
993 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
994).pipe(Layer.provide(HtmlRender.layer));
995​
996const layerPreviewStandardToolkitRegistration = toolkitRegistration(
997 PreviewStandardToolkit,
998 PreviewHandlers.layerStandard,
999);
1000​
1001const layerPreviewSnapshotRegistration = imageToolRegistration(
1002 registerPreviewSnapshot(),
1003 PreviewHandlers.layerSnapshot,
1005​
1006export const layerPreviewToolkit = Layer.mergeAll(
1007 layerPreviewStandardToolkitRegistration,
1008 layerPreviewSnapshotRegistration,
1010​
1011export const layerOrchestratorToolkit = toolkitRegistration(
1012 OrchestratorToolkit,
1013 OrchestratorHandlers.layer,
1014).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
1015​
1016export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
1017​
1018const layerWorktreeToolkitRegistration = toolkitRegistration(
1019 WorktreeToolkit,
1020 WorktreeHandlers.layer,
1021).pipe(Layer.provide(WorktreeMcpService.layer));
1022​
1023const layerPreviewControlsRegistration = toolkitRegistration(
1024 PreviewControlsToolkit,
1025 PreviewControlsHandlers.layer,
1027​
1028export const layerEnvironmentToolkit = toolkitRegistration(
1029 EnvironmentToolkit,
1030 EnvironmentHandlers.layer,
1031).pipe(Layer.provide(ThreadCommandExecutor.layer));
1032​
1033const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1034​
1035export const layerAttachmentToolkit = toolkitRegistration(
1036 AttachmentToolkit,
1037 AttachmentHandlers.layer,
1039​
1040export const layerPullRequestsToolkit = toolkitRegistration(
1041 PullRequestsToolkit,
1042 PullRequestsHandlers.layer,
1044​
1045const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1046 DeviceStandardToolkit,
1047 DeviceHandlers.layerStandard,
1049​
1050const layerDeviceScreenshotRegistration = imageToolRegistration(
1051 registerDeviceScreenshot(),
1052 DeviceHandlers.layerScreenshot,
1054​
1055export const layerDeviceToolkit = Layer.mergeAll(
1056 layerDeviceStandardToolkitRegistration,
1057 layerDeviceScreenshotRegistration,
1059​
1060export const layerMcpTransport = McpServer.layerHttp({
1061 name: "T3 Code",
1062 version: packageJson.version,
1063 path: "/mcp",
1064 protocols: [McpProtocol.v2025_06_18],
1065 allowSessionTermination: true,
1066}).pipe(Layer.provide(layerMcpAuthMiddleware));
1067​
1068export const layer = Layer.mergeAll(
1069 layerPreviewToolkit,
1070 layerOrchestratorToolkit,
1071 layerThreadToolkit,
1072 layerAttachmentToolkit,
1073 layerProjectRegistration,
1074 layerEnvironmentToolkit,
1075 layerPreviewControlsRegistration,
1076 layerWorktreeToolkitRegistration,
1077 layerPullRequestsToolkit,
1078 layerDeviceToolkit,
1079 layerHtmlToolkit,
1080).pipe(Layer.provideMerge(layerMcpTransport));