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