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