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