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 { 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 ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
16import * as McpSessionRegistry from "./McpSessionRegistry.ts";
17import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
18import { OrchestratorToolkitHandlersLive } from "./toolkits/orchestrator/handlers.ts";
19import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
20import {
21 PreviewSnapshotToolkitHandlersLive,
22 PreviewStandardToolkitHandlersLive,
23} from "./toolkits/preview/handlers.ts";
24import {
25 PreviewSnapshotTool,
26 PreviewSnapshotToolkit,
27 PreviewStandardToolkit,
28} from "./toolkits/preview/tools.ts";
29import { WorktreeToolkitHandlersLive } from "./toolkits/worktree/handlers.ts";
30import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
31import * as WorktreeMcpService from "./WorktreeMcpService.ts";
32
33const unauthorized = HttpServerResponse.jsonUnsafe(
34 {
35 error: "invalid_mcp_credential",
36 message: "A valid provider-scoped MCP bearer credential is required.",
37 },
38 {
39 status: 401,
40 headers: {
41 "cache-control": "no-store",
42 "www-authenticate": "Bearer",
43 },
44 },
45);
46
47type AuthenticatedHttpEffect = Effect.Effect<
48 HttpServerResponse.HttpServerResponse,
49 Types.unhandled,
50 McpInvocationContext.McpInvocationContext
51>;
52
53type McpAuthMiddleware = (
54 httpEffect: AuthenticatedHttpEffect,
55) => Effect.Effect<
56 HttpServerResponse.HttpServerResponse,
57 Types.unhandled,
58 HttpServerRequest.HttpServerRequest
59>;
60
61export const normalizeMcpHttpResponse = (
62 response: HttpServerResponse.HttpServerResponse,
63): HttpServerResponse.HttpServerResponse => {
64 const bodyIsEmpty =
65 response.body._tag === "Empty" ||
66 (response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
67 (response.body._tag === "Raw" && response.body.contentLength === 0);
68 return response.status === 200 && bodyIsEmpty
69 ? HttpServerResponse.setStatus(response, 202)
70 : response;
71};
72
73const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
74 Effect.map((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 Layer.provide(ThreadMetadataMcpService.layer),
229);
230
231export const WorktreeToolkitRegistrationLive = McpServer.toolkit(WorktreeToolkit).pipe(
232 Layer.provide(WorktreeToolkitHandlersLive),
233 Layer.provide(WorktreeMcpService.layer),
234);
235
236const McpTransportLive = McpServer.layerHttp({
237 name: "T3 Code",
238 version: packageJson.version,
239 path: "/mcp",
240 protocols: [McpProtocol.v2025_06_18],
241}).pipe(Layer.provide(McpAuthMiddlewareLive));
242
243export const layer = Layer.mergeAll(
244 PreviewToolkitRegistrationLive,
245 OrchestratorToolkitRegistrationLive,
246 WorktreeToolkitRegistrationLive,
247).pipe(Layer.provideMerge(McpTransportLive));