@procedures/mcp-server 0.22.0 → 0.23.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/tasks.ts CHANGED
@@ -16,12 +16,13 @@
16
16
  * task, and the request gets the error `-32600` with the code `TASKS_FULL`.
17
17
  * - The time to keep a task (`ttl`) starts when the task ends. The store never removes a task
18
18
  * whose work runs, so a short `ttl` does not let work escape the limit or the cancel. A refused
19
- * task stays 1 minute.
19
+ * task stays 1 minute. The timers run on the clock of the store (`clock`).
20
20
  * - Each session keeps at most 100 tasks, and the store keeps at most `maxStored` tasks for all
21
21
  * the sessions together: 1000 by default (CLI-51). A new task removes the oldest task of its
22
22
  * own session that ended. When the store is full and the session has no task that ended, the
23
23
  * request of the new task gets an error, and the store keeps nothing of it. Thus a client
24
24
  * cannot remove the results of another session. `Infinity` turns the total limit off.
25
+ * - The fair share (CLI-69) keeps one client from the whole store. Refer to `McpTaskStore`.
25
26
  * - A cancel of a task (`tasks/cancel`) aborts the signal of its procedure call. The close of a
26
27
  * session cancels its tasks, and the stop of the host cancels each task.
27
28
  *
@@ -31,7 +32,7 @@
31
32
  import { randomUUID } from "node:crypto";
32
33
  import type { CreateTaskOptions, TaskStore } from "@modelcontextprotocol/sdk/experimental/tasks/interfaces.js";
33
34
  import { ErrorCode, McpError, type Request, type RequestId, type Result, type Task } from "@modelcontextprotocol/sdk/types.js";
34
- import { optionalMs, type Duration } from "@procedures/client";
35
+ import { optionalMs, realClock, type Cancel, type Clock, type Duration, type Principal } from "@procedures/client";
35
36
 
36
37
  /** The limits of the tasks of one MCP host. */
