Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

McpHttpServer.ts

644 lines24.0 KB

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