@procedures/mcp-server 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/face.ts CHANGED
@@ -15,6 +15,9 @@
15
15
  * `McpFaceOptions.narrowing`.
16
16
  * - The stop of the intake ends the GET stream of each session without a task in progress
17
17
  * (CLI-72). Then a new session and a new GET stream get 503. A call in progress completes.
18
+ * - The face stays on the listener through the drain (CLI-74): its handler has `until` of a
19
+ * `RequestHandler` of the service, `close transports`. Thus a call in progress gets the answer of
20
+ * an elicitation and its cancel. A new tool call gets `UNAVAILABLE` from the server.
18
21
  * - The types are structural: this package does not depend on `@procedures/peer`.
19
22
  */
20
23
 
@@ -33,6 +36,7 @@ import {
33
36
  type RequestHandler,
34
37
  } from "@procedures/client";
35
38
  import type { McpToolFilter } from "@procedures/mcp";
39
+ import { throughTheDrain } from "./transport/http.js";
36
40
  import { McpServerTransport, httpEndpointOf } from "./transport/mcp-transport.js";
37
41
  import type { McpServerTransportOptions } from "./types.js";
38
42
 
@@ -78,6 +82,10 @@ export interface McpFaceContext {
78
82
 
79
83
  /** The MCP face: its request handler, its stop parts, its endpoint and its transport. */
80
84
  export interface McpFace {
85
+ /**
86
+ * The request handler of the face. It has `until` of a `RequestHandler` of the service: `close
87
+ * transports` (CLI-74). Thus a listener of the service keeps the face through the drain.
88
+ */
81
89
  readonly handler: (req: IncomingMessage, res: ServerResponse) => boolean;
82
90
  readonly parts: {
83
91
  start(): Promise<void>;
@@ -180,7 +188,10 @@ export function mcpFace(options: McpFaceOptions = {}): (context: McpFaceContext)
180
188
  },
181
189
  });
