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

McpHttpServer.ts

1,254 lines48.0 KB

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 }
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 readonly fullScreenshot?: { readonly data: string };
561 };
562 const { screenshot, fullScreenshot, ...page } = snapshot;
563 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
564 const screenshotPath =
565 payload?.save === true
566 ? yield* saveScreenshot(
567 snapshot.url,
568 fullScreenshot
569 ? new Uint8Array(Buffer.from(fullScreenshot.data, "base64"))
570 : png,
571 )
572 : undefined;
573 // Providers replay images on later requests, and some reject them; include images only when requested.
574 const includeImage = payload?.includeImage === true;
575 if (screenshotPath !== undefined && !includeImage) {
576 const saved = {
577 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
578 screenshotPath,
579 };
580 return new McpSchema.CallToolResult({
581 isError: false,
582 structuredContent: saved,
583 content: [{ type: "text", text: encodeJsonText(saved) }],
584 });
585 }
586 const metadata = {
587 ...page,
588 screenshot: {
589 mimeType: screenshot.mimeType,
590 width: screenshot.width,
591 height: screenshot.height,
592 },
593 ...(screenshotPath === undefined ? {} : { screenshotPath }),
594 };
595 const bounded = boundSnapshotMetadata(metadata);
596 return new McpSchema.CallToolResult({
597 isError: false,
598 structuredContent:
599 bounded.omitted.length === 0
600 ? bounded.value
601 : { ...bounded.value, omitted: bounded.omitted },
602 content: [
603 {
604 type: "text",
605 text: encodeJsonText({
606 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
607 }),
608 },
609 { type: "text", text: bounded.text },
610 ...(bounded.omitted.length === 0
611 ? []
612 : [
613 {
614 type: "text" as const,
615 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
616 },
617 ]),
618 ...(includeImage
619 ? [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]
620 : []),
621 ],
622 });
623 }),
624 ),
625 Effect.provide(saveServices),
626 Effect.matchCauseEffect({
627 onFailure: previewSnapshotFailure,
628 onSuccess: Effect.succeed,
629 }),
630 );
631 }),
632 });
633});
634​
635interface ImageToolResult {
636 readonly screenshot: {
637 readonly mimeType: "image/png";
638 readonly data: string;
639 readonly width: number;
640 readonly height: number;
641 };
642 readonly [key: string]: unknown;
644​
645/** Expose only undescribed failures' tags; remote messages may contain renderer or device output. */
646const imageToolFailure =
647 <E>(toolName: string, operation: string, failureText: string | ((error: E) => string)) =>
648 (cause: Cause.Cause<E>) => {
649 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
650 return Effect.failCause(cause).pipe(Effect.orDie);
651 }
652 const failures = cause.reasons.filter(Cause.isFailReason);
653 const firstFailure = failures[0]?.error;
654 const errorTag =
655 typeof firstFailure === "object" &&
656 firstFailure !== null &&
657 "_tag" in firstFailure &&
658 typeof firstFailure._tag === "string"
659 ? firstFailure._tag
660 : `${toolName}Error`;
661 const message =
662 typeof failureText === "string" || failures[0] === undefined
663 ? undefined
664 : failureText(failures[0].error);
665 const result = new McpSchema.CallToolResult({
666 isError: true,
667 structuredContent: {
668 error: {
669 _tag: errorTag,
670 operation,
671 failureCount: failures.length,
672 ...(message === undefined ? {} : { message }),
673 },
674 },
675 // Some clients show only the text content and others only structuredContent, so both carry it.
676 content: [
677 {
678 type: "text",
679 text: typeof failureText === "string" ? failureText : (message ?? `${toolName} failed.`),
680 },
681 ],
682 });
683 return Effect.logWarning(`${toolName} failed`, {
684 operation,
685 errorTag,
686 failureCount: failures.length,
687 }).pipe(Effect.as(result));
688 };
689​
690/**
691 * `McpServer.toolkit` serializes every result as JSON text, which is the wrong
692 * shape for a screenshot: the model needs image content.
693 */
694const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* <
695 T extends Tool.Any,
696 E,
697 R,
698>(
699 tool: T,
700 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
701 provide: (
702 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
703 ) => Effect.Effect<
704 { readonly encodedResult: unknown },
705 E,
706 McpInvocationContext.McpInvocationContext
707 >,
708 operation: string,
709 failureText: string | ((error: E) => string),
710) {
711 const server = yield* McpServer.McpServer;
712 yield* server.addTool({
713 tool: new McpSchema.Tool({
714 name: tool.name,
715 description: Tool.getDescription(tool),
716 inputSchema: advertisedJsonSchema(tool),
717 annotations: {
718 ...Context.getOption(tool.annotations, Tool.Title).pipe(
719 Option.map((title) => ({ title })),
720 Option.getOrUndefined,
721 ),
722 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
723 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
724 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
725 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
726 },
727 }),
728 annotations: tool.annotations,
729 handle: (payload) =>
730 Effect.withFiber((fiber) => {
731 const invocation = Context.getUnsafe(
732 fiber.context,
733 McpInvocationContext.McpInvocationContext,
734 );
735 return provide(handle(payload as Tool.Parameters<T>)).pipe(
736 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
737 Effect.matchCauseEffect({
738 onFailure: imageToolFailure(tool.name, operation, failureText),
739 onSuccess: ({ encodedResult }) => {
740 const { screenshot, ...rest } = encodedResult as ImageToolResult;
741 const includeImage =
742 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
743 false;
744 const metadata = {
745 ...rest,
746 screenshot: {
747 mimeType: screenshot.mimeType,
748 width: screenshot.width,
749 height: screenshot.height,
750 },
751 };
752 return Effect.succeed(
753 new McpSchema.CallToolResult({
754 isError: false,
755 structuredContent: metadata,
756 content: [
757 { type: "text", text: JSON.stringify(metadata) },
758 ...(includeImage
759 ? [
760 {
761 type: "image" as const,
762 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
763 mimeType: screenshot.mimeType,
764 },
765 ]
766 : []),
767 ],
768 }),
769 );
770 },
771 }),
772 );
773 }),
774 });
775});
776​
777const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
778 const devices = yield* DeviceService.DeviceService;
779 const threads = yield* ThreadManagementService.ThreadManagementService;
780 const built = yield* decodeAsAdvertised(DeviceScreenshotToolkit);
781 yield* registerImageTool(
782 DeviceScreenshotTool,
783 (payload) =>
784 built
785 .handle("device_screenshot", payload)
786 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
787 (effect) =>
788 effect.pipe(
789 Effect.provideService(DeviceService.DeviceService, devices),
790 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
791 ),
792 "screenshot",
793 (error) => {
794 if (!isDeviceToolError(error)) {
795 return isOrchestratorMcpFailure(error) ? error.message : "Device screenshot failed.";
796 }
797 return error._tag === "DeviceOperationError" && error.reason === "hub_rejected"
798 ? `${error.message} Call device_list to check the device state, and device_open if it needs to be reopened.`
799 : error.message;
800 },
801 );
802});
803​
804const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure);
805const isDeviceToolError = Schema.is(DeviceToolError);
806​
807const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () {
808 const htmlRender = yield* HtmlRender.HtmlRender;
809 const threads = yield* ThreadManagementService.ThreadManagementService;
810 const built = yield* decodeAsAdvertised(HtmlPreviewToolkit);
811 yield* registerImageTool(
812 HtmlPreviewTool,
813 (payload) =>
814 built
815 .handle("html_preview", payload)
816 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
817 (effect) =>
818 effect.pipe(
819 Effect.provideService(HtmlRender.HtmlRender, htmlRender),
820 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
821 ),
822 "preview",
823​
824 (error) =>
825 isOrchestratorMcpFailure(error) || AiError.isAiError(error)
826 ? error.message
827 : "HTML preview failed.",
828 );
829});
830​
831/**
832 * Tools that hand work to another thread's agent: they create it, message it,
833 * steer it, or move context into it. Their events name the receiving agent too.
834 */
835const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
836 "delegate_task",
837 "create_threads",
838 "t3_thread_launch",
839 "t3_thread_send",
840 "t3_thread_send_attachments",
841 "schedule_task",
842 "run_scheduled_task_now",
843]);
844​
845/** Tool actions that hand work over with only a `{ sequence }` result; the input names the thread. */
846const INPUT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
847 t3_queue: new Set(["edit", "promote_to_steer"]),
848 t3_pending_request: new Set(["respond"]),
849};
850​
851/** Tool actions that hand work over and name the receiving thread in their result. */
852const RESULT_TARGET_ACTIONS: Readonly<Record<string, ReadonlySet<string>>> = {
853 t3_thread_transfer: new Set(["fork", "merge_back"]),
854};
855​
856const hasAction = (
857 actions: Readonly<Record<string, ReadonlySet<string>>>,
858 tool: string,
859 args: unknown,
860) =>
861 actions[tool]?.has(String((args as { readonly action?: unknown } | null | undefined)?.action)) ===
862 true;
863​
864const isInputTargetHandoff = (tool: string, args: unknown) =>
865 hasAction(INPUT_TARGET_ACTIONS, tool, args);
866​
867const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
868​
869/** Thread ids a handoff tool result names: the thread that received the work. */
870const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
871 if (typeof content !== "object" || content === null) return [];
872 const record = content as Readonly<Record<string, unknown>>;
873 if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
874 const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
875 return key === undefined ? [] : [record[key] as string];
876};
877​
878/**
879 * Thread ids that received a handoff. The input's `threadId` is used only after
880 * the call succeeded, so it is one the handler already resolved and authorized.
881 */
882const handoffTargetIds = (
883 tool: string,
884 args: unknown,
885 result: McpSchema.CallToolResult | undefined,
886): ReadonlyArray<string> => {
887 if (!isInputTargetHandoff(tool, args)) return resultThreadIds(result?.structuredContent);
888 if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
889 const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
890 return typeof threadId === "string" ? [threadId] : [];
891};
892​
893/** Tool analytics must never include IDs, prompts or free text. */
894const withToolAnalytics =
895 /* Request instrumentation already owns the span; keep this helper in that context. */
896 Effect.fnUntraced(function* <A, E, R>(registration: Effect.Effect<A, E, R>) {
897 const server = yield* McpServer.McpServer;
898 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
899 if (Option.isNone(analytics)) return yield* registration;
900 const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
901 const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
902 const shellOf = (threadId: string) =>
903 Option.isNone(threads)
904 ? Effect.succeed(null)
905 : threads.value
906 .getThreadShell(ThreadId.make(threadId))
907 .pipe(Effect.orElseSucceed(() => null));
908 // Delegation depth: parents walked from the caller, capped.
909 const depthOf =
910 /* Request instrumentation already owns the span; keep this helper in that context. */
911 Effect.fnUntraced(function* (thread: AgentThread) {
912 let depth = 0;
913 let parentId =
914 thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
915 while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
916 depth += 1;
917 const parent = yield* shellOf(parentId);
918 parentId =
919 parent?.lineage.relationshipToParent === "subagent"
920 ? parent.lineage.parentThreadId
921 : null;
922 }
923 return depth;
924 });
925 // Whether the caller's active run was started by a scheduled task.
926 const scheduledRunOf = (threadId: string, runId: RunId | null) =>
927 Option.isNone(threads) || runId === null
928 ? Effect.succeed(false)
929 : threads.value
930 .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
931 runIds: [runId],
932 messageRoles: ["user"],
933 })
934 .pipe(
935 Effect.map((records) => {
936 const run = records.runs.find((candidate) => candidate.id === runId);
937 return records.messages.some(
938 (message) =>
939 message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
940 );
941 }),
942 Effect.orElseSucceed(() => false),
943 );
944 const record =
945 /* Request instrumentation already owns the span; keep this helper in that context. */
946 Effect.fnUntraced(
947 function* (
948 tool: string,
949 args: unknown,
950 result: McpSchema.CallToolResult | undefined,
951 durationMs: number,
952 ) {
953 const handoff =
954 HANDOFF_TOOLS.has(tool) ||
955 isInputTargetHandoff(tool, args) ||
956 hasAction(RESULT_TARGET_ACTIONS, tool, args);
957 const outcome = toolOutcome(result);
958 // Agents call status, read, and preview tools in tight loops, so an
959 // event per successful call floods analytics. Only failures count there.
960 if (!handoff && outcome.outcome === "ok") return;
961 // Client credentials (no calling thread) report an unknown caller.
962 const invocation = Option.getOrUndefined(
963 yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
964 )?.thread;
965 const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
966 // Only handoff tools pay for thread lookups; the rest report the
967 // caller's provider from the credential.
968 const caller =
969 handoff && invocation !== undefined
970 ? ((yield* shellOf(invocation.threadId)) ?? undefined)
971 : undefined;
972 const targetIds = handoff
973 ? [...new Set(handoffTargetIds(tool, args, result))].filter(
974 (threadId) => threadId !== invocation?.threadId,
975 )
976 : [];
977 const targets = yield* Effect.forEach(targetIds, shellOf);
978 for (const properties of agentToolProperties({
979 tool,
980 providers,
981 caller,
982 ...(invocation === undefined
983 ? {}
984 : { callerProviderInstanceId: invocation.providerInstanceId }),
985 ...(caller === undefined || invocation === undefined
986 ? {}
987 : {
988 callerDepth: yield* depthOf(caller),
989 callerScheduledRun: yield* scheduledRunOf(
990 invocation.threadId,
991 caller.activeRunId,
992 ),
993 }),
994 targets: targets.filter((thread) => thread !== null),
995 outcome,
996 ...(handoff
997 ? { settings: handoffSettings(tool, args, result?.structuredContent) }
998 : {}),
999 durationMs,
1000 })) {
1001 yield* analytics.value.record("mcp.tool.invoked", properties);
1003 },
1004 (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause),
1005 );
1006 const recordingServer = McpServer.McpServer.of({
1007 ...server,
1008 addTool: Effect.fn("McpServer.addTool")(function (options) {
1009 return server.addTool({
1010 ...options,
1011 handle:
1012 /* Request instrumentation already owns the span; keep this helper in that context. */
1013 Effect.fnUntraced(function* (payload) {
1014 const startedAt = yield* Clock.currentTimeMillis;
1015 return yield* options.handle(payload).pipe(
1016 Effect.onExit((exit) => {
1017 const result = exit._tag === "Success" ? exit.value : undefined;
1018 // A call that asks for input is retried with it, and that call is the one counted.
1019 if (result instanceof McpSchema.InputRequired) return Effect.void;
1020 // Handoff tools look up threads to record; the response must not wait on them.
1021 return Clock.currentTimeMillis.pipe(
1022 Effect.flatMap((endedAt) =>
1023 record(options.tool.name, payload, result, endedAt - startedAt),
1024 ),
1025 Effect.forkDetach,
1026 Effect.asVoid,
1027 );
1028 }),
1029 );
1030 }),
1031 });
1032 }),
1033 });
1034 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
1035 });
1036​
1037/** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */
1038const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* <A, E, R>(
1039 registration: Effect.Effect<A, E, R>,
1040) {
1041 const server = yield* McpServer.McpServer;
1042 const tracingServer = McpServer.McpServer.of({
1043 ...server,
1044 addTool: Effect.fn("McpServer.addTool")(function (options) {
1045 const name = options.tool.name;
1046 return server.addTool({
1047 ...options,
1048 // Never the current span: Toolkit.handle annotates that one with the raw arguments.
1049 handle: (payload) =>
1050 Effect.useSpan(
1051 `mcp.tool.${name}`,
1053 attributes: {
1054 "rpc.system": "mcp",
1055 "rpc.method": "tools/call",
1056 "mcp.tool.name": name,
1057 },
1058 },
1059 () => options.handle(payload),
1060 ),
1061 });
1062 }),
1063 });
1064 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, tracingServer));
1065});
1066​
1067/** `McpServer.registerToolkit` advertises the full codec schema; agents get the compact one. */
1068const withAdvertisedSchemas = Effect.fn("McpHttpServer.withAdvertisedSchemas")(function* <
1069 Tools extends Record<string, Tool.Any>,
1070 A,
1071 E,
1072 R,
1073>(toolkit: Toolkit.Toolkit<Tools>, registration: Effect.Effect<A, E, R>) {
1074 const server = yield* McpServer.McpServer;
1075 const tools: Record<string, Tool.Any> = toolkit.tools;
1076 const advertisingServer = McpServer.McpServer.of({
1077 ...server,
1078 addTool: Effect.fn("McpServer.addTool")(function (options) {
1079 const tool = tools[options.tool.name];
1080 return server.addTool(
1081 tool === undefined
1082 ? options
1083 : {
1084 ...options,
1085 tool: new McpSchema.Tool({
1086 ...options.tool,
1087 inputSchema: advertisedJsonSchema(tool),
1088 }),
1089 },
1090 );
1091 }),
1092 });
1093 return yield* registration.pipe(Effect.provideService(McpServer.McpServer, advertisingServer));
1094});
1095​
1096/** Hands each call the services its registration was built with; the request's own still win. */
1097const provideRegistrationServices = <Services>() =>
1098 McpServer.middleware<{ provides: Services }>()(
1099 Effect.map(
1100 Effect.context<Services>(),
1101 (services) => (effect) =>
1102 Effect.updateContext(effect, (request: Context.Context<never>) =>
1103 Context.merge(services, request),
1104 ),
1105 ),
1106 );
1107​
1108/**
1109 * Tools declare their handler services as request-level dependencies. Those
1110 * built with the server are provided here; `McpInvocationContext` is left to
1111 * the transport, whose auth middleware resolves it per request.
1112 */
1113export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX, RX>(
1114 toolkit: Toolkit.Toolkit<Tools>,
1115 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
1116) =>
1117 Layer.effectDiscard(
1118 withToolAnalytics(
1119 withToolSpans(
1120 withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
1121 ),
1122 ),
1123 ).pipe(
1124 Layer.provide(
1125 provideRegistrationServices<
1126 Exclude<Tool.Requirements<Tools[keyof Tools]>, McpInvocationContext.McpInvocationContext>
1127 >().layer,
1128 ),
1129 Layer.provide(McpServer.McpServer.layer),
1130 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
1131 );
1132​
1133const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
1134 register: Effect.Effect<A, E, R>,
1135 handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
1136) =>
1137 Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe(
1138 Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
1139 );
1140​
1141export const layerHtmlToolkit = Layer.mergeAll(
1142 toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
1143 imageToolRegistration(registerHtmlPreview(), HtmlHandlers.layerPreview),
1144).pipe(Layer.provide(HtmlRender.layer));
1145​
1146const layerPreviewStandardToolkitRegistration = toolkitRegistration(
1147 PreviewStandardToolkit,
1148 PreviewHandlers.layerStandard,
1150​
1151const layerPreviewSnapshotRegistration = imageToolRegistration(
1152 registerPreviewSnapshot(),
1153 PreviewHandlers.layerSnapshot,
1155​
1156export const layerPreviewToolkit = Layer.mergeAll(
1157 layerPreviewStandardToolkitRegistration,
1158 layerPreviewSnapshotRegistration,
1160​
1161export const layerOrchestratorToolkit = toolkitRegistration(
1162 OrchestratorToolkit,
1163 OrchestratorHandlers.layer,
1164).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer));
1165​
1166export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
1167​
1168const layerWorktreeToolkitRegistration = toolkitRegistration(
1169 WorktreeToolkit,
1170 WorktreeHandlers.layer,
1171).pipe(Layer.provide(WorktreeMcpService.layer));
1172​
1173const layerPreviewControlsRegistration = toolkitRegistration(
1174 PreviewControlsToolkit,
1175 PreviewControlsHandlers.layer,
1177​
1178const layerEnvironmentToolkit = toolkitRegistration(
1179 EnvironmentToolkit,
1180 EnvironmentHandlers.layer,
1181).pipe(Layer.provide(ThreadCommandExecutor.layer));
1182​
1183export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1184​
1185export const layerAttachmentToolkit = toolkitRegistration(
1186 AttachmentToolkit,
1187 AttachmentHandlers.layer,
1189​
1190export const layerPullRequestsToolkit = toolkitRegistration(
1191 PullRequestsToolkit,
1192 PullRequestsHandlers.layer,
1194​
1195const layerDeviceStandardToolkitRegistration = toolkitRegistration(
1196 DeviceStandardToolkit,
1197 DeviceHandlers.layerStandard,
1199​
1200const layerDeviceScreenshotRegistration = imageToolRegistration(
1201 registerDeviceScreenshot(),
1202 DeviceHandlers.layerScreenshot,
1204​
1205export const layerDeviceToolkit = Layer.mergeAll(
1206 layerDeviceStandardToolkitRegistration,
1207 layerDeviceScreenshotRegistration,
1209​
1210/**
1211 * `McpServer` for in-process calls, which provide `McpInvocationContext`
1212 * around `callTool` as the auth middleware does for each /mcp request.
1213 */
1214export const layerInProcessMcpServer = McpServer.middleware<{
1215 provides: McpInvocationContext.McpInvocationContext;
1216}>()(
1217 (effect) =>
1218 Effect.flatMap(
1219 Effect.serviceOption(McpInvocationContext.McpInvocationContext),
1220 Option.match({
1221 onNone: () => Effect.die("Provide McpInvocationContext around the in-process MCP call."),
1222 onSome: (scope) =>
1223 Effect.provideService(effect, McpInvocationContext.McpInvocationContext, scope),
1224 }),
1225 ),
1226 { global: true },
1227).pipe(Layer.provideMerge(McpServer.McpServer.layer));
1228​
1229export const layerMcpTransport = <RA, RE, RR>(registrations: Layer.Layer<RA, RE, RR>) =>
1230 McpServer.layerHttp({
1231 name: "T3 Code",
1232 version: packageJson.version,
1233 path: "/mcp",
1234 protocols: [McpProtocol.v2025_06_18],
1235 allowSessionTermination: true,
1236 registrations,
1237 }).pipe(Layer.provide(layerMcpAuthMiddleware));
1238​
1239/** Every tool the T3 MCP server advertises. AgentContextBudget.test.ts measures this set. */
1240export const layerTools = Layer.mergeAll(
1241 layerPreviewToolkit,
1242 layerOrchestratorToolkit,
1243 layerThreadToolkit,
1244 layerAttachmentToolkit,
1245 layerProjectRegistration,
1246 layerEnvironmentToolkit,
1247 layerPreviewControlsRegistration,
1248 layerWorktreeToolkitRegistration,
1249 layerPullRequestsToolkit,
1250 layerDeviceToolkit,
1251 layerHtmlToolkit,
1253​
1254export const layer = layerMcpTransport(layerTools);