@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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