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