182
190
  return {
183
- handler: (req, res) => transport.handleHttp(req, res),
191
+ // The face stays on the listener through the drain, so a call in progress gets the answer of
192
+ // an elicitation and its cancel (CLI-74). Before, the listener closed at the stop of the intake,
193
+ // and each request got its plain 503. The endpoint refuses new work itself.
194
+ handler: throughTheDrain((req: IncomingMessage, res: ServerResponse) => transport.handleHttp(req, res)),
184
195
  // The tool calls go through the request tracking of the host: the face counts no work of its own.
185
196
  // The stop of the intake ends the GET stream of each session without a task in progress, so the
186
197
  // drain of the listener waits only for the calls and the tasks (CLI-72). Before, each GET stream
package/src/host.ts CHANGED
@@ -46,6 +46,7 @@ import {
46
46
  type Duration,
47
47
  } from "@procedures/client";
48
48
  import { proceduresToMcpTools, type McpTool, type McpToolFilter } from "@procedures/mcp";
49
+ import { throughTheDrain } from "./transport/http.js";
49
50
  import { McpServerTransport, distinctTools, httpEndpointOf, namedTools } from "./transport/mcp-transport.js";
50
51
  import type {
51
52
  HttpTransportOptions,
@@ -234,6 +235,11 @@ export interface McpHost {
234
235
  * This function answers a request of the Streamable HTTP face (`faces.http`) and gives true. It
235
236
  * gives false for another path, or without that face. Mount it on a listener, for example an
236
237
  * `httpTransport` of `@mark1russell7/service/http`.
238
+ *
239
+ * With the face, the function has `until` of a `RequestHandler` of the service: `close transports`
240
+ * (CLI-74). Thus `listener.mount(host.handleHttp)` keeps the face on the listener through the drain,
241
+ * and a call in progress gets the answer of an elicitation and its cancel. A function that wraps
242
+ * `handleHttp` loses `until`: then give `{ until: "close transports" }` to `mount()`.
237
243
  */
238
244
  handleHttp(req: IncomingMessage, res: ServerResponse): boolean;
239
245
  /** The tools of the host at this time, from the registry and the expose rule. */
@@ -421,6 +427,11 @@ export function createMcpHost(options: McpHostOptions = {}): McpHost {
421
427
  }
422
428
  for (const transport of transports) server.addTransport(transport);
423
429
 
430
+ // The face stays on a listener of the service through the drain (CLI-74). Without the face, the
431
+ // handler takes no request, so it does not keep the listener open.
432
+ const answer = (req: IncomingMessage, res: ServerResponse): boolean => httpFace?.handleHttp(req, res) ?? false;
433
+ const handleHttp = httpFace ? throughTheDrain(answer) : answer;
434
+
424
435
  /** This function starts the server and its faces: by `start()`, or by the part of the runner. */
425
436
  const begin = async (): Promise<void> => {
426
437
  if (stopping) throw new Error("This MCP host stopped. A host stops one time: create a new host.");
@@ -473,7 +484,7 @@ export function createMcpHost(options: McpHostOptions = {}): McpHost {
473
484
  if (stdio) svc.trigger("stdin-close");
474
485
  return svc;
475
486
  },
476
- handleHttp: (req, res) => httpFace?.handleHttp(req, res) ?? false,
487
+ handleHttp,
477
488
  tools: () => distinctTools(namedTools(proceduresToMcpTools(registry.getAll(), toolFilter), options.toolName)),
478
489
  state: () => ({ running, faces: transports.map((transport) => transport.getState()) }),
479
490
  };
package/src/tasks.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  * call is a normal request.
9
9
  *
10
10
  * - The store keeps the tasks in memory and binds each task to its session. One store serves each
11
- * session and each face of a host.
11
+ * session and each face of a host. A task without a session (stdio, an SDK transport) is
12
+ * visible only to the requests without a session, not to an HTTP session.
12
13
  * - A slot of the limit (`maxRunning`) stays taken until the work of the task ends, not until its
13
14
  * status ends: a cancelled task holds its slot until its procedure returns. A task above the
14
15
  * limit is created, and then fails at once with the reason: the client gets a task, and reads
@@ -222,10 +223,14 @@ export class McpTaskStore implements TaskStore {
222
223
  }
223
224
  }
224
225
 
225
- /** The entry of a task, when the session may see it: a task of another session is not found. */
226
+ /**
227
+ * The entry of a task, when the session may see it: a task of another session is not found. A
228
+ * task without a session (stdio, an SDK transport) is visible only to a request without a
229
+ * session, and a request without a session does not see the tasks of the HTTP sessions.
230
+ */
226
231
  private lookup(taskId: string, sessionId: string | undefined): Entry | undefined {
227
232
  const entry = this.entries.get(taskId);
228
- if (entry && sessionId !== undefined && entry.sessionId !== undefined && entry.sessionId !== sessionId) return undefined;
233
+ if (entry && entry.sessionId !== sessionId) return undefined;
229
234
  return entry;
230
235
  }
231
236
 
@@ -24,6 +24,11 @@
24
24
  * The browser checks of each request are in `guard.ts` (CLI-35). Only an `initialize` request starts a
25
25
  * session, and each body has a limit. The endpoint keeps at most `maxSessions` sessions: 256 by
26
26
  * default (CLI-51), or no limit with `Infinity`.
27
+ *
28
+ * The endpoint stays on its listener through the drain (CLI-74). Its handler has `until` of a
29
+ * `RequestHandler` of the service: `close transports`. Thus a call in progress gets the answer of an
30
+ * elicitation and its cancel. The endpoint refuses new work itself, after the stop of its intake. The
31
+ * SSE stream of a POST ends when each request of the POST has its answer or is cancelled.
27
32
  */
28
33
 
29
34
  import { randomUUID } from "node:crypto";
@@ -117,6 +122,105 @@ function isLimit(value: number): boolean {
117
122
  return value === Number.POSITIVE_INFINITY || (Number.isInteger(value) && value >= 1);
118
123
  }
119
124
 
125
+ /**
126
+ * The stage of the shutdown at which a mount of the endpoint stops: the close of the transports
127
+ * (CLI-74). A listener of the service reads it as `until` of a `RequestHandler`. Thus the listener
128
+ * stays open through the drain, and a call in progress gets the answer of an elicitation and its
129
+ * cancel. The endpoint refuses new work itself after the stop of its intake.
130
+ */
131
+ export const MCP_MOUNT_STAGE = "close transports";
132
+
133
+ /**
134
+ * This function gives the handler of an endpoint with the stage of its mount: `until` of a
135
+ * `RequestHandler` of `@mark1russell7/service/http` (CLI-74). A function that wraps the handler
136
+ * loses the stage.
137
+ */
138
+ export function throughTheDrain<H extends (req: IncomingMessage, res: ServerResponse) => boolean>(handler: H): H & { readonly until: typeof MCP_MOUNT_STAGE } {
139
+ return Object.assign(handler, { until: MCP_MOUNT_STAGE } as const);
140
+ }
141
+
142
+ /** The id of a JSON-RPC request. */
143
+ type RequestId = string | number;
144
+
145
+ /** A JSON-RPC message, as far as the endpoint reads it. */
146
+ interface MessageFields {
147
+ readonly id?: unknown;
148
+ readonly method?: unknown;
149
+ readonly params?: { readonly requestId?: unknown } | undefined;
150
+ }
151
+
152
+ /** The fields of a JSON-RPC message that the endpoint reads. */
153
+ function fieldsOf(message: unknown): MessageFields {
154
+ return typeof message === "object" && message !== null ? (message as MessageFields) : {};
155
+ }
156
+
157
+ /** The id of a JSON-RPC message, when it is a string or a number. */
158
+ function idOf(value: unknown): RequestId | undefined {
159
+ return typeof value === "string" || typeof value === "number" ? value : undefined;
160
+ }
161
+
162
+ /** The requests of one POST of a session: the requests without an answer, and the cancelled requests. */
163
+ interface PostRequests {
164
+ readonly open: Set<RequestId>;
165
+ readonly cancelled: RequestId[];
166
+ }
167
+
168
+ /**
169
+ * This function makes a session end the SSE stream of a POST when each request of the POST has its
170
+ * answer or is cancelled (CLI-74). The SDK sends no answer to a request that the client cancels with
171
+ * `notifications/cancelled`. Thus the SDK kept the stream of that POST open until the close of the
172
+ * session, and the drain of a listener waited for that stream until its deadline.
173
+ *
174
+ * - The SDK gives one `requestInfo` to each message of one POST. The function groups the requests by it.
175
+ * - The function reads a cancel one turn of the event loop later, after the SDK aborted the call.
176
+ * - The function ends the stream with `closeSSEStream()` of the SDK. A batch POST keeps its stream
177
+ * until each other request of the batch has its answer.
178
+ */
179
+ function endCancelledStreams(transport: StreamableHTTPServerTransport): void {
180
+ const posts = new WeakMap<object, PostRequests>();
181
+ const postOf = new Map<RequestId, PostRequests>();
182
+ // A request leaves its POST at its answer or at its cancel. The stream ends when no request of
183
+ // the POST waits for an answer, and one of them was cancelled.
184
+ const settle = (id: RequestId, cancelled: boolean): void => {
185
+ const post = postOf.get(id);
186
+ if (post === undefined) return;
187
+ postOf.delete(id);
188
+ post.open.delete(id);
189
+ if (cancelled) post.cancelled.push(id);
190
+ const first = post.cancelled[0];
191
+ // The floor of the SDK has closeSSEStream(). The check keeps an older SDK from an uncaught error.
192
+ if (post.open.size === 0 && first !== undefined && typeof transport.closeSSEStream === "function") transport.closeSSEStream(first);
193
+ };
194
+ // The Protocol of the SDK keeps a handler that the transport has before connect(), and calls it first
195
+ transport.onmessage = (message, extra) => {
196
+ const { id, method, params } = fieldsOf(message);
197
+ if (typeof method !== "string") return;
198
+ const requestId = idOf(id);
199
+ if (requestId !== undefined) {
200
+ const key: object = extra?.requestInfo ?? {};
201
+ const post: PostRequests = posts.get(key) ?? { open: new Set<RequestId>(), cancelled: [] };
202
+ posts.set(key, post);
203
+ post.open.add(requestId);
204
+ postOf.set(requestId, post);
205
+ return;
206
+ }
207
+ const cancelled = method === "notifications/cancelled" ? idOf(params?.requestId) : undefined;
208
+ // The SDK aborts the call in a later microtask: the stream ends after it
209
+ if (cancelled !== undefined) setImmediate(() => settle(cancelled, true));
210
+ };
211
+ const send = transport.send.bind(transport);
212
+ transport.send = async (message, options) => {
213
+ try {
214
+ await send(message, options);
215
+ } finally {
216
+ // An answer of the server to a request of the client: a response has an id and no method
217
+ const { id, method } = fieldsOf(message);
218
+ const answered = method === undefined ? idOf(id) : undefined;
219
+ if (answered !== undefined) settle(answered, false);
220
+ }
221
+ };
222
+ }
223
+
120
224
  /**
121
225
  * This function makes the Streamable HTTP endpoint of an MCP server. `connect` connects the
122
226
  * transport of a new session to an MCP server of its own.
@@ -248,6 +352,8 @@ export function createHttpTransport(
248
352
  created.onclose = () => {
249
353
  if (created.sessionId) forget(created.sessionId);
250
354
  };
355
+ // The stream of a cancelled call ends, so it does not hold the drain of the listener (CLI-74)
356
+ endCancelledStreams(created);
251
357
  await connect(created);
252
358
  await created.handleRequest(req, res, body);
253
359
  } finally {