(factory: () => McpServer, options: McpTestServerOptions = {})
| 61 | const protectedResourcePath = "/.well-known/oauth-protected-resource"; |
| 62 | |
| 63 | export const serveMcpServer = (factory: () => McpServer, options: McpTestServerOptions = {}) => |
| 64 | Effect.acquireRelease( |
| 65 | Effect.gen(function* () { |
| 66 | const transports = new Map<string, StreamableHTTPServerTransport>(); |
| 67 | const requests = yield* Ref.make<readonly McpTestRequest[]>([]); |
| 68 | const path = options.path ?? "/"; |
| 69 | let sessions = 0; |
| 70 | |
| 71 | const handleMcpRequest = ( |
| 72 | request: http.IncomingMessage, |
| 73 | response: http.ServerResponse, |
| 74 | ): Effect.Effect<void> => |
| 75 | Effect.gen(function* () { |
| 76 | const requestUrl = request.url ?? "/"; |
| 77 | const sessionId = Array.isArray(request.headers["mcp-session-id"]) |
| 78 | ? request.headers["mcp-session-id"][0] |
| 79 | : request.headers["mcp-session-id"]; |
| 80 | const authorization = Array.isArray(request.headers.authorization) |
| 81 | ? request.headers.authorization[0] |
| 82 | : request.headers.authorization; |
| 83 | const origin = request.headers.host |
| 84 | ? `http://${request.headers.host}` |
| 85 | : "http://127.0.0.1"; |
| 86 | |
| 87 | yield* Ref.update(requests, (all) => [ |
| 88 | ...all, |
| 89 | { |
| 90 | method: request.method ?? "GET", |
| 91 | url: requestUrl, |
| 92 | authorization, |
| 93 | sessionId, |
| 94 | }, |
| 95 | ]); |
| 96 | |
| 97 | if ( |
| 98 | options.auth?.authorizationServerUrls && |
| 99 | requestUrl.startsWith(protectedResourcePath) |
| 100 | ) { |
| 101 | const resourcePath = requestUrl.slice(protectedResourcePath.length); |
| 102 | writeJson(response, 200, { |
| 103 | resource: `${origin}${resourcePath}`, |
| 104 | authorization_servers: options.auth.authorizationServerUrls, |
| 105 | bearer_methods_supported: ["header"], |
| 106 | scopes_supported: options.auth.scopes ?? ["read"], |
| 107 | }); |
| 108 | return; |
| 109 | } |
| 110 | |
| 111 | if (!isMcpPath(requestUrl, path)) { |
| 112 | writeJson(response, 404, { error: "not_found" }); |
| 113 | return; |
| 114 | } |
| 115 | |
| 116 | if (options.auth) { |
| 117 | const accepted = yield* options.auth.validateAuthorization(authorization); |
| 118 | if (!accepted) { |
| 119 | writeJson( |
| 120 | response, |
no test coverage detected