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

McpHttpServer.ts

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