MCPcopy Create free account
hub / github.com/UsefulSoftwareCo/executor / serveMcpServer

Function serveMcpServer

packages/plugins/mcp/src/testing/server.ts:95–340  ·  view source on GitHub ↗
(factory: () => McpServer, options: McpTestServerOptions = {})

Source from the content-addressed store, hash-verified

93const protectedResourcePath = "/.well-known/oauth-protected-resource";
94
95export const serveMcpServer = (factory: () => McpServer, options: McpTestServerOptions = {}) =>
96 Effect.acquireRelease(
97 Effect.gen(function* () {
98 const transports = new Map<string, StreamableHTTPServerTransport>();
99 const allTransports = new Set<StreamableHTTPServerTransport>();
100 const requests = yield* Ref.make<readonly McpTestRequest[]>([]);
101 const path = options.path ?? "/";
102 let sessions = 0;
103 let nextSessionRequestStatus: number | undefined;
104 let sessionMethodRejection: { readonly method: string; readonly status: number } | undefined;
105
106 const writeUnauthorized = (response: http.ServerResponse, origin: string) =>
107 writeJson(
108 response,
109 401,
110 { error: "invalid_token" },
111 {
112 "www-authenticate":
113 options.auth?.wwwAuthenticate ??
114 `Bearer resource_metadata="${origin}${protectedResourcePath}${path}", error="invalid_token"`,
115 },
116 );
117
118 const namesJsonRpcMethod = (parsedBody: unknown, method: string): boolean => {
119 const messages = Array.isArray(parsedBody) ? parsedBody : [parsedBody];
120 return messages.some(
121 (message) =>
122 typeof message === "object" &&
123 message !== null &&
124 (message as { readonly method?: unknown }).method === method,
125 );
126 };
127
128 const handleMcpRequest = (
129 request: http.IncomingMessage,
130 response: http.ServerResponse,
131 ): Effect.Effect<void> =>
132 Effect.gen(function* () {
133 const requestUrl = request.url ?? "/";
134 const sessionId = Array.isArray(request.headers["mcp-session-id"])
135 ? request.headers["mcp-session-id"][0]
136 : request.headers["mcp-session-id"];
137 const authorization = Array.isArray(request.headers.authorization)
138 ? request.headers.authorization[0]
139 : request.headers.authorization;
140 const origin = request.headers.host
141 ? `http://${request.headers.host}`
142 : "http://127.0.0.1";
143
144 yield* Ref.update(requests, (all) => [
145 ...all,
146 {
147 method: request.method ?? "GET",
148 url: requestUrl,
149 authorization,
150 sessionId,
151 },
152 ]);

Calls 10

handleMcpRequestFunction · 0.85
resumeFunction · 0.85
listenMethod · 0.80
addressMethod · 0.80
toStringMethod · 0.80
clearMethod · 0.80
getMethod · 0.65
setMethod · 0.65
syncMethod · 0.65
closeMethod · 0.65

Tested by 1

serveTokenGatedMcpServerFunction · 0.72