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