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