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