37
38
  export const MCP_TASK_LIMITS = {
@@ -56,6 +57,11 @@ export const MCP_TASK_LIMITS = {
56
57
  * their most tasks. Without it, only the session limit times 100 bounds the store.
57
58
  */
58
59
  maxStored: 1_000,
60
+ /**
61
+ * The part of `maxStored` that the fair share keeps for the clients below their share (CLI-69):
62
+ * a tenth, rounded down. Thus the default `reserve` is 100 slots of 1000.
63
+ */
64
+ reserveDivisor: 10,
59
65
  } as const;
60
66
 
61
67
  /** A task whose work did not end, as a status page of the host shows it. */
@@ -72,6 +78,34 @@ export interface McpTaskInfo {
72
78
  readonly updatedAt: string;
73
79
  }
74
80
 
81
+ /** What the key of the fair share reads to find the client of a new task (CLI-69). */
82
+ export interface McpTaskShareContext {
83
+ /** The session of the request. It is undefined for a face without sessions: stdio, or an SDK transport. */
84
+ readonly sessionId: string | undefined;
85
+ /** The principal of the request, when the handler of the face gives it before the call (`identify`). */
86
+ readonly principal: Principal | undefined;
87
+ /** The request of the task: its method and its params. */
88
+ readonly request: Request;
89
+ }
90
+
91
+ /** What a face knows of the caller of a new task (CLI-69): the fifth argument of `createTask`. */
92
+ export interface McpTaskCaller {
93
+ /** The principal of the request, from `identify` of the handler of the face. */
94
+ readonly principal?: Principal | undefined;
95
+ }
96
+
97
+ /**
98
+ * The default key of the fair share (CLI-69): the principal of the request, else the session.
99
+ * Each caller with the token of the host gets the same principal (`via: "token"`). That principal
100
+ * does not identify one client, so such a request gets the key of its session. A request without
101
+ * a session (stdio, an SDK transport) gets the key `local`.
102
+ */
103
+ export function mcpTaskShareKey(context: McpTaskShareContext): string {
104
+ const { principal, sessionId } = context;
105
+ if (principal !== undefined && principal.via !== "token") return `principal:${principal.via}:${principal.id}`;
106
+ return sessionId !== undefined ? `session:${sessionId}` : "local";
107
+ }
108
+
75
109
  /** The options of a task store. */
76
110
  export interface McpTaskStoreOptions {
77
111
  /** The most tasks whose work runs at one time. The default is 8. */
@@ -82,8 +116,22 @@ export interface McpTaskStoreOptions {
82
116
  * limit off.
83
117
  */
84
118
  readonly maxStored?: number | undefined;
119
+ /**
120
+ * The last free slots of the store, which only a client below its fair share can take (CLI-69).
121
+ * The default is a tenth of `maxStored`, rounded down: 100 of 1000. The value is an integer
122
+ * from 0 to half of `maxStored`. `0` turns the fair share off.
123
+ */
124
+ readonly reserve?: number | undefined;
125
+ /**
126
+ * This function gives the key of the client of a new task, for the fair share (CLI-69). The
127
+ * tasks with one key count as the tasks of one client. The default is `mcpTaskShareKey`: the
128
+ * principal of the request, else the session.
129
+ */
130
+ readonly shareKey?: ((context: McpTaskShareContext) => string) | undefined;
85
131
  /** The time that a task and its result stay after the task ends, when the client asks for no time. The default is 1 hour. */
86
132
  readonly ttl?: Duration | undefined;
133
+ /** The clock of the timers that remove the tasks. The default is the clock of the platform. A test gives a fake clock. */
134
+ readonly clock?: Clock | undefined;
87
135
  /** This function runs when a task starts, changes its status or ends. An error of it does not stop a task. */
88
136
  readonly onChange?: (() => void) | undefined;
89
137
  }
@@ -97,6 +145,8 @@ export interface McpTasksOptions extends McpTaskStoreOptions {
97
145
  interface Entry {
98
146
  readonly task: Task;
99
147
  readonly sessionId: string | undefined;
148
+ /** The key of the client of the task, for the fair share (CLI-69). */
149
+ readonly key: string;
100
150
  readonly tool: string;
101
151
  readonly controller: AbortController;
102
152
  /** The reason that the task does not start: the store has its most tasks. The task then fails at once. */
@@ -104,20 +154,45 @@ interface Entry {
104
154
  result?: Result;
105
155
  /** True when the work of the task ended: its slot is free. */
106
156
  settled: boolean;
107
- timer?: ReturnType<typeof setTimeout>;
157
+ /** This function stops the timer that removes the task. */
158
+ cancel?: Cancel | undefined;
108
159
  }
109
160
 
110
161
  const TERMINAL = new Set<Task["status"]>(["completed", "failed", "cancelled"]);
111
162
 
163
+ /** True for a limit: an integer of 1 or more, or no limit (`Infinity`). */
164
+ function isLimit(value: number): boolean {
165
+ return value === Number.POSITIVE_INFINITY || (Number.isInteger(value) && value >= 1);
166
+ }
167
+
112
168
  /**
113
169
  * The store of the tasks of an MCP host. It keeps an abort signal for each task, so a cancel of
114
170
  * the task aborts the work of its procedure.
171
+ *
172
+ * The fair share (CLI-69) keeps one client from the whole store. The key of a task
173
+ * (`shareKey`) tells its client: by default the principal of the request, else the session.
174
+ * These are the rules for a new task of a key:
175
+ *
176
+ * - The share of the key is `maxStored / (k + 1)`. `k` is the number of keys that have tasks in
177
+ * the store, the new key included. The `+ 1` keeps a share for the client that comes next.
178
+ * - When `reserve` slots or fewer are free, a key with its share or more does not get more tasks.
179
+ * Its new task replaces the oldest task of its session that ended. Without such a task, the
180
+ * request gets the error `TASKS_FULL`, as for a full store.
181
+ * - A key below its share gets a task while the store has a free slot.
182
+ *
183
+ * Thus one key keeps at most `maxStored - reserve` tasks, because `reserve` is at most half of
184
+ * `maxStored`. One client with many sessions under one principal cannot take the whole store. A
185
+ * session of another client gets a task while the reserve has a free slot. The total limit
186
+ * (`maxStored`) and the limit of 100 tasks of a session stay as they are.
115
187
  */
116
188
  export class McpTaskStore implements TaskStore {
117
189
  private readonly entries = new Map<string, Entry>();
118
190
  private readonly maxRunning: number;
119
191
  private readonly maxStored: number;
192
+ private readonly reserve: number;
120
193
  private readonly ttlMs: number;
194
+ private readonly clock: Clock;
195
+ private readonly shareKey: (context: McpTaskShareContext) => string;
121
196
  private closed = false;
122
197
 
123
198
  constructor(private readonly options: McpTaskStoreOptions = {}) {
@@ -125,11 +200,18 @@ export class McpTaskStore implements TaskStore {
125
200
  if (!Number.isInteger(maxRunning) || maxRunning < 1) throw new RangeError(`maxRunning must be an integer of 1 or more, not ${String(maxRunning)}`);
126
201
  this.maxRunning = maxRunning;
127
202
  const maxStored = options.maxStored ?? MCP_TASK_LIMITS.maxStored;
128
- if (maxStored !== Number.POSITIVE_INFINITY && (!Number.isInteger(maxStored) || maxStored < 1)) {
129
- throw new RangeError(`maxStored must be an integer of 1 or more, or Infinity, not ${String(maxStored)}`);
130
- }
203
+ if (!isLimit(maxStored)) throw new RangeError(`maxStored must be an integer of 1 or more, or Infinity, not ${String(maxStored)}`);
131
204
  this.maxStored = maxStored;
205
+ // Without a total limit the store is never full, so the fair share has nothing to keep
206
+ const finite = maxStored !== Number.POSITIVE_INFINITY;
207
+ const reserve = options.reserve ?? (finite ? Math.floor(maxStored / MCP_TASK_LIMITS.reserveDivisor) : 0);
208
+ if (!Number.isInteger(reserve) || reserve < 0 || (finite && reserve > Math.floor(maxStored / 2))) {
209
+ throw new RangeError(`reserve must be an integer from 0 to half of maxStored, not ${String(reserve)}`);
210
+ }
211
+ this.reserve = finite ? reserve : 0;
132
212
  this.ttlMs = optionalMs(options.ttl, "ttl") ?? MCP_TASK_LIMITS.ttlMs;
213
+ this.clock = options.clock ?? realClock;
214
+ this.shareKey = options.shareKey ?? mcpTaskShareKey;
133
215
  }
134
216
 
135
217
  private changed(): void {
@@ -153,33 +235,82 @@ export class McpTaskStore implements TaskStore {
153
235
  return entry;
154
236
  }
155
237
 
238
+ /** This method removes a task and stops its timer. */
239
+ private remove(entry: Entry): void {
240
+ entry.cancel?.();
241
+ entry.cancel = undefined;
242
+ this.entries.delete(entry.task.taskId);
243
+ }
244
+
156
245
  /** The time to keep a task starts when it ends, and the store removes it only when its work also ended. */
157
246
  private expire(entry: Entry): void {
158
- if (entry.timer) clearTimeout(entry.timer);
247
+ entry.cancel?.();
248
+ entry.cancel = undefined;
159
249
  if (!TERMINAL.has(entry.task.status) || !entry.settled || this.closed) return;
160
250
  const ttl = entry.task.ttl ?? this.ttlMs;
161
- entry.timer = setTimeout(() => {
162
- this.entries.delete(entry.task.taskId);
163
- }, ttl);
164
- entry.timer.unref?.();
251
+ const cancel = this.clock.after(ttl, () => {
252
+ if (this.entries.get(entry.task.taskId) === entry) this.entries.delete(entry.task.taskId);
253
+ });
254
+ // The timer of a task does not keep the process alive
255
+ cancel.unref?.();
256
+ entry.cancel = cancel;
257
+ }
258
+
259
+ /** The key of the client of a new task. An error of the function, or a key that is not a string, refuses the task. */
260
+ private keyOf(context: McpTaskShareContext): string {
261
+ let key: unknown;
262
+ try {
263
+ key = this.shareKey(context);
264
+ } catch (error) {
265
+ throw new McpError(ErrorCode.InternalError, `The share key of the task store failed: ${error instanceof Error ? error.message : String(error)}`);
266
+ }
267
+ if (typeof key !== "string") throw new McpError(ErrorCode.InternalError, "The share key of the task store gave no string");
268
+ return key;
269
+ }
270
+
271
+ /** The tasks of a key, and the number of keys that have tasks, the key included. */
272
+ private holding(key: string): { held: number; keys: number } {
273
+ const keys = new Set<string>([key]);
274
+ let held = 0;
275
+ for (const entry of this.entries.values()) {
276
+ keys.add(entry.key);
277
+ if (entry.key === key) held++;
278
+ }
279
+ return { held, keys: keys.size };
280
+ }
281
+
282
+ /**
283
+ * True when a new task of the key must replace a task of its session: the store is full, or
284
+ * `reserve` slots or fewer are free and the key has its fair share or more (CLI-69).
285
+ */
286
+ private mustReplace(key: string): boolean {
287
+ const size = this.entries.size;
288
+ if (size >= this.maxStored) return true;
289
+ if (this.reserve === 0 || size < this.maxStored - this.reserve) return false;
290
+ const { held, keys } = this.holding(key);
291
+ // The share is maxStored / (keys + 1): the + 1 keeps a share for the client that comes next
292
+ return held * (keys + 1) >= this.maxStored;
165
293
  }
166
294
 
167
295
  /**
168
- * This method removes the oldest tasks of a session that ended, until the session and the store
169
- * have room for one more task. It removes only the tasks of the same session, so a client cannot
170
- * remove the results of another session. A task whose work runs stays: the limit of the running
171
- * tasks bounds them.
296
+ * This method removes the oldest tasks of a session that ended. It removes one task for a
297
+ * replacement (`replace`), and enough tasks to keep the session below its limit of 100. It
298
+ * removes only the tasks of the same session, so a client cannot remove the results of another
299
+ * session. A task whose work runs stays: the limit of the running tasks bounds them. The method
300
+ * gives the number of tasks that it removed.
172
301
  */
173
- private makeRoom(sessionId: string | undefined): void {
302
+ private makeRoom(sessionId: string | undefined, replace: boolean): number {
174
303
  const own = [...this.entries.values()].filter((entry) => entry.sessionId === sessionId);
175
- let excess = Math.max(own.length + 1 - MCP_TASK_LIMITS.maxStoredPerSession, this.entries.size + 1 - this.maxStored);
304
+ let excess = Math.max(own.length + 1 - MCP_TASK_LIMITS.maxStoredPerSession, this.entries.size + 1 - this.maxStored, replace ? 1 : 0);
305
+ let removed = 0;
176
306
  for (const entry of own) {
177
307
  if (excess <= 0) break;
178
308
  if (!entry.settled || !TERMINAL.has(entry.task.status)) continue;
179
- if (entry.timer) clearTimeout(entry.timer);
180
- this.entries.delete(entry.task.taskId);
309
+ this.remove(entry);
181
310
  excess--;
311
+ removed++;
182
312
  }
313
+ return removed;
183
314
  }
184
315
 
185
316
  /** The count of the tasks whose work runs. */
@@ -189,20 +320,28 @@ export class McpTaskStore implements TaskStore {
189
320
  return count;
190
321
  }
191
322
 
323
+ /** The error of a request that the store refuses: the store is full, or the client has its fair share near the limit. */
324
+ private full(key: string): McpError {
325
+ const size = this.entries.size;
326
+ const reason =
327
+ size >= this.maxStored
328
+ ? `The host stores ${String(size)} tasks, its limit of stored tasks.`
329
+ : `The host stores ${String(size)} tasks, near its limit of stored tasks (${String(this.maxStored)}), and this client has its fair share of them (${String(this.holding(key).held)} tasks).`;
330
+ return new McpError(ErrorCode.InvalidRequest, `${reason} Try again when the time of a task ends.`, { code: "TASKS_FULL" });
331
+ }
332
+
192
333
  /**
193
334
  * The store counts and inserts a task in one step, so a batch of requests cannot pass the limits.
194
- * When the store is full after `makeRoom`, the request gets an error and the store keeps nothing.
335
+ * When the store has no room after `makeRoom`, the request gets an error and the store keeps
336
+ * nothing. The fifth argument tells the caller (CLI-69): the face gives the principal of the
337
+ * request, for the key of the fair share.
195
338
  */
196
- async createTask(params: CreateTaskOptions, _requestId: RequestId, request: Request, sessionId?: string): Promise<Task> {
339
+ async createTask(params: CreateTaskOptions, _requestId: RequestId, request: Request, sessionId?: string, caller: McpTaskCaller = {}): Promise<Task> {
197
340
  if (this.closed) throw new McpError(ErrorCode.InvalidRequest, "The MCP host is stopping: it starts no task");
198
- this.makeRoom(sessionId);
199
- if (this.entries.size >= this.maxStored) {
200
- throw new McpError(
201
- ErrorCode.InvalidRequest,
202
- `The host stores ${String(this.entries.size)} tasks, its limit of stored tasks. Try again when the time of a task ends.`,
203
- { code: "TASKS_FULL" },
204
- );
205
- }
341
+ const key = this.keyOf({ sessionId, principal: caller.principal, request });
342
+ const replace = this.mustReplace(key);
343
+ const removed = this.makeRoom(sessionId, replace);
344
+ if (this.entries.size >= this.maxStored || (replace && removed === 0)) throw this.full(key);
206
345
  const running = this.runningCount();
207
346
  const refused =
208
347
  running >= this.maxRunning ? `The host runs ${String(running)} tasks, its limit. Wait for a task to end, or cancel one.` : undefined;
@@ -220,6 +359,7 @@ export class McpTaskStore implements TaskStore {
220
359
  this.entries.set(task.taskId, {
221
360
  task,
222
361
  sessionId,
362
+ key,
223
363
  tool: typeof name === "string" ? name : request.method,
224
364
  controller: new AbortController(),
225
365
  refused,
@@ -338,7 +478,7 @@ export class McpTaskStore implements TaskStore {
338
478
  await this.updateTaskStatus(id, "cancelled", "The MCP host stopped", entry.sessionId).catch(() => undefined);
339
479
  }
340
480
  this.closed = true;
341
- for (const entry of this.entries.values()) if (entry.timer) clearTimeout(entry.timer);
481
+ for (const entry of this.entries.values()) entry.cancel?.();
342
482
  this.entries.clear();
343
483
  this.changed();
344
484
  }
@@ -12,6 +12,7 @@ import {
12
12
  ListToolsRequestSchema,
13
13
  McpError,
14
14
  type CallToolResult,
15
+ type Request,
15
16
  type ServerNotification,
16
17
  type Task,
17
18
  } from "@modelcontextprotocol/sdk/types.js";
@@ -28,6 +29,7 @@ import type {
28
29
  ElicitRequest,
29
30
  ElicitResult,
30
31
  ElicitOptions,
32
+ Principal,
31
33
  ReportProgress,
32
34
  } from "@procedures/client";
33
35
  import { LOCAL_CREDENTIALS, NARROWING_METADATA_KEY, PROCEDURE_REGISTRY, addNarrowing, pathToMethod, createElicit, elicitWithPolicy, requestCredentials, untrustedTextsOf } from "@procedures/client";
@@ -79,6 +81,8 @@ export const DEFAULT_ELICIT_TIMEOUT_MS = 300_000;
79
81
  interface CallExtra {
80
82
  signal: AbortSignal;
81
83
  requestId: string | number;
84
+ /** The session of the request: undefined for a face without sessions (stdio, an SDK transport) */
85
+ sessionId?: string | undefined;
82
86
  _meta?: { progressToken?: string | number | undefined; readonly [key: string]: unknown } | undefined;
83
87
  sendNotification: (notification: ServerNotification) => Promise<void>;
84
88
  /** The HTTP request of the message: present only for a network transport (Streamable HTTP) */
@@ -307,7 +311,7 @@ export class McpServerTransport implements ServerTransport {
307
311
  if (!this.taskStore || (support !== "optional" && support !== "required")) {
308
312
  throw new McpError(ErrorCode.MethodNotFound, `The tool ${name} does not run as a task`);
309
313
  }
310
- return this.startTask(server, this.taskStore, tool, args, callExtra);
314
+ return this.startTask(server, this.taskStore, tool, args, callExtra, { method: request.method, params: request.params });
311
315
  }
312
316
  if (support === "required") {
313
317
  throw new McpError(ErrorCode.MethodNotFound, `The tool ${name} runs only as a task: call it with a task`);
@@ -321,13 +325,23 @@ export class McpServerTransport implements ServerTransport {
321
325
  * call goes on. A progress of the procedure becomes the status message of the task, and a
322
326
  * progress notification when the client sent a progress token. A cancel of the task aborts the
323
327
  * call. A task above the limit of the store fails at once with the reason. The call of a task
324
- * cannot ask the person: its request already has its answer.
328
+ * cannot ask the person: its request already has its answer. The store gets the principal of
329
+ * the request before the call, for the fair share of its tasks (CLI-69).
325
330
  */
326
- private async startTask(server: McpServer, store: McpTaskStore, tool: McpTool, args: Record<string, unknown> | undefined, extra: CallExtra): Promise<{ task: Task }> {
331
+ private async startTask(
332
+ server: McpServer,
333
+ store: McpTaskStore,
334
+ tool: McpTool,
335
+ args: Record<string, unknown> | undefined,
336
+ extra: CallExtra,
337
+ request: Request,
338
+ ): Promise<{ task: Task }> {
327
339
  const taskStore = extra.taskStore;
328
340
  if (!taskStore) throw new McpError(ErrorCode.InternalError, "The server has no task store for this request");
329
341
  const ttl = extra.taskRequestedTtl;
330
- const task = await taskStore.createTask(typeof ttl === "number" ? { ttl } : {});
342
+ const principal = await this.callPrincipal(server, extra);
343
+ // The store directly, not the task store of the request: only the store takes the caller
344
+ const task = await store.createTask(typeof ttl === "number" ? { ttl } : {}, extra.requestId, request, extra.sessionId, principal ? { principal } : {});
331
345
  const id = task.taskId;
332
346
  const finish = async (result: CallToolResult): Promise<void> => {
333
347
  // A cancelled task keeps its status: the store refuses a result after a cancel
@@ -362,6 +376,21 @@ export class McpServerTransport implements ServerTransport {
362
376
  return { task };
363
377
  }
364
378
 
379
+ /**
380
+ * The principal of a call before the call (CLI-69): `identify` of the handler reads the
381
+ * credentials of the call. A handler without `identify`, a refusal and an error give undefined.
382
+ * Then the task store keys the task with its session.
383
+ */
384
+ private async callPrincipal(server: McpServer, extra: CallExtra): Promise<Principal | undefined> {
385
+ const handler = this.server;
386
+ if (!handler.identify) return undefined;
387
+ try {
388
+ return await handler.identify(callCredentials(extra, server === this.mcpServer));
389
+ } catch {
390
+ return undefined;
391
+ }
392
+ }
393
+
365
394
  /**
366
395
  * This method calls the procedure of a tool and gives the MCP result. `offerElicit` is false for
367
396
  * the call of a task: then the procedure gets no function to ask the person.
package/src/types.ts CHANGED
@@ -187,7 +187,8 @@ export interface McpServerTransportOptions {
187
187
  streamLimits?: { items?: number; time?: Duration } | undefined;
188
188
 
189
189
  /**
190
- * MCP tasks (CLI-35): a store, or the options of a new store (`maxRunning`, `maxStored`, `ttl`).
190
+ * MCP tasks (CLI-35): a store, or the options of a new store (`maxRunning`, `maxStored`,
191
+ * `reserve`, `shareKey`, `ttl`, `clock`).
191
192
  * With it, a tool whose procedure has `metadata.taskSupport` can run as a task. Without it, each
192
193
  * tool call is a normal request. The stop of the transport closes a store that it made.
193
194
  */