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

McpHttpServer.ts

1,440 lines56.7 KB

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