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