(factory: () => McpServer, options: McpTestServerOptions = {})
| 82 | const protectedResourcePath = "/.well-known/oauth-protected-resource"; |
| 83 | |
| 84 | export const serveMcpServer = (factory: () => McpServer, options: McpTestServerOptions = {}) => |
| 85 | Effect.acquireRelease( |
| 86 | Effect.gen(function* () { |
| 87 | const transports = new Map<string, StreamableHTTPServerTransport>(); |
| 88 | const allTransports = new Set<StreamableHTTPServerTransport>(); |
| 89 | const requests = yield* Ref.make<readonly McpTestRequest[]>([]); |
| 90 | const path = options.path ?? "/"; |
| 91 | let sessions = 0; |
| 92 | let nextSessionRequestStatus: number | undefined; |
| 93 | |
| 94 | const handleMcpRequest = ( |
| 95 | request: http.IncomingMessage, |
| 96 | response: http.ServerResponse, |
| 97 | ): Effect.Effect<void> => |
| 98 | Effect.gen(function* () { |
| 99 | const requestUrl = request.url ?? "/"; |
| 100 | const sessionId = Array.isArray(request.headers["mcp-session-id"]) |
| 101 | ? request.headers["mcp-session-id"][0] |
| 102 | : request.headers["mcp-session-id"]; |
| 103 | const authorization = Array.isArray(request.headers.authorization) |
| 104 | ? request.headers.authorization[0] |
| 105 | : request.headers.authorization; |
| 106 | const origin = request.headers.host |
| 107 | ? `http://${request.headers.host}` |
| 108 | : "http://127.0.0.1"; |
| 109 | |
| 110 | yield* Ref.update(requests, (all) => [ |
| 111 | ...all, |
| 112 | { |
| 113 | method: request.method ?? "GET", |
| 114 | url: requestUrl, |
| 115 | authorization, |
| 116 | sessionId, |
| 117 | }, |
| 118 | ]); |
| 119 | |
| 120 | if ( |
| 121 | options.auth?.authorizationServerUrls && |
| 122 | requestUrl.startsWith(protectedResourcePath) |
| 123 | ) { |
| 124 | const resourcePath = requestUrl.slice(protectedResourcePath.length); |
| 125 | writeJson(response, 200, { |
| 126 | resource: `${origin}${resourcePath}`, |
| 127 | authorization_servers: options.auth.authorizationServerUrls, |
| 128 | bearer_methods_supported: ["header"], |
| 129 | scopes_supported: options.auth.scopes ?? ["read"], |
| 130 | }); |
| 131 | return; |
| 132 | } |
| 133 | |
| 134 | if (!isMcpPath(requestUrl, path)) { |
| 135 | writeJson(response, 404, { error: "not_found" }); |
| 136 | return; |
| 137 | } |
| 138 | |
| 139 | if (options.auth) { |
| 140 | const accepted = yield* options.auth.validateAuthorization(authorization); |
| 141 | if (!accepted) { |
no test coverage detected