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

McpHttpServer.ts

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