Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
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 Schema from "effect/Schema";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import type * as Types from "effect/Types";
14import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
15import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
16
17import packageJson from "../../package.json" with { type: "json" };
18import * as ServerConfig from "../config.ts";
19import * as McpInvocationContext from "./McpInvocationContext.ts";
20import * as McpSessionRegistry from "./McpSessionRegistry.ts";
21import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
22import {
23 PreviewSnapshotToolkitHandlersLive,
24 PreviewStandardToolkitHandlersLive,
25} from "./toolkits/preview/handlers.ts";
26import {
27 PreviewSnapshotTool,
28 PreviewSnapshotToolkit,
29 PreviewStandardToolkit,
30} from "./toolkits/preview/tools.ts";
31
32const unauthorized = HttpServerResponse.jsonUnsafe(
33 {
34 error: "invalid_mcp_credential",
35 message: "A valid provider-scoped MCP bearer credential is required.",
36 },
37 {
38 status: 401,
39 headers: {
40 "cache-control": "no-store",
41 "www-authenticate": "Bearer",
42 },
43 },
44);
45
46type AuthenticatedHttpEffect = Effect.Effect<
47 HttpServerResponse.HttpServerResponse,
48 Types.unhandled,
49 McpInvocationContext.McpInvocationContext
50>;
51
52type McpAuthMiddleware = (
53 httpEffect: AuthenticatedHttpEffect,
54) => Effect.Effect<
55 HttpServerResponse.HttpServerResponse,
56 Types.unhandled,
57 HttpServerRequest.HttpServerRequest
58>;
59
60export const normalizeMcpHttpResponse = (
61 response: HttpServerResponse.HttpServerResponse,
62): HttpServerResponse.HttpServerResponse => {
63 const bodyIsEmpty =
64 response.body._tag === "Empty" ||
65 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
66 (response.body._tag === "Raw" && response.body.contentLength === 0);
67 return response.status === 200 && bodyIsEmpty
68 ? HttpServerResponse.setStatus(response, 202)
69 : response;
70};
71
72const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
73 Effect.map((registry): McpAuthMiddleware =>
74 Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
75 const request = yield* HttpServerRequest.HttpServerRequest;
76 const authorization = request.headers.authorization;
77 const token =
78 authorization?.startsWith("Bearer ") === true
79 ? authorization.slice("Bearer ".length).trim()
80 : "";
81 const invocation = yield* registry.resolve(token);
82 if (!invocation) {
83 // Without this the only symptom of a dead credential is the agent
84 // quietly losing the whole `t3-code` toolkit for the rest of its
85 // session, with nothing on the server to explain why.
86 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
87 reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
88 });
89 return unauthorized;
90 }
91 return yield* httpEffect.pipe(
92 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
93 Effect.map(normalizeMcpHttpResponse),
94 );
95 }),
96 ),
97 Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
98);
99
100const McpAuthMiddlewareLive = HttpRouter.middleware<{
101 provides: McpInvocationContext.McpInvocationContext;
102}>()(makeMcpAuthMiddleware).layer;
103
104/**
105 * Claude Code drops every MCP result above 25k tokens (~100 KB of text) and
106 * hands the agent a truncation notice instead, so a snapshot that carries the
107 * full accessibility tree and 20 KB of page text loses its locators too. Keep
108 * the text under that ceiling and tell the agent what was cut.
109 */
110export const MAX_SNAPSHOT_TEXT_BYTES = 60_000;
111const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;
112const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;
113const MAX_SNAPSHOT_LOG_ENTRIES = 40;
114const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500;
115const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048;
116
117const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
118const utf8Length = (text: string) => Buffer.byteLength(text, "utf8");
119const cutText = (text: string, max: number) =>
120 text.length > max ? `${text.slice(0, max)}…` : text;
121
122/** Shortens every string field of a log entry; other fields pass through. */
123const cutEntryStrings = <A>(entry: A): A =>
124 typeof entry === "object" && entry !== null
125 ? (Object.fromEntries(
126 Object.entries(entry).map(([key, value]) => [
127 key,
128 typeof value === "string" ? cutText(value, MAX_SNAPSHOT_LOG_TEXT_CHARS) : value,
129 ]),
130 ) as A)
131 : entry;
132
133const hasLongString = (entry: unknown, max: number) =>
134 typeof entry === "object" &&
135 entry !== null &&
136 Object.values(entry).some((value) => typeof value === "string" && value.length > max);
137
138type SnapshotMetadata = {
139 readonly url: string;
140 readonly title: string;
141 readonly visibleText: string;
142 readonly interactiveElements: ReadonlyArray<{
143 readonly name: string;
144 readonly [key: string]: unknown;
145 }>;
146 readonly consoleEntries: ReadonlyArray<unknown>;
147 readonly networkEntries: ReadonlyArray<unknown>;
148 readonly actionTimeline: ReadonlyArray<unknown>;
149 readonly [key: string]: unknown;
150};
151
152/**
153 * Drops the accessibility tree, shortens page text, element names, identifiers,
154 * and log strings, keeps only the newest log entries, and finally sheds
155 * interactive elements until the JSON fits. Returns the text plus notes on
156 * what is missing so the agent can reach for preview_evaluate.
157 */
158const boundSnapshotMetadata = (
159 metadata: SnapshotMetadata,
160): { readonly text: string; readonly omitted: ReadonlyArray<string> } => {
161 const omitted: Array<string> = [];
162 const { accessibilityTree, ...withoutTree } = metadata;
163 if (accessibilityTree !== undefined) {
164 omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)");
165 }
166 const tail = <A>(entries: ReadonlyArray<A>, label: string) => {
167 if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) {
168 omitted.push(`${entries.length - MAX_SNAPSHOT_LOG_ENTRIES} older ${label}`);
169 }
170 const kept = entries.slice(-MAX_SNAPSHOT_LOG_ENTRIES);
171 if (kept.some((entry) => hasLongString(entry, MAX_SNAPSHOT_LOG_TEXT_CHARS))) {
172 omitted.push(`${label} text after ${MAX_SNAPSHOT_LOG_TEXT_CHARS} characters`);
173 }
174 return kept.map(cutEntryStrings);
175 };
176 if (
177 metadata.url.length > MAX_SNAPSHOT_IDENTIFIER_CHARS ||
178 metadata.title.length > MAX_SNAPSHOT_IDENTIFIER_CHARS
179 ) {
180 omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`);
181 }
182 if (
183 metadata.interactiveElements.some(
184 (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS,
185 )
186 ) {
187 omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`);
188 }
189 if (metadata.visibleText.length > MAX_SNAPSHOT_VISIBLE_TEXT_CHARS) {
190 omitted.push(
191 `visibleText after ${MAX_SNAPSHOT_VISIBLE_TEXT_CHARS} characters (use preview_evaluate for more)`,
192 );
193 }
194 const bounded = {
195 ...withoutTree,
196 url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
197 title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS),
198 visibleText: cutText(metadata.visibleText, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS),
199 interactiveElements: metadata.interactiveElements.map((element) => ({
200 ...element,
201 name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS),
202 })),
203 consoleEntries: tail(metadata.consoleEntries, "console entries"),
204 networkEntries: tail(metadata.networkEntries, "network entries"),
205 actionTimeline: tail(metadata.actionTimeline, "action timeline entries"),
206 };
207
208 // Per-field caps do not sum below the ceiling: three log arrays of 40 capped
209 // entries alone can pass 60 KB. Shed the least useful lists first, halving
210 // one list per round, until the JSON fits. With every list empty the rest
211 // is bounded by the identifier and visibleText caps, so this terminates.
212 const shedOrder = [
213 "actionTimeline",
214 "networkEntries",
215 "consoleEntries",
216 "interactiveElements",
217 ] as const;
218 const lists: Record<(typeof shedOrder)[number], ReadonlyArray<unknown>> = {
219 interactiveElements: bounded.interactiveElements,
220 consoleEntries: bounded.consoleEntries,
221 networkEntries: bounded.networkEntries,
222 actionTimeline: bounded.actionTimeline,
223 };
224 const dropped: Record<(typeof shedOrder)[number], number> = {
225 interactiveElements: 0,
226 consoleEntries: 0,
227 networkEntries: 0,
228 actionTimeline: 0,
229 };
230 let text = encodeJsonText({ ...bounded, ...lists });
231 while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) {
232 // Elements carry the locators, so they go last; logs shed newest-last.
233 const key =
234 shedOrder.find(
235 (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0,
236 ) ?? (lists.interactiveElements.length > 0 ? "interactiveElements" : undefined);
237 if (key === undefined) break;
238 const keep = Math.floor(lists[key].length / 2);
239 dropped[key] += lists[key].length - keep;
240 // slice(-0) keeps everything, so spell out the empty case.
241 lists[key] =
242 keep === 0
243 ? []
244 : key === "interactiveElements"
245 ? lists[key].slice(0, keep)
246 : lists[key].slice(-keep);
247 text = encodeJsonText({ ...bounded, ...lists });
248 }
249 for (const key of shedOrder) {
250 if (dropped[key] > 0) {
251 omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);
252 }
253 }
254 return { text, omitted };
255};
256
257export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(
258 "PreviewScreenshotSaveError",
259 { screenshotPath: Schema.String, cause: Schema.Defect() },
260) {
261 override get message(): string {
262 return `Could not save preview screenshot to ${this.screenshotPath}.`;
263 }
264}
265
266const MAX_SCREENSHOT_SITE_SLUG_LENGTH = 40;
267
268/** Hostname reduced to a filename-safe slug, matching the desktop's own screenshot names. */
269const screenshotSiteSlug = (rawUrl: string): string => {
270 try {
271 const slug = new URL(rawUrl).hostname
272 .toLowerCase()
273 .replace(/[^a-z0-9]+/g, "-")
274 .replace(/^-+|-+$/g, "")
275 .slice(0, MAX_SCREENSHOT_SITE_SLUG_LENGTH)
276 .replace(/-+$/g, "");
277 return slug || "site";
278 } catch {
279 return "site";
280 }
281};
282
283/** Writes the snapshot PNG under the browser artifacts directory and returns its path. */
284const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
285 pageUrl: string,
286 data: Uint8Array,
287) {
288 const config = yield* ServerConfig.ServerConfig;
289 const fileSystem = yield* FileSystem.FileSystem;
290 const path = yield* Path.Path;
291 const millis = yield* Clock.currentTimeMillis;
292 // Two saves in the same millisecond must not overwrite each other.
293 const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
294 const screenshotPath = path.join(config.browserArtifactsDir, fileName);
295 yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
296 Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
297 Effect.mapError((cause) => new PreviewScreenshotSaveError({ screenshotPath, cause })),
298 );
299 return screenshotPath;
300});
301
302const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
303 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
304 return Effect.failCause(cause).pipe(Effect.orDie);
305 }
306 const failures = cause.reasons.filter(Cause.isFailReason);
307 const firstFailure = failures[0]?.error;
308 const errorTag =
309 typeof firstFailure === "object" &&
310 firstFailure !== null &&
311 "_tag" in firstFailure &&
312 typeof firstFailure._tag === "string"
313 ? firstFailure._tag
314 : "PreviewSnapshotError";
315 const result = new McpSchema.CallToolResult({
316 isError: true,
317 structuredContent: {
318 error: {
319 _tag: errorTag,
320 operation: "snapshot",
321 failureCount: failures.length,
322 },
323 },
324 // Agents usually see only the text content, so name the tag there too.
325 content: [{ type: "text", text: `Preview snapshot failed: ${errorTag}.` }],
326 });
327 return Effect.logWarning("preview snapshot failed", {
328 operation: "snapshot",
329 errorTag,
330 failureCount: failures.length,
331 }).pipe(Effect.as(result));
332};
333
334const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
335 const server = yield* McpServer.McpServer;
336 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
337 // The MCP tool runner only supplies the client, so hand the save path its services here.
338 const saveServices = yield* Effect.context<
339 ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path
340 >();
341 const built = yield* PreviewSnapshotToolkit;
342 const tool = PreviewSnapshotTool;
343 yield* server.addTool({
344 tool: new McpSchema.Tool({
345 name: tool.name,
346 description: Tool.getDescription(tool),
347 inputSchema: Tool.getJsonSchema(tool),
348 annotations: {
349 ...Context.getOption(tool.annotations, Tool.Title).pipe(
350 Option.map((title) => ({ title })),
351 Option.getOrUndefined,
352 ),
353 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
354 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
355 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
356 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
357 },
358 }),
359 annotations: tool.annotations,
360 handle: (payload) =>
361 Effect.withFiber((fiber) => {
362 const invocation = Context.getUnsafe(
363 fiber.context,
364 McpInvocationContext.McpInvocationContext,
365 );
366 return built.handle("preview_snapshot", payload).pipe(
367 Stream.unwrap,
368 Stream.run(Sink.last()),
369 Effect.flatMap(Effect.fromOption),
370 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
371 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
372 Effect.flatMap(({ encodedResult }) =>
373 Effect.gen(function* () {
374 const snapshot = encodedResult as SnapshotMetadata & {
375 readonly url: string;
376 readonly screenshot: {
377 readonly mimeType: "image/png";
378 readonly data: string;
379 readonly width: number;
380 readonly height: number;
381 };
382 };
383 const { screenshot, ...page } = snapshot;
384 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
385 const screenshotPath =
386 payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
387 const metadata = {
388 ...page,
389 screenshot: {
390 mimeType: screenshot.mimeType,
391 width: screenshot.width,
392 height: screenshot.height,
393 },
394 ...(screenshotPath === undefined ? {} : { screenshotPath }),
395 };
396 const bounded = boundSnapshotMetadata(metadata);
397 return new McpSchema.CallToolResult({
398 isError: false,
399 structuredContent: metadata,
400 content: [
401 { type: "text", text: bounded.text },
402 ...(bounded.omitted.length === 0
403 ? []
404 : [
405 {
406 type: "text" as const,
407 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
408 },
409 ]),
410 ...(payload?.includeImage === false
411 ? []
412 : [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]),
413 ],
414 });
415 }),
416 ),
417 Effect.provide(saveServices),
418 Effect.matchCauseEffect({
419 onFailure: previewSnapshotFailure,
420 onSuccess: Effect.succeed,
421 }),
422 );
423 }),
424 });
425});
426
427const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
428 Layer.provide(PreviewStandardToolkitHandlersLive),
429);
430
431const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
432 Layer.provide(PreviewSnapshotToolkitHandlersLive),
433);
434
435export const PreviewToolkitRegistrationLive = Layer.mergeAll(
436 PreviewStandardToolkitRegistrationLive,
437 PreviewSnapshotRegistrationLive,
438);
439
440const McpTransportLive = McpServer.layerHttp({
441 name: "T3 Code",
442 version: packageJson.version,
443 path: "/mcp",
444 protocols: [McpProtocol.v2025_06_18],
445}).pipe(Layer.provide(McpAuthMiddlewareLive));
446
447export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));