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 DeviceService from "../device/DeviceService.ts";
20import * as McpInvocationContext from "./McpInvocationContext.ts";
21import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
22import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
23import { PreviewControlsHandlersLive } from "./toolkits/previewControls/handlers.ts";
24import { EnvironmentToolkit } from "./toolkits/environment/tools.ts";
25import { EnvironmentHandlersLive } from "./toolkits/environment/handlers.ts";
26import { ProjectToolkit } from "./toolkits/project/tools.ts";
27import { ProjectHandlersLive } from "./toolkits/project/handlers.ts";
28import { AttachmentToolkit } from "./toolkits/attachment/tools.ts";
29import { AttachmentHandlersLive } from "./toolkits/attachment/handlers.ts";
30import { ThreadToolkit } from "./toolkits/thread/tools.ts";
31import { ThreadToolkitHandlersLive } from "./toolkits/thread/handlers.ts";
32import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
33import * as McpSessionRegistry from "./McpSessionRegistry.ts";
34import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
35import { OrchestratorToolkitHandlersLive } from "./toolkits/orchestrator/handlers.ts";
36import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
37import {
38 PreviewSnapshotToolkitHandlersLive,
39 PreviewStandardToolkitHandlersLive,
40} from "./toolkits/preview/handlers.ts";
41import {
42 PreviewSnapshotTool,
43 PreviewSnapshotToolkit,
44 PreviewStandardToolkit,
45} from "./toolkits/preview/tools.ts";
46import { WorktreeToolkitHandlersLive } from "./toolkits/worktree/handlers.ts";
47import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
48import * as WorktreeMcpService from "./WorktreeMcpService.ts";
49import { PullRequestsToolkitHandlersLive } from "./toolkits/pullRequests/handlers.ts";
50import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
51import {
52 DeviceScreenshotToolkitHandlersLive,
53 DeviceStandardToolkitHandlersLive,
54} from "./toolkits/device/handlers.ts";
55import {
56 DeviceScreenshotTool,
57 DeviceScreenshotToolkit,
58 DeviceStandardToolkit,
59} from "./toolkits/device/tools.ts";
60
61const unauthorized = HttpServerResponse.jsonUnsafe(
62 {
63 error: "invalid_mcp_credential",
64 message: "A valid provider-scoped MCP bearer credential is required.",
65 },
66 {
67 status: 401,
68 headers: {
69 "cache-control": "no-store",
70 "www-authenticate": "Bearer",
71 },
72 },
73);
74
75type AuthenticatedHttpEffect = Effect.Effect<
76 HttpServerResponse.HttpServerResponse,
77 Types.unhandled,
78 McpInvocationContext.McpInvocationContext
79>;
80
81type McpAuthMiddleware = (
82 httpEffect: AuthenticatedHttpEffect,
83) => Effect.Effect<
84 HttpServerResponse.HttpServerResponse,
85 Types.unhandled,
86 HttpServerRequest.HttpServerRequest
87>;
88
89export const normalizeMcpHttpResponse = (
90 response: HttpServerResponse.HttpServerResponse,
91): HttpServerResponse.HttpServerResponse => {
92 const bodyIsEmpty =
93 response.body._tag === "Empty" ||
94 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
95 (response.body._tag === "Raw" && response.body.contentLength === 0);
96 return response.status === 200 && bodyIsEmpty
97 ? HttpServerResponse.setStatus(response, 202)
98 : response;
99};
100
101const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
102 Effect.map((registry): McpAuthMiddleware =>
103 Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
104 const request = yield* HttpServerRequest.HttpServerRequest;
105 const authorization = request.headers.authorization;
106 const token =
107 authorization?.startsWith("Bearer ") === true
108 ? authorization.slice("Bearer ".length).trim()
109 : "";
110 const invocation = yield* registry.resolve(token);
111 if (!invocation) {
112 // Without this the only symptom of a dead credential is the agent
113 // quietly losing the whole `t3-code` toolkit for the rest of its
114 // session, with nothing on the server to explain why.
115 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
116 reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
117 });
118 return unauthorized;
119 }
120 return yield* httpEffect.pipe(
121 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
122 Effect.map(normalizeMcpHttpResponse),
123 );
124 }),
125 ),
126 Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
127);
128
129const McpAuthMiddlewareLive = HttpRouter.middleware<{
130 provides: McpInvocationContext.McpInvocationContext;
131}>()(makeMcpAuthMiddleware).layer;
132
133/**
134 * Claude Code drops every MCP result above 25k tokens (~100 KB of text) and
135 * hands the agent a truncation notice instead, so a snapshot that carries the
136 * full accessibility tree and 20 KB of page text loses its locators too. Keep
137 * the text under that ceiling and tell the agent what was cut.
138 */
139export const MAX_SNAPSHOT_TEXT_BYTES = 60_000;
140const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000;
141const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200;
142const MAX_SNAPSHOT_LOG_ENTRIES = 40;
143const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500;
144const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048;
145
146const encodeJsonText = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
147const utf8Length = (text: string) => Buffer.byteLength(text, "utf8");
148const cutText = (text: string, max: number) =>
149 text.length > max ? `${text.slice(0, max)}…` : text;
150
151/** Shortens every string field of a log entry; other fields pass through. */
152const cutEntryStrings = <A>(entry: A): A =>
153 typeof entry === "object" && entry !== null
154 ? (Object.fromEntries(
155 Object.entries(entry).map(([key, value]) => [
156 key,
157 typeof value === "string" ? cutText(value, MAX_SNAPSHOT_LOG_TEXT_CHARS) : value,
158 ]),
159 ) as A)
160 : entry;
161
162const hasLongString = (entry: unknown, max: number) =>
163 typeof entry === "object" &&
164 entry !== null &&
165 Object.values(entry).some((value) => typeof value === "string" && value.length > max);
166
167type SnapshotMetadata = {
168 readonly url: string;
169 readonly title: string;
170 readonly visibleText: string;
171 readonly interactiveElements: ReadonlyArray<{
172 readonly name: string;
173 readonly [key: string]: unknown;
174 }>;
175 readonly consoleEntries: ReadonlyArray<unknown>;
176 readonly networkEntries: ReadonlyArray<unknown>;
177 readonly actionTimeline: ReadonlyArray<unknown>;
178 readonly [key: string]: unknown;
179};
180
181/**
182 * Drops the accessibility tree, shortens page text, element names, identifiers,
183 * and log strings, keeps only the newest log entries, and finally sheds
184 * interactive elements until the JSON fits. Returns the text plus notes on
185 * what is missing so the agent can reach for preview_evaluate.
186 */
187const boundSnapshotMetadata = (
188 metadata: SnapshotMetadata,
189): { readonly text: string; readonly omitted: ReadonlyArray<string> } => {
190 const omitted: Array<string> = [];
191 const { accessibilityTree, ...withoutTree } = metadata;
192 if (accessibilityTree !== undefined) {
193 omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)");
194 }
195 const tail = <A>(entries: ReadonlyArray<A>, label: string) => {
196 if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) {
197 omitted.push(`${entries.length - MAX_SNAPSHOT_LOG_ENTRIES} older ${label}`);
198 }
199 const kept = entries.slice(-MAX_SNAPSHOT_LOG_ENTRIES);
200 if (kept.some((entry) => hasLongString(entry, MAX_SNAPSHOT_LOG_TEXT_CHARS))) {
201 omitted.push(`${label} text after ${MAX_SNAPSHOT_LOG_TEXT_CHARS} characters`);
202 }
203 return kept.map(cutEntryStrings);
204 };
205 if (
206 metadata.url.length > MAX_SNAPSHOT_IDENTIFIER_CHARS ||
207 metadata.title.length > MAX_SNAPSHOT_IDENTIFIER_CHARS
208 ) {
209 omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`);
210 }
211 if (
212 metadata.interactiveElements.some(
213 (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS,
214 )
215 ) {
216 omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`);
217 }
218 if (metadata.visibleText.length > MAX_SNAPSHOT_VISIBLE_TEXT_CHARS) {
219 omitted.push(
220 `visibleText after ${MAX_SNAPSHOT_VISIBLE_TEXT_CHARS} characters (use preview_evaluate for more)`,
221 );
222 }
223 const bounded = {
224 ...withoutTree,
225 url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
226 title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS),
227 visibleText: cutText(metadata.visibleText, MAX_SNAPSHOT_VISIBLE_TEXT_CHARS),
228 interactiveElements: metadata.interactiveElements.map((element) => ({
229 ...element,
230 name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS),
231 })),
232 consoleEntries: tail(metadata.consoleEntries, "console entries"),
233 networkEntries: tail(metadata.networkEntries, "network entries"),
234 actionTimeline: tail(metadata.actionTimeline, "action timeline entries"),
235 };
236
237 // Per-field caps do not sum below the ceiling: three log arrays of 40 capped
238 // entries alone can pass 60 KB. Shed the least useful lists first, halving
239 // one list per round, until the JSON fits. With every list empty the rest
240 // is bounded by the identifier and visibleText caps, so this terminates.
241 const shedOrder = [
242 "actionTimeline",
243 "networkEntries",
244 "consoleEntries",
245 "interactiveElements",
246 ] as const;
247 const lists: Record<(typeof shedOrder)[number], ReadonlyArray<unknown>> = {
248 interactiveElements: bounded.interactiveElements,
249 consoleEntries: bounded.consoleEntries,
250 networkEntries: bounded.networkEntries,
251 actionTimeline: bounded.actionTimeline,
252 };
253 const dropped: Record<(typeof shedOrder)[number], number> = {
254 interactiveElements: 0,
255 consoleEntries: 0,
256 networkEntries: 0,
257 actionTimeline: 0,
258 };
259 let text = encodeJsonText({ ...bounded, ...lists });
260 while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) {
261 // Elements carry the locators, so they go last; logs shed newest-last.
262 const key =
263 shedOrder.find(
264 (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0,
265 ) ?? (lists.interactiveElements.length > 0 ? "interactiveElements" : undefined);
266 if (key === undefined) break;
267 const keep = Math.floor(lists[key].length / 2);
268 dropped[key] += lists[key].length - keep;
269 // slice(-0) keeps everything, so spell out the empty case.
270 lists[key] =
271 keep === 0
272 ? []
273 : key === "interactiveElements"
274 ? lists[key].slice(0, keep)
275 : lists[key].slice(-keep);
276 text = encodeJsonText({ ...bounded, ...lists });
277 }
278 for (const key of shedOrder) {
279 if (dropped[key] > 0) {
280 omitted.push(`${dropped[key]} of ${bounded[key].length} ${key}`);
281 }
282 }
283 return { text, omitted };
284};
285
286export class PreviewScreenshotSaveError extends Schema.TaggedError<PreviewScreenshotSaveError>()(
287 "PreviewScreenshotSaveError",
288 { screenshotPath: Schema.String, cause: Schema.Defect() },
289) {
290 override get message(): string {
291 return `Could not save preview screenshot to ${this.screenshotPath}.`;
292 }
293}
294
295const MAX_SCREENSHOT_SITE_SLUG_LENGTH = 40;
296
297/** Hostname reduced to a filename-safe slug, matching the desktop's own screenshot names. */
298const screenshotSiteSlug = (rawUrl: string): string => {
299 try {
300 const slug = new URL(rawUrl).hostname
301 .toLowerCase()
302 .replace(/[^a-z0-9]+/g, "-")
303 .replace(/^-+|-+$/g, "")
304 .slice(0, MAX_SCREENSHOT_SITE_SLUG_LENGTH)
305 .replace(/-+$/g, "");
306 return slug || "site";
307 } catch {
308 return "site";
309 }
310};
311
312/** Writes the snapshot PNG under the browser artifacts directory and returns its path. */
313const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* (
314 pageUrl: string,
315 data: Uint8Array,
316) {
317 const config = yield* ServerConfig.ServerConfig;
318 const fileSystem = yield* FileSystem.FileSystem;
319 const path = yield* Path.Path;
320 const millis = yield* Clock.currentTimeMillis;
321 // Two saves in the same millisecond must not overwrite each other.
322 const fileName = `browser-screenshot-${screenshotSiteSlug(pageUrl)}-${millis.toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
323 const screenshotPath = path.join(config.browserArtifactsDir, fileName);
324 yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true }).pipe(
325 Effect.andThen(fileSystem.writeFile(screenshotPath, data)),
326 Effect.mapError((cause) => new PreviewScreenshotSaveError({ screenshotPath, cause })),
327 );
328 return screenshotPath;
329});
330
331const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
332 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
333 return Effect.failCause(cause).pipe(Effect.orDie);
334 }
335 const failures = cause.reasons.filter(Cause.isFailReason);
336 const firstFailure = failures[0]?.error;
337 const errorTag =
338 typeof firstFailure === "object" &&
339 firstFailure !== null &&
340 "_tag" in firstFailure &&
341 typeof firstFailure._tag === "string"
342 ? firstFailure._tag
343 : "PreviewSnapshotError";
344 const result = new McpSchema.CallToolResult({
345 isError: true,
346 structuredContent: {
347 error: {
348 _tag: errorTag,
349 operation: "snapshot",
350 failureCount: failures.length,
351 },
352 },
353 // Agents usually see only the text content, so name the tag there too.
354 content: [{ type: "text", text: `Preview snapshot failed: ${errorTag}.` }],
355 });
356 return Effect.logWarning("preview snapshot failed", {
357 operation: "snapshot",
358 errorTag,
359 failureCount: failures.length,
360 }).pipe(Effect.as(result));
361};
362
363const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
364 const server = yield* McpServer.McpServer;
365 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
366 // The MCP tool runner only supplies the client, so hand the save path its services here.
367 const saveServices = yield* Effect.context<
368 ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path
369 >();
370 const built = yield* PreviewSnapshotToolkit;
371 const tool = PreviewSnapshotTool;
372 yield* server.addTool({
373 tool: new McpSchema.Tool({
374 name: tool.name,
375 description: Tool.getDescription(tool),
376 inputSchema: Tool.getJsonSchema(tool),
377 annotations: {
378 ...Context.getOption(tool.annotations, Tool.Title).pipe(
379 Option.map((title) => ({ title })),
380 Option.getOrUndefined,
381 ),
382 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
383 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
384 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
385 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
386 },
387 }),
388 annotations: tool.annotations,
389 handle: (payload) =>
390 Effect.withFiber((fiber) => {
391 const invocation = Context.getUnsafe(
392 fiber.context,
393 McpInvocationContext.McpInvocationContext,
394 );
395 return built.handle("preview_snapshot", payload).pipe(
396 Stream.unwrap,
397 Stream.run(Sink.last()),
398 Effect.flatMap(Effect.fromOption),
399 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
400 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
401 Effect.flatMap(({ encodedResult }) =>
402 Effect.gen(function* () {
403 const snapshot = encodedResult as SnapshotMetadata & {
404 readonly url: string;
405 readonly screenshot: {
406 readonly mimeType: "image/png";
407 readonly data: string;
408 readonly width: number;
409 readonly height: number;
410 };
411 };
412 const { screenshot, ...page } = snapshot;
413 const png = new Uint8Array(Buffer.from(screenshot.data, "base64"));
414 const screenshotPath =
415 payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined;
416 const metadata = {
417 ...page,
418 screenshot: {
419 mimeType: screenshot.mimeType,
420 width: screenshot.width,
421 height: screenshot.height,
422 },
423 ...(screenshotPath === undefined ? {} : { screenshotPath }),
424 };
425 const bounded = boundSnapshotMetadata(metadata);
426 return new McpSchema.CallToolResult({
427 isError: false,
428 structuredContent: metadata,
429 content: [
430 // Keep the page identity readable even if a provider truncates the snapshot.
431 {
432 type: "text",
433 text: encodeJsonText({
434 url: cutText(snapshot.url, MAX_SNAPSHOT_IDENTIFIER_CHARS),
435 }),
436 },
437 { type: "text", text: bounded.text },
438 ...(bounded.omitted.length === 0
439 ? []
440 : [
441 {
442 type: "text" as const,
443 text: `Snapshot text was bounded. Omitted: ${bounded.omitted.join("; ")}.`,
444 },
445 ]),
446 ...(payload?.includeImage === false
447 ? []
448 : [{ type: "image" as const, data: png, mimeType: screenshot.mimeType }]),
449 ],
450 });
451 }),
452 ),
453 Effect.provide(saveServices),
454 Effect.matchCauseEffect({
455 onFailure: previewSnapshotFailure,
456 onSuccess: Effect.succeed,
457 }),
458 );
459 }),
460 });
461});
462
463interface ImageToolResult {
464 readonly screenshot: {
465 readonly mimeType: "image/png";
466 readonly data: string;
467 readonly width: number;
468 readonly height: number;
469 };
470 readonly [key: string]: unknown;
471}
472
473/**
474 * Failures surface only their tag: the remote message may carry renderer or
475 * device output the agent should not see, and the tag is what it can act on.
476 */
477const imageToolFailure =
478 (toolName: string, operation: string, failureText: string) =>
479 <E>(cause: Cause.Cause<E>) => {
480 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
481 return Effect.failCause(cause).pipe(Effect.orDie);
482 }
483 const failures = cause.reasons.filter(Cause.isFailReason);
484 const firstFailure = failures[0]?.error;
485 const errorTag =
486 typeof firstFailure === "object" &&
487 firstFailure !== null &&
488 "_tag" in firstFailure &&
489 typeof firstFailure._tag === "string"
490 ? firstFailure._tag
491 : `${toolName}Error`;
492 const result = new McpSchema.CallToolResult({
493 isError: true,
494 structuredContent: {
495 error: {
496 _tag: errorTag,
497 operation,
498 failureCount: failures.length,
499 },
500 },
501 content: [{ type: "text", text: failureText }],
502 });
503 return Effect.logWarning(`${toolName} failed`, {
504 operation,
505 errorTag,
506 failureCount: failures.length,
507 }).pipe(Effect.as(result));
508 };
509
510/**
511 * `McpServer.toolkit` serializes every result as JSON text, which is the
512 * wrong shape for a screenshot: the model needs image content. Tools whose
513 * result carries a `screenshot` field are registered by hand so the PNG goes
514 * out as an image block and the rest of the payload as JSON metadata.
515 */
516const registerImageTool = <T extends Tool.Any, E, R>(
517 tool: T,
518 handle: (payload: Tool.Parameters<T>) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
519 provide: (
520 effect: Effect.Effect<{ readonly encodedResult: unknown }, E, R>,
521 ) => Effect.Effect<
522 { readonly encodedResult: unknown },
523 E,
524 McpInvocationContext.McpInvocationContext
525 >,
526 operation: string,
527 failureText: string,
528) =>
529 Effect.gen(function* () {
530 const server = yield* McpServer.McpServer;
531 yield* server.addTool({
532 tool: new McpSchema.Tool({
533 name: tool.name,
534 description: Tool.getDescription(tool),
535 inputSchema: Tool.getJsonSchema(tool),
536 annotations: {
537 ...Context.getOption(tool.annotations, Tool.Title).pipe(
538 Option.map((title) => ({ title })),
539 Option.getOrUndefined,
540 ),
541 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
542 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
543 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
544 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
545 },
546 }),
547 annotations: tool.annotations,
548 handle: (payload) =>
549 Effect.withFiber((fiber) => {
550 const invocation = Context.getUnsafe(
551 fiber.context,
552 McpInvocationContext.McpInvocationContext,
553 );
554 return provide(handle(payload as Tool.Parameters<T>)).pipe(
555 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
556 Effect.matchCauseEffect({
557 onFailure: imageToolFailure(tool.name, operation, failureText),
558 onSuccess: ({ encodedResult }) => {
559 const { screenshot, ...rest } = encodedResult as ImageToolResult;
560 const includeImage =
561 (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !==
562 false;
563 const metadata = {
564 ...rest,
565 screenshot: {
566 mimeType: screenshot.mimeType,
567 width: screenshot.width,
568 height: screenshot.height,
569 },
570 };
571 return Effect.succeed(
572 new McpSchema.CallToolResult({
573 isError: false,
574 structuredContent: metadata,
575 content: [
576 { type: "text", text: JSON.stringify(metadata) },
577 ...(includeImage
578 ? [
579 {
580 type: "image" as const,
581 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
582 mimeType: screenshot.mimeType,
583 },
584 ]
585 : []),
586 ],
587 }),
588 );
589 },
590 }),
591 );
592 }),
593 });
594 });
595
596const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () {
597 const devices = yield* DeviceService.DeviceService;
598 const built = yield* DeviceScreenshotToolkit;
599 yield* registerImageTool(
600 DeviceScreenshotTool,
601 (payload) =>
602 built
603 .handle("device_screenshot", payload)
604 .pipe(Stream.unwrap, Stream.run(Sink.last()), Effect.flatMap(Effect.fromOption)),
605 (effect) => effect.pipe(Effect.provideService(DeviceService.DeviceService, devices)),
606 "screenshot",
607 "Device screenshot failed.",
608 );
609});
610
611const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
612 Layer.provide(PreviewStandardToolkitHandlersLive),
613);
614
615const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
616 Layer.provide(PreviewSnapshotToolkitHandlersLive),
617);
618
619export const PreviewToolkitRegistrationLive = Layer.mergeAll(
620 PreviewStandardToolkitRegistrationLive,
621 PreviewSnapshotRegistrationLive,
622);
623
624export const OrchestratorToolkitRegistrationLive = McpServer.toolkit(OrchestratorToolkit).pipe(
625 Layer.provide(OrchestratorToolkitHandlersLive),
626 Layer.provide(OrchestratorMcpService.layer),
627 Layer.provide(ThreadMetadataMcpService.layer),
628);
629
630export const ThreadToolkitRegistrationLive = McpServer.toolkit(ThreadToolkit).pipe(
631 Layer.provide(ThreadToolkitHandlersLive),
632);
633
634const WorktreeToolkitRegistrationLive = McpServer.toolkit(WorktreeToolkit).pipe(
635 Layer.provide(WorktreeToolkitHandlersLive),
636 Layer.provide(WorktreeMcpService.layer),
637);
638
639const PreviewControlsRegistrationLive = McpServer.toolkit(PreviewControlsToolkit).pipe(
640 Layer.provide(PreviewControlsHandlersLive),
641);
642
643const EnvironmentRegistrationLive = McpServer.toolkit(EnvironmentToolkit).pipe(
644 Layer.provide(EnvironmentHandlersLive),
645);
646
647const ProjectRegistrationLive = McpServer.toolkit(ProjectToolkit).pipe(
648 Layer.provide(ProjectHandlersLive),
649);
650
651const AttachmentRegistrationLive = McpServer.toolkit(AttachmentToolkit).pipe(
652 Layer.provide(AttachmentHandlersLive),
653);
654
655export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequestsToolkit).pipe(
656 Layer.provide(PullRequestsToolkitHandlersLive),
657);
658
659const DeviceStandardToolkitRegistrationLive = McpServer.toolkit(DeviceStandardToolkit).pipe(
660 Layer.provide(DeviceStandardToolkitHandlersLive),
661);
662
663const DeviceScreenshotRegistrationLive = Layer.effectDiscard(registerDeviceScreenshot()).pipe(
664 Layer.provide(DeviceScreenshotToolkitHandlersLive),
665);
666
667export const DeviceToolkitRegistrationLive = Layer.mergeAll(
668 DeviceStandardToolkitRegistrationLive,
669 DeviceScreenshotRegistrationLive,
670);
671
672const McpTransportLive = McpServer.layerHttp({
673 name: "T3 Code",
674 version: packageJson.version,
675 path: "/mcp",
676 protocols: [McpProtocol.v2025_06_18],
677}).pipe(Layer.provide(McpAuthMiddlewareLive));
678
679export const layer = Layer.mergeAll(
680 PreviewToolkitRegistrationLive,
681 OrchestratorToolkitRegistrationLive,
682 ThreadToolkitRegistrationLive,
683 AttachmentRegistrationLive,
684 ProjectRegistrationLive,
685 EnvironmentRegistrationLive,
686 PreviewControlsRegistrationLive,
687 WorktreeToolkitRegistrationLive,
688 PullRequestsToolkitRegistrationLive,
689 DeviceToolkitRegistrationLive,
690).pipe(Layer.provideMerge(McpTransportLive));