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