Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import type * as Types from "effect/Types";
9import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
10import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
11
12import packageJson from "../../package.json" with { type: "json" };
13import * as McpInvocationContext from "./McpInvocationContext.ts";
14import * as McpSessionRegistry from "./McpSessionRegistry.ts";
15import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
16import {
17 PreviewSnapshotToolkitHandlersLive,
18 PreviewStandardToolkitHandlersLive,
19} from "./toolkits/preview/handlers.ts";
20import {
21 PreviewSnapshotTool,
22 PreviewSnapshotToolkit,
23 PreviewStandardToolkit,
24} from "./toolkits/preview/tools.ts";
25
26const unauthorized = HttpServerResponse.jsonUnsafe(
27 {
28 error: "invalid_mcp_credential",
29 message: "A valid provider-scoped MCP bearer credential is required.",
30 },
31 {
32 status: 401,
33 headers: {
34 "cache-control": "no-store",
35 "www-authenticate": "Bearer",
36 },
37 },
38);
39
40type AuthenticatedHttpEffect = Effect.Effect<
41 HttpServerResponse.HttpServerResponse,
42 Types.unhandled,
43 McpInvocationContext.McpInvocationContext
44>;
45
46type McpAuthMiddleware = (
47 httpEffect: AuthenticatedHttpEffect,
48) => Effect.Effect<
49 HttpServerResponse.HttpServerResponse,
50 Types.unhandled,
51 HttpServerRequest.HttpServerRequest
52>;
53
54export const normalizeMcpHttpResponse = (
55 response: HttpServerResponse.HttpServerResponse,
56): HttpServerResponse.HttpServerResponse => {
57 const bodyIsEmpty =
58 response.body._tag === "Empty" ||
59 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
60 (response.body._tag === "Raw" && response.body.contentLength === 0);
61 return response.status === 200 && bodyIsEmpty
62 ? HttpServerResponse.setStatus(response, 202)
63 : response;
64};
65
66const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
67 Effect.map(
68 (registry): McpAuthMiddleware =>
69 Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
70 const request = yield* HttpServerRequest.HttpServerRequest;
71 const authorization = request.headers.authorization;
72 const token =
73 authorization?.startsWith("Bearer ") === true
74 ? authorization.slice("Bearer ".length).trim()
75 : "";
76 const invocation = yield* registry.resolve(token);
77 if (!invocation) return unauthorized;
78 return yield* httpEffect.pipe(
79 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
80 Effect.map(normalizeMcpHttpResponse),
81 );
82 }),
83 ),
84 Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
85);
86
87const McpAuthMiddlewareLive = HttpRouter.middleware<{
88 provides: McpInvocationContext.McpInvocationContext;
89}>()(makeMcpAuthMiddleware).layer;
90
91const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
92 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
93 return Effect.failCause(cause).pipe(Effect.orDie);
94 }
95 const failures = cause.reasons.filter(Cause.isFailReason);
96 const firstFailure = failures[0]?.error;
97 const errorTag =
98 typeof firstFailure === "object" &&
99 firstFailure !== null &&
100 "_tag" in firstFailure &&
101 typeof firstFailure._tag === "string"
102 ? firstFailure._tag
103 : "PreviewSnapshotError";
104 const result = new McpSchema.CallToolResult({
105 isError: true,
106 structuredContent: {
107 error: {
108 _tag: errorTag,
109 operation: "snapshot",
110 failureCount: failures.length,
111 },
112 },
113 content: [{ type: "text", text: "Preview snapshot failed." }],
114 });
115 return Effect.logWarning("preview snapshot failed", {
116 operation: "snapshot",
117 errorTag,
118 failureCount: failures.length,
119 }).pipe(Effect.as(result));
120};
121
122const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
123 const server = yield* McpServer.McpServer;
124 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
125 const built = yield* PreviewSnapshotToolkit;
126 const tool = PreviewSnapshotTool;
127 yield* server.addTool({
128 tool: new McpSchema.Tool({
129 name: tool.name,
130 description: Tool.getDescription(tool),
131 inputSchema: Tool.getJsonSchema(tool),
132 annotations: {
133 ...Context.getOption(tool.annotations, Tool.Title).pipe(
134 Option.map((title) => ({ title })),
135 Option.getOrUndefined,
136 ),
137 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
138 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
139 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
140 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
141 },
142 }),
143 annotations: tool.annotations,
144 handle: (payload) =>
145 Effect.withFiber((fiber) => {
146 const invocation = Context.getUnsafe(
147 fiber.context,
148 McpInvocationContext.McpInvocationContext,
149 );
150 return built.handle("preview_snapshot", payload).pipe(
151 Stream.unwrap,
152 Stream.run(Sink.last()),
153 Effect.flatMap(Effect.fromOption),
154 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
155 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
156 Effect.matchCauseEffect({
157 onFailure: previewSnapshotFailure,
158 onSuccess: ({ encodedResult }) => {
159 const snapshot = encodedResult as {
160 readonly screenshot: {
161 readonly mimeType: "image/png";
162 readonly data: string;
163 readonly width: number;
164 readonly height: number;
165 };
166 readonly [key: string]: unknown;
167 };
168 const { screenshot, ...page } = snapshot;
169 const metadata = {
170 ...page,
171 screenshot: {
172 mimeType: screenshot.mimeType,
173 width: screenshot.width,
174 height: screenshot.height,
175 },
176 };
177 return Effect.succeed(
178 new McpSchema.CallToolResult({
179 isError: false,
180 structuredContent: metadata,
181 content: [
182 { type: "text", text: JSON.stringify(metadata) },
183 {
184 type: "image",
185 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
186 mimeType: screenshot.mimeType,
187 },
188 ],
189 }),
190 );
191 },
192 }),
193 );
194 }),
195 });
196});
197
198const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
199 Layer.provide(PreviewStandardToolkitHandlersLive),
200);
201
202const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
203 Layer.provide(PreviewSnapshotToolkitHandlersLive),
204);
205
206export const PreviewToolkitRegistrationLive = Layer.mergeAll(
207 PreviewStandardToolkitRegistrationLive,
208 PreviewSnapshotRegistrationLive,
209);
210
211const McpTransportLive = McpServer.layerHttp({
212 name: "V12",
213 version: packageJson.version,
214 path: "/mcp",
215}).pipe(Layer.provide(McpAuthMiddlewareLive));
216
217export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));