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

McpHttpServer.ts

225 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 { McpProtocol, 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((registry): McpAuthMiddleware =>
68 Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
69 const request = yield* HttpServerRequest.HttpServerRequest;
70 const authorization = request.headers.authorization;
71 const token =
72 authorization?.startsWith("Bearer ") === true
73 ? authorization.slice("Bearer ".length).trim()
74 : "";
75 const invocation = yield* registry.resolve(token);
76 if (!invocation) {
77 // Without this the only symptom of a dead credential is the agent
78 // quietly losing the whole `t3-code` toolkit for the rest of its
79 // session, with nothing on the server to explain why.
80 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
81 reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
82 });
83 return unauthorized;
84 }
85 return yield* httpEffect.pipe(
86 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
87 Effect.map(normalizeMcpHttpResponse),
88 );
89 }),
90 ),
91 Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
92);
93​
94const McpAuthMiddlewareLive = HttpRouter.middleware<{
95 provides: McpInvocationContext.McpInvocationContext;
96}>()(makeMcpAuthMiddleware).layer;
97​
98const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
99 if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {
100 return Effect.failCause(cause).pipe(Effect.orDie);
101 }
102 const failures = cause.reasons.filter(Cause.isFailReason);
103 const firstFailure = failures[0]?.error;
104 const errorTag =
105 typeof firstFailure === "object" &&
106 firstFailure !== null &&
107 "_tag" in firstFailure &&
108 typeof firstFailure._tag === "string"
109 ? firstFailure._tag
110 : "PreviewSnapshotError";
111 const result = new McpSchema.CallToolResult({
112 isError: true,
113 structuredContent: {
114 error: {
115 _tag: errorTag,
116 operation: "snapshot",
117 failureCount: failures.length,
118 },
119 },
120 content: [{ type: "text", text: "Preview snapshot failed." }],
121 });
122 return Effect.logWarning("preview snapshot failed", {
123 operation: "snapshot",
124 errorTag,
125 failureCount: failures.length,
126 }).pipe(Effect.as(result));
127};
128​
129const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
130 const server = yield* McpServer.McpServer;
131 const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
132 const built = yield* PreviewSnapshotToolkit;
133 const tool = PreviewSnapshotTool;
134 yield* server.addTool({
135 tool: new McpSchema.Tool({
136 name: tool.name,
137 description: Tool.getDescription(tool),
138 inputSchema: Tool.getJsonSchema(tool),
139 annotations: {
140 ...Context.getOption(tool.annotations, Tool.Title).pipe(
141 Option.map((title) => ({ title })),
142 Option.getOrUndefined,
143 ),
144 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
145 destructiveHint: Context.get(tool.annotations, Tool.Destructive),
146 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
147 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
148 },
149 }),
150 annotations: tool.annotations,
151 handle: (payload) =>
152 Effect.withFiber((fiber) => {
153 const invocation = Context.getUnsafe(
154 fiber.context,
155 McpInvocationContext.McpInvocationContext,
156 );
157 return built.handle("preview_snapshot", payload).pipe(
158 Stream.unwrap,
159 Stream.run(Sink.last()),
160 Effect.flatMap(Effect.fromOption),
161 Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
162 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
163 Effect.matchCauseEffect({
164 onFailure: previewSnapshotFailure,
165 onSuccess: ({ encodedResult }) => {
166 const snapshot = encodedResult as {
167 readonly screenshot: {
168 readonly mimeType: "image/png";
169 readonly data: string;
170 readonly width: number;
171 readonly height: number;
172 };
173 readonly [key: string]: unknown;
174 };
175 const { screenshot, ...page } = snapshot;
176 const metadata = {
177 ...page,
178 screenshot: {
179 mimeType: screenshot.mimeType,
180 width: screenshot.width,
181 height: screenshot.height,
182 },
183 };
184 return Effect.succeed(
185 new McpSchema.CallToolResult({
186 isError: false,
187 structuredContent: metadata,
188 content: [
189 { type: "text", text: JSON.stringify(metadata) },
190 {
191 type: "image",
192 data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
193 mimeType: screenshot.mimeType,
194 },
195 ],
196 }),
197 );
198 },
199 }),
200 );
201 }),
202 });
203});
204​
205const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
206 Layer.provide(PreviewStandardToolkitHandlersLive),
207);
208​
209const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
210 Layer.provide(PreviewSnapshotToolkitHandlersLive),
211);
212​
213export const PreviewToolkitRegistrationLive = Layer.mergeAll(
214 PreviewStandardToolkitRegistrationLive,
215 PreviewSnapshotRegistrationLive,
216);
217​
218const McpTransportLive = McpServer.layerHttp({
219 name: "T3 Code",
220 version: packageJson.version,
221 path: "/mcp",
222 protocols: [McpProtocol.v2025_06_18],
223}).pipe(Layer.provide(McpAuthMiddlewareLive));
224​
225export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));