(resource: McpResource)
| 214 | |
| 215 | /** Dispatch an MCP request through authenticate -> store.dispatch -> transport. */ |
| 216 | const mcpDispatch = (resource: McpResource) => |
| 217 | Effect.gen(function* () { |
| 218 | const httpRequest = yield* HttpServerRequest.HttpServerRequest; |
| 219 | const auth = yield* McpAuthProvider; |
| 220 | const store = yield* McpSessionStore; |
| 221 | const request = yield* toWebRequest(httpRequest); |
| 222 | |
| 223 | // CORS preflight: answer before auth so unauthenticated clients can probe. |
| 224 | if (request.method === "OPTIONS") { |
| 225 | return fromWebResponse(corsPreflightResponse()); |
| 226 | } |
| 227 | |
| 228 | // Streamable-HTTP only defines GET/POST/DELETE on the endpoint. Any other |
| 229 | // method (PUT/PATCH/…) is rejected with a JSON-RPC 405 BEFORE auth/dispatch — |
| 230 | // otherwise it would fall through and spin up a session engine for a method |
| 231 | // the transport can't serve. |
| 232 | if (!ALLOWED_MCP_METHODS.has(request.method)) { |
| 233 | return fromWebResponse(jsonRpcResponse(405, -32001, "Method not allowed")); |
| 234 | } |
| 235 | |
| 236 | const sessionId = request.headers.get("mcp-session-id"); |
| 237 | |
| 238 | // Authenticate (and, for session-aware providers, authorize) on EVERY |
| 239 | // request. Non-authenticated outcomes render directly. Session teardown is |
| 240 | // only safe after the store can validate the authenticated principal and MCP |
| 241 | // resource; an auth-level Forbidden may not carry either. |
| 242 | const outcome = yield* auth.authenticate(request); |
| 243 | if (!Predicate.isTagged(outcome, "Authenticated")) { |
| 244 | return fromWebResponse(renderAuthError(auth, request, outcome)); |
| 245 | } |
| 246 | const principal = outcome.principal; |
| 247 | |
| 248 | // No session id: per the streamable-HTTP transport contract, only POST opens |
| 249 | // a session. A GET needs an existing id (400); a DELETE on nothing is a |
| 250 | // no-op (204). Both short-circuit BEFORE dispatch so the store never spins up |
| 251 | // an engine for a bare GET/DELETE. |
| 252 | if (!sessionId) { |
| 253 | if (request.method === "GET") { |
| 254 | return fromWebResponse( |
| 255 | jsonRpcResponse(400, -32000, "mcp-session-id header required for SSE"), |
| 256 | ); |
| 257 | } |
| 258 | if (request.method === "DELETE") { |
| 259 | return fromWebResponse( |
| 260 | new Response(null, { status: 204, headers: { "access-control-allow-origin": "*" } }), |
| 261 | ); |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | const result: McpDispatchResult = yield* store.dispatch({ |
| 266 | request, |
| 267 | principal, |
| 268 | resource, |
| 269 | sessionId, |
| 270 | method: request.method, |
| 271 | }); |
| 272 | return fromWebResponse(result instanceof Response ? result : renderDispatchError(result)); |
| 273 | }); |
no test coverage detected