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