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

McpHttpServer.ts

228 lines8.0 KB

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