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

McpHttpServer.ts

1,374 lines53.4 KB

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