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