@procedures/mcp-server 0.14.0 → 0.14.1
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/CHANGELOG.md +40 -0
- package/README.md +99 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/face.d.ts +20 -1
- package/dist/face.d.ts.map +1 -1
- package/dist/face.js +49 -3
- package/dist/face.js.map +1 -1
- package/dist/host.d.ts +64 -4
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +73 -11
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/tasks.d.ts +131 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +276 -0
- package/dist/tasks.js.map +1 -0
- package/dist/transport/guard.d.ts +61 -0
- package/dist/transport/guard.d.ts.map +1 -0
- package/dist/transport/guard.js +58 -0
- package/dist/transport/guard.js.map +1 -0
- package/dist/transport/http.d.ts +17 -2
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +157 -37
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/mcp-transport.d.ts +19 -0
- package/dist/transport/mcp-transport.d.ts.map +1 -1
- package/dist/transport/mcp-transport.js +183 -76
- package/dist/transport/mcp-transport.js.map +1 -1
- package/dist/types.d.ts +43 -4
- package/dist/types.d.ts.map +1 -1
- package/package.json +5 -4
- package/src/face.ts +82 -4
- package/src/host.ts +133 -21
- package/src/index.ts +23 -1
- package/src/tasks.ts +318 -0
- package/src/transport/guard.ts +90 -0
- package/src/transport/http.ts +164 -36
- package/src/transport/mcp-transport.ts +200 -81
- package/src/types.ts +44 -4
package/src/tasks.ts
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP tasks (CLI-35): the long-running task primitive of the MCP specification 2025-11-25.
|
|
3
|
+
*
|
|
4
|
+
* A client starts a long tool call as a task: it gets a task id at once, polls the status, gets
|
|
5
|
+
* the result later, and can cancel the task. A procedure declares that its tool can run as a task
|
|
6
|
+
* with `metadata.taskSupport` (`"optional"` or `"required"`). The MCP host gives the store of the
|
|
7
|
+
* tasks (`tasks` of `createMcpHost`). Without that option the host has no tasks, and each tool
|
|
8
|
+
* call is a normal request.
|
|
9
|
+
*
|
|
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.
|
|
12
|
+
* - A slot of the limit (`maxRunning`) stays taken until the work of the task ends, not until its
|
|
13
|
+
* status ends: a cancelled task holds its slot until its procedure returns. A task above the
|
|
14
|
+
* limit is created, and then fails at once with the reason. The SDK 1.32.1 cannot give an error
|
|
15
|
+
* for a task request, so the client reads the reason in the result of the task.
|
|
16
|
+
* - The time to keep a task (`ttl`) starts when the task ends. The store never removes a task
|
|
17
|
+
* whose work runs, so a short `ttl` does not let work escape the limit or the cancel. A refused
|
|
18
|
+
* task stays 1 minute, and each session keeps at most 100 tasks: a new task removes the oldest
|
|
19
|
+
* task of its session that ended.
|
|
20
|
+
* - A cancel of a task (`tasks/cancel`) aborts the signal of its procedure call. The close of a
|
|
21
|
+
* session cancels its tasks, and the stop of the host cancels each task.
|
|
22
|
+
*
|
|
23
|
+
* The SDK marks its task API as experimental, so this part follows the SDK when it changes.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { randomUUID } from "node:crypto";
|
|
27
|
+
import type { CreateTaskOptions, TaskStore } from "@modelcontextprotocol/sdk/experimental/tasks/interfaces.js";
|
|
28
|
+
import { ErrorCode, McpError, type Request, type RequestId, type Result, type Task } from "@modelcontextprotocol/sdk/types.js";
|
|
29
|
+
import { optionalMs, type Duration } from "@procedures/client";
|
|
30
|
+
|
|
31
|
+
/** The limits of the tasks of one MCP host. */
|
|
32
|
+
export const MCP_TASK_LIMITS = {
|
|
33
|
+
/** A task and its result stay for this time after the task ends: 1 hour by default. */
|
|
34
|
+
ttlMs: 3_600_000,
|
|
35
|
+
/** The longest time that a client can ask for: 1 day. */
|
|
36
|
+
maxTtlMs: 86_400_000,
|
|
37
|
+
/** The shortest time that a client can ask for: 1 second. */
|
|
38
|
+
minTtlMs: 1_000,
|
|
39
|
+
/** The time that the server proposes between two polls of the status: 1 second. */
|
|
40
|
+
pollMs: 1_000,
|
|
41
|
+
/** The most tasks whose work runs at one time. A new task above the limit fails at once. */
|
|
42
|
+
maxRunning: 8,
|
|
43
|
+
/** The tasks on one page of `tasks/list`. */
|
|
44
|
+
pageSize: 10,
|
|
45
|
+
/** A refused task and its reason stay for this time: 1 minute. */
|
|
46
|
+
refusedTtlMs: 60_000,
|
|
47
|
+
/** The most tasks that the store keeps for one session. A new task removes the oldest task of its session that ended. */
|
|
48
|
+
maxStoredPerSession: 100,
|
|
49
|
+
} as const;
|
|
50
|
+
|
|
51
|
+
/** A task whose work did not end, as a status page of the host shows it. */
|
|
52
|
+
export interface McpTaskInfo {
|
|
53
|
+
/** The task id that the client got. */
|
|
54
|
+
readonly id: string;
|
|
55
|
+
/** The name of the tool, for example `crawl.site`. */
|
|
56
|
+
readonly tool: string;
|
|
57
|
+
/** `working`, `input_required`, or `cancelled` while the procedure stops. */
|
|
58
|
+
readonly status: string;
|
|
59
|
+
/** The text of the progress, for example `3 of 10 done`, or null. */
|
|
60
|
+
readonly message: string | null;
|
|
61
|
+
readonly createdAt: string;
|
|
62
|
+
readonly updatedAt: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The options of a task store. */
|
|
66
|
+
export interface McpTaskStoreOptions {
|
|
67
|
+
/** The most tasks whose work runs at one time. The default is 8. */
|
|
68
|
+
readonly maxRunning?: number | undefined;
|
|
69
|
+
/** 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. */
|
|
70
|
+
readonly ttl?: Duration | undefined;
|
|
71
|
+
/** This function runs when a task starts, changes its status or ends. An error of it does not stop a task. */
|
|
72
|
+
readonly onChange?: (() => void) | undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The tasks of an MCP host (`tasks` of `createMcpHost`): a store, or the options of a new store. */
|
|
76
|
+
export interface McpTasksOptions extends McpTaskStoreOptions {
|
|
77
|
+
/** The store of the tasks. Without it, the host makes a store with the other options. */
|
|
78
|
+
readonly store?: McpTaskStore | undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface Entry {
|
|
82
|
+
readonly task: Task;
|
|
83
|
+
readonly sessionId: string | undefined;
|
|
84
|
+
readonly tool: string;
|
|
85
|
+
readonly controller: AbortController;
|
|
86
|
+
/** The reason that the task does not start: the store has its most tasks. The task then fails at once. */
|
|
87
|
+
readonly refused: string | undefined;
|
|
88
|
+
result?: Result;
|
|
89
|
+
/** True when the work of the task ended: its slot is free. */
|
|
90
|
+
settled: boolean;
|
|
91
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const TERMINAL = new Set<Task["status"]>(["completed", "failed", "cancelled"]);
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The store of the tasks of an MCP host. It keeps an abort signal for each task, so a cancel of
|
|
98
|
+
* the task aborts the work of its procedure.
|
|
99
|
+
*/
|
|
100
|
+
export class McpTaskStore implements TaskStore {
|
|
101
|
+
private readonly entries = new Map<string, Entry>();
|
|
102
|
+
private readonly maxRunning: number;
|
|
103
|
+
private readonly ttlMs: number;
|
|
104
|
+
private closed = false;
|
|
105
|
+
|
|
106
|
+
constructor(private readonly options: McpTaskStoreOptions = {}) {
|
|
107
|
+
const maxRunning = options.maxRunning ?? MCP_TASK_LIMITS.maxRunning;
|
|
108
|
+
if (!Number.isInteger(maxRunning) || maxRunning < 1) throw new RangeError(`maxRunning must be an integer of 1 or more, not ${String(maxRunning)}`);
|
|
109
|
+
this.maxRunning = maxRunning;
|
|
110
|
+
this.ttlMs = optionalMs(options.ttl, "ttl") ?? MCP_TASK_LIMITS.ttlMs;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private changed(): void {
|
|
114
|
+
try {
|
|
115
|
+
this.options.onChange?.();
|
|
116
|
+
} catch {
|
|
117
|
+
// A listener writes a status file, for example: its error does not stop a task
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The entry of a task, when the session may see it: a task of another session is not found. */
|
|
122
|
+
private lookup(taskId: string, sessionId: string | undefined): Entry | undefined {
|
|
123
|
+
const entry = this.entries.get(taskId);
|
|
124
|
+
if (entry && sessionId !== undefined && entry.sessionId !== undefined && entry.sessionId !== sessionId) return undefined;
|
|
125
|
+
return entry;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private found(taskId: string, sessionId: string | undefined): Entry {
|
|
129
|
+
const entry = this.lookup(taskId, sessionId);
|
|
130
|
+
if (!entry) throw new Error(`Task with ID ${taskId} not found`);
|
|
131
|
+
return entry;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The time to keep a task starts when it ends, and the store removes it only when its work also ended. */
|
|
135
|
+
private expire(entry: Entry): void {
|
|
136
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
137
|
+
if (!TERMINAL.has(entry.task.status) || !entry.settled || this.closed) return;
|
|
138
|
+
const ttl = entry.task.ttl ?? this.ttlMs;
|
|
139
|
+
entry.timer = setTimeout(() => {
|
|
140
|
+
this.entries.delete(entry.task.taskId);
|
|
141
|
+
}, ttl);
|
|
142
|
+
entry.timer.unref?.();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* This method removes the oldest tasks of a session that ended, until the session has room for
|
|
147
|
+
* one more task. A task whose work runs stays: the limit of the running tasks bounds them.
|
|
148
|
+
*/
|
|
149
|
+
private makeRoom(sessionId: string | undefined): void {
|
|
150
|
+
const own = [...this.entries.values()].filter((entry) => entry.sessionId === sessionId);
|
|
151
|
+
let excess = own.length + 1 - MCP_TASK_LIMITS.maxStoredPerSession;
|
|
152
|
+
for (const entry of own) {
|
|
153
|
+
if (excess <= 0) break;
|
|
154
|
+
if (!entry.settled || !TERMINAL.has(entry.task.status)) continue;
|
|
155
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
156
|
+
this.entries.delete(entry.task.taskId);
|
|
157
|
+
excess--;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The count of the tasks whose work runs. */
|
|
162
|
+
private runningCount(): number {
|
|
163
|
+
let count = 0;
|
|
164
|
+
for (const entry of this.entries.values()) if (!entry.settled) count++;
|
|
165
|
+
return count;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The store counts and inserts a task in one step, so a batch of requests cannot pass the limit. */
|
|
169
|
+
async createTask(params: CreateTaskOptions, _requestId: RequestId, request: Request, sessionId?: string): Promise<Task> {
|
|
170
|
+
if (this.closed) throw new McpError(ErrorCode.InvalidRequest, "The MCP host is stopping: it starts no task");
|
|
171
|
+
this.makeRoom(sessionId);
|
|
172
|
+
const running = this.runningCount();
|
|
173
|
+
const refused =
|
|
174
|
+
running >= this.maxRunning ? `The host runs ${String(running)} tasks, its limit. Wait for a task to end, or cancel one.` : undefined;
|
|
175
|
+
const asked = params.ttl ?? this.ttlMs;
|
|
176
|
+
const createdAt = new Date().toISOString();
|
|
177
|
+
const task: Task = {
|
|
178
|
+
taskId: randomUUID(),
|
|
179
|
+
status: "working",
|
|
180
|
+
ttl: refused !== undefined ? MCP_TASK_LIMITS.refusedTtlMs : Math.min(Math.max(MCP_TASK_LIMITS.minTtlMs, asked), MCP_TASK_LIMITS.maxTtlMs),
|
|
181
|
+
createdAt,
|
|
182
|
+
lastUpdatedAt: createdAt,
|
|
183
|
+
pollInterval: params.pollInterval ?? MCP_TASK_LIMITS.pollMs,
|
|
184
|
+
};
|
|
185
|
+
const name = (request.params as { name?: unknown } | undefined)?.name;
|
|
186
|
+
this.entries.set(task.taskId, {
|
|
187
|
+
task,
|
|
188
|
+
sessionId,
|
|
189
|
+
tool: typeof name === "string" ? name : request.method,
|
|
190
|
+
controller: new AbortController(),
|
|
191
|
+
refused,
|
|
192
|
+
// A refused task never starts its work, so it takes no slot
|
|
193
|
+
settled: refused !== undefined,
|
|
194
|
+
});
|
|
195
|
+
this.changed();
|
|
196
|
+
return { ...task };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async getTask(taskId: string, sessionId?: string): Promise<Task | null> {
|
|
200
|
+
const entry = this.lookup(taskId, sessionId);
|
|
201
|
+
return entry ? { ...entry.task } : null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async storeTaskResult(taskId: string, status: "completed" | "failed", result: Result, sessionId?: string): Promise<void> {
|
|
205
|
+
const entry = this.found(taskId, sessionId);
|
|
206
|
+
if (TERMINAL.has(entry.task.status)) {
|
|
207
|
+
throw new Error(`Cannot store result for task ${taskId} in terminal status '${entry.task.status}'. Task results can only be stored once.`);
|
|
208
|
+
}
|
|
209
|
+
entry.result = result;
|
|
210
|
+
entry.task.status = status;
|
|
211
|
+
entry.task.lastUpdatedAt = new Date().toISOString();
|
|
212
|
+
this.expire(entry);
|
|
213
|
+
this.changed();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async getTaskResult(taskId: string, sessionId?: string): Promise<Result> {
|
|
217
|
+
const entry = this.found(taskId, sessionId);
|
|
218
|
+
if (!entry.result) throw new Error(`Task ${taskId} has no result stored`);
|
|
219
|
+
return entry.result;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async updateTaskStatus(taskId: string, status: Task["status"], statusMessage?: string, sessionId?: string): Promise<void> {
|
|
223
|
+
const entry = this.found(taskId, sessionId);
|
|
224
|
+
if (TERMINAL.has(entry.task.status)) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Cannot update task ${taskId} from terminal status '${entry.task.status}' to '${status}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
entry.task.status = status;
|
|
230
|
+
if (statusMessage) entry.task.statusMessage = statusMessage;
|
|
231
|
+
entry.task.lastUpdatedAt = new Date().toISOString();
|
|
232
|
+
// A cancel aborts the work of the procedure: its requests in progress stop
|
|
233
|
+
if (status === "cancelled") entry.controller.abort(new Error("The client cancelled the task"));
|
|
234
|
+
this.expire(entry);
|
|
235
|
+
this.changed();
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async listTasks(cursor?: string, sessionId?: string): Promise<{ tasks: Task[]; nextCursor?: string }> {
|
|
239
|
+
const ids = [...this.entries.keys()].filter((id) => this.lookup(id, sessionId) !== undefined);
|
|
240
|
+
let start = 0;
|
|
241
|
+
if (cursor) {
|
|
242
|
+
const index = ids.indexOf(cursor);
|
|
243
|
+
if (index < 0) throw new Error(`Invalid cursor: ${cursor}`);
|
|
244
|
+
start = index + 1;
|
|
245
|
+
}
|
|
246
|
+
const page = ids.slice(start, start + MCP_TASK_LIMITS.pageSize);
|
|
247
|
+
const tasks = page.map((id) => ({ ...this.entries.get(id)!.task }));
|
|
248
|
+
return start + MCP_TASK_LIMITS.pageSize < ids.length ? { tasks, nextCursor: page[page.length - 1]! } : { tasks };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* This method tells the store that the work of a task ended: the procedure returned or threw.
|
|
253
|
+
* Its slot is free, and the time to keep the task starts when the task also has an end status.
|
|
254
|
+
*/
|
|
255
|
+
settle(taskId: string): void {
|
|
256
|
+
const entry = this.entries.get(taskId);
|
|
257
|
+
if (!entry || entry.settled) return;
|
|
258
|
+
entry.settled = true;
|
|
259
|
+
this.expire(entry);
|
|
260
|
+
this.changed();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The abort signal of a task. A cancel of the task aborts it. An unknown task gives an aborted signal. */
|
|
264
|
+
signal(taskId: string): AbortSignal {
|
|
265
|
+
return this.entries.get(taskId)?.controller.signal ?? AbortSignal.abort(new Error("The task is not known"));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The reason that a task did not start, or undefined for a task that started. */
|
|
269
|
+
refusal(taskId: string): string | undefined {
|
|
270
|
+
return this.entries.get(taskId)?.refused;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The tasks whose work did not end, the oldest first. */
|
|
274
|
+
running(): McpTaskInfo[] {
|
|
275
|
+
const infos: McpTaskInfo[] = [];
|
|
276
|
+
for (const [id, entry] of this.entries) {
|
|
277
|
+
if (entry.settled) continue;
|
|
278
|
+
const { task } = entry;
|
|
279
|
+
infos.push({ id, tool: entry.tool, status: task.status, message: task.statusMessage ?? null, createdAt: task.createdAt, updatedAt: task.lastUpdatedAt });
|
|
280
|
+
}
|
|
281
|
+
return infos;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** The sessions that have a task whose work runs. The session limit of the HTTP face keeps them open. */
|
|
285
|
+
busySessions(): Set<string> {
|
|
286
|
+
const busy = new Set<string>();
|
|
287
|
+
for (const entry of this.entries.values()) if (!entry.settled && entry.sessionId !== undefined) busy.add(entry.sessionId);
|
|
288
|
+
return busy;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** This method cancels the tasks of a session that closed. Their work stops. */
|
|
292
|
+
async cancelSession(sessionId: string, message = "The session of the task closed"): Promise<void> {
|
|
293
|
+
for (const [id, entry] of this.entries) {
|
|
294
|
+
if (entry.sessionId !== sessionId || TERMINAL.has(entry.task.status)) continue;
|
|
295
|
+
await this.updateTaskStatus(id, "cancelled", message, sessionId).catch(() => undefined);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** This method cancels each task that runs and removes all the tasks and their timers. A second close does nothing. */
|
|
300
|
+
async close(): Promise<void> {
|
|
301
|
+
if (this.closed) return;
|
|
302
|
+
for (const [id, entry] of this.entries) {
|
|
303
|
+
if (TERMINAL.has(entry.task.status)) continue;
|
|
304
|
+
await this.updateTaskStatus(id, "cancelled", "The MCP host stopped", entry.sessionId).catch(() => undefined);
|
|
305
|
+
}
|
|
306
|
+
this.closed = true;
|
|
307
|
+
for (const entry of this.entries.values()) if (entry.timer) clearTimeout(entry.timer);
|
|
308
|
+
this.entries.clear();
|
|
309
|
+
this.changed();
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The task store of an option: the given store, or a new store. `owned` is true for a new store. */
|
|
314
|
+
export function taskStoreOf(options: McpTasksOptions | undefined): { store: McpTaskStore; owned: boolean } | undefined {
|
|
315
|
+
if (options === undefined) return undefined;
|
|
316
|
+
if (options.store) return { store: options.store, owned: false };
|
|
317
|
+
return { store: new McpTaskStore(options), owned: true };
|
|
318
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The checks of a request to the Streamable HTTP face (CLI-35), in one place.
|
|
3
|
+
*
|
|
4
|
+
* The `handle` of the face calls `guardMcpRequest` before a request reaches the MCP SDK. The face
|
|
5
|
+
* mounts on more than one kind of listener, so the listener adds no second check for its path.
|
|
6
|
+
*
|
|
7
|
+
* - The checks of a web browser (`checkBrowserRequest` of the core): a request on a loopback
|
|
8
|
+
* address names a loopback host or an allowed host (DNS rebinding), and an `Origin` header names
|
|
9
|
+
* the server or a permitted origin. A request with cookies needs a named origin (CSRF).
|
|
10
|
+
* - The bearer token, with `tokenMatches` of the core: its time does not tell the token.
|
|
11
|
+
*
|
|
12
|
+
* The other guards of the face:
|
|
13
|
+
*
|
|
14
|
+
* - The face reads the body of a request that starts a session to a limit (4 MiB, the limit of
|
|
15
|
+
* the SDK), with `readJsonBody` of the core. Only an `initialize` request starts a session, so
|
|
16
|
+
* a stray POST makes no MCP server.
|
|
17
|
+
* - With `maxSessions`, the face keeps at most that many sessions. A new session above the limit
|
|
18
|
+
* closes the session that was idle longest: no task in progress and no open response.
|
|
19
|
+
* - `assertLoopbackBind` refuses a listener on an address that is not loopback, unless the
|
|
20
|
+
* operator allows it. The owner of the listener calls it before it listens.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { IncomingMessage } from "node:http";
|
|
24
|
+
import { bearerOf, checkBrowserRequest, isLoopbackHost, tokenMatches, type BrowserGuardOptions } from "@procedures/client";
|
|
25
|
+
|
|
26
|
+
/** The limits of the Streamable HTTP face. `maxBodyBytes` and `maxSessions` of the HTTP options change them. */
|
|
27
|
+
export const MCP_HTTP_LIMITS: {
|
|
28
|
+
/** The largest body of a request: 4 MiB, the limit of the SDK. */
|
|
29
|
+
readonly maxBodyBytes: 4_194_304;
|
|
30
|
+
/** The most sessions at one time: no limit, unless the HTTP options give one. */
|
|
31
|
+
readonly maxSessions: number;
|
|
32
|
+
/** The seconds in the `Retry-After` header of a 503, when each session is busy. */
|
|
33
|
+
readonly retryAfterSeconds: 5;
|
|
34
|
+
} = {
|
|
35
|
+
maxBodyBytes: 4_194_304,
|
|
36
|
+
maxSessions: Number.POSITIVE_INFINITY,
|
|
37
|
+
retryAfterSeconds: 5,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** The options of `guardMcpRequest`. */
|
|
41
|
+
export interface McpRequestGuardOptions {
|
|
42
|
+
/** The token that each request sends as `Authorization: Bearer <token>`. Without it, the face checks no token. */
|
|
43
|
+
readonly token?: string | undefined;
|
|
44
|
+
/** The browser origins that can call the face, besides its own origin. */
|
|
45
|
+
readonly allowedOrigins?: BrowserGuardOptions["allowedOrigins"];
|
|
46
|
+
/** The host names that a request on a loopback address can name, besides the loopback names. */
|
|
47
|
+
readonly allowedHosts?: BrowserGuardOptions["allowedHosts"];
|
|
48
|
+
/** True when the server trusts cookies for the request: then only a named origin can call (CSRF). */
|
|
49
|
+
readonly ambient?: boolean | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The result of the checks: the request passes, or the HTTP status, the error and the headers to send. */
|
|
53
|
+
export type McpGuardResult =
|
|
54
|
+
| { readonly ok: true }
|
|
55
|
+
| {
|
|
56
|
+
readonly ok: false;
|
|
57
|
+
readonly status: 401 | 403 | 405 | 415;
|
|
58
|
+
readonly code: string;
|
|
59
|
+
readonly message: string;
|
|
60
|
+
readonly headers?: Readonly<Record<string, string>> | undefined;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** The checks of a request to the MCP endpoint: the browser checks, then the token. */
|
|
64
|
+
export function guardMcpRequest(req: Pick<IncomingMessage, "method" | "headers" | "socket">, options: McpRequestGuardOptions = {}): McpGuardResult {
|
|
65
|
+
const browser: BrowserGuardOptions = {
|
|
66
|
+
...(options.allowedOrigins !== undefined ? { allowedOrigins: options.allowedOrigins } : {}),
|
|
67
|
+
...(options.allowedHosts !== undefined ? { allowedHosts: options.allowedHosts } : {}),
|
|
68
|
+
};
|
|
69
|
+
const checked = checkBrowserRequest(req, browser, false, options.ambient === true);
|
|
70
|
+
if (!checked.ok) return checked;
|
|
71
|
+
if (options.token !== undefined && !tokenMatches(options.token, bearerOf(req.headers.authorization))) {
|
|
72
|
+
return {
|
|
73
|
+
ok: false,
|
|
74
|
+
status: 401,
|
|
75
|
+
code: "UNAUTHORIZED",
|
|
76
|
+
message: "Unauthorized: this server requires its token",
|
|
77
|
+
headers: { "www-authenticate": 'Bearer realm="mcp"' },
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return { ok: true };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* This function refuses a listener on an address that is not loopback, unless `allowRemote` is
|
|
85
|
+
* true. Then other computers can reach the tools and try the token.
|
|
86
|
+
*/
|
|
87
|
+
export function assertLoopbackBind(host: string, allowRemote = false): void {
|
|
88
|
+
if (isLoopbackHost(host) || allowRemote) return;
|
|
89
|
+
throw new Error(`The MCP endpoint would listen on ${host}, which is not a loopback address. To serve other computers, allow it (allowRemote).`);
|
|
90
|
+
}
|
package/src/transport/http.ts
CHANGED
|
@@ -12,18 +12,37 @@
|
|
|
12
12
|
* Each tool call carries the credentials of its HTTP request (CLI-10), so the request hook of the
|
|
13
13
|
* server (`principalOf`) and its token check apply. A server that reads cookies trusts a request
|
|
14
14
|
* with a cookie only from a named origin (CSRF).
|
|
15
|
+
*
|
|
16
|
+
* The checks of each request are in `guard.ts` (CLI-35). Only an `initialize` request starts a
|
|
17
|
+
* session, each body has a limit, and with `maxSessions` the endpoint keeps at most that many sessions.
|
|
15
18
|
*/
|
|
16
19
|
|
|
17
20
|
import { randomUUID } from "node:crypto";
|
|
18
21
|
import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from "node:http";
|
|
19
22
|
import type { AddressInfo } from "node:net";
|
|
20
23
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
21
|
-
import {
|
|
24
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
25
|
+
import { hasAmbientCredentials } from "@procedures/client";
|
|
26
|
+
import { BodyError, readJsonBody } from "@procedures/client/node";
|
|
22
27
|
import type { HttpTransportOptions } from "../types.js";
|
|
28
|
+
import { MCP_HTTP_LIMITS, guardMcpRequest } from "./guard.js";
|
|
29
|
+
|
|
30
|
+
/** The limits of the sessions of the endpoint (CLI-35). The HTTP options win over them. */
|
|
31
|
+
export interface McpHttpSessionOptions {
|
|
32
|
+
/** The most sessions at one time. The default is no limit. */
|
|
33
|
+
readonly maxSessions?: number | undefined;
|
|
34
|
+
/** The largest body of a request. The default is 4 MiB, the limit of the SDK. */
|
|
35
|
+
readonly maxBodyBytes?: number | undefined;
|
|
36
|
+
/** The sessions that have a task in progress: the session limit does not close them. */
|
|
37
|
+
readonly busySessions?: (() => ReadonlySet<string>) | undefined;
|
|
38
|
+
}
|
|
23
39
|
|
|
24
40
|
/** The HTTP endpoint of an MCP server, with a session for each client. */
|
|
25
41
|
export interface McpHttpTransport {
|
|
26
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* This function starts to listen, when the endpoint has a server of its own. It gives the URL, or the path of a mounted endpoint.
|
|
44
|
+
* @deprecated The next MINOR removes the listener of the endpoint (CLI-11): then the endpoint is always mounted.
|
|
45
|
+
*/
|
|
27
46
|
listen(): Promise<string>;
|
|
28
47
|
/**
|
|
29
48
|
* This function answers a request of the path of the endpoint and gives true. It gives false for
|
|
@@ -36,6 +55,11 @@ export interface McpHttpTransport {
|
|
|
36
55
|
close(): Promise<void>;
|
|
37
56
|
}
|
|
38
57
|
|
|
58
|
+
/** True for a limit: an integer of 1 or more, or no limit (`Infinity`). */
|
|
59
|
+
function isLimit(value: number): boolean {
|
|
60
|
+
return value === Number.POSITIVE_INFINITY || (Number.isInteger(value) && value >= 1);
|
|
61
|
+
}
|
|
62
|
+
|
|
39
63
|
/**
|
|
40
64
|
* This function makes the Streamable HTTP endpoint of an MCP server. `connect` connects the
|
|
41
65
|
* transport of a new session to an MCP server of its own.
|
|
@@ -43,6 +67,7 @@ export interface McpHttpTransport {
|
|
|
43
67
|
export function createHttpTransport(
|
|
44
68
|
options: HttpTransportOptions,
|
|
45
69
|
connect: (transport: StreamableHTTPServerTransport) => Promise<void>,
|
|
70
|
+
limits: McpHttpSessionOptions = {},
|
|
46
71
|
): McpHttpTransport {
|
|
47
72
|
const path = options.path ?? "/mcp";
|
|
48
73
|
const host = options.host ?? "127.0.0.1";
|
|
@@ -50,29 +75,136 @@ export function createHttpTransport(
|
|
|
50
75
|
const owned = !mounted && options.server === undefined;
|
|
51
76
|
const server: HttpServer | undefined = mounted ? undefined : (options.server ?? createServer());
|
|
52
77
|
const sessions = new Map<string, StreamableHTTPServerTransport>();
|
|
78
|
+
/** The time of the last request of each session: the session limit closes the session that was idle longest */
|
|
79
|
+
const lastUsed = new Map<string, number>();
|
|
80
|
+
/** The open responses of each session (a call, a GET stream): a session with one is not idle */
|
|
81
|
+
const openResponses = new Map<string, number>();
|
|
82
|
+
/** The new sessions that do not have their id yet: the session limit counts them */
|
|
83
|
+
let pending = 0;
|
|
84
|
+
const maxSessions = options.maxSessions ?? limits.maxSessions ?? MCP_HTTP_LIMITS.maxSessions;
|
|
85
|
+
const maxBodyBytes = options.maxBodyBytes ?? limits.maxBodyBytes ?? MCP_HTTP_LIMITS.maxBodyBytes;
|
|
86
|
+
if (!isLimit(maxSessions)) throw new RangeError(`maxSessions must be an integer of 1 or more, or Infinity, not ${String(maxSessions)}`);
|
|
87
|
+
if (!Number.isInteger(maxBodyBytes) || maxBodyBytes < 1) throw new RangeError(`maxBodyBytes must be an integer of 1 or more, not ${String(maxBodyBytes)}`);
|
|
53
88
|
|
|
54
|
-
const refuse = (res: ServerResponse, status: number, code: string, message: string): void => {
|
|
89
|
+
const refuse = (res: ServerResponse, status: number, code: string, message: string, headers: Readonly<Record<string, string>> = {}): void => {
|
|
55
90
|
res.statusCode = status;
|
|
56
91
|
res.setHeader("content-type", "application/json");
|
|
92
|
+
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
|
|
57
93
|
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32001, message, data: { code } }, id: null }));
|
|
58
94
|
};
|
|
59
95
|
|
|
60
|
-
/**
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
sessions.set(id, transport);
|
|
69
|
-
},
|
|
96
|
+
/** This function counts an open response of a session until the response closes. */
|
|
97
|
+
const track = (sessionId: string, res: ServerResponse): void => {
|
|
98
|
+
openResponses.set(sessionId, (openResponses.get(sessionId) ?? 0) + 1);
|
|
99
|
+
res.once("close", () => {
|
|
100
|
+
const left = (openResponses.get(sessionId) ?? 1) - 1;
|
|
101
|
+
if (left > 0) openResponses.set(sessionId, left);
|
|
102
|
+
else openResponses.delete(sessionId);
|
|
103
|
+
if (sessions.has(sessionId)) lastUsed.set(sessionId, Date.now());
|
|
70
104
|
});
|
|
71
|
-
|
|
72
|
-
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const forget = (sessionId: string): void => {
|
|
108
|
+
sessions.delete(sessionId);
|
|
109
|
+
lastUsed.delete(sessionId);
|
|
110
|
+
openResponses.delete(sessionId);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* This function closes the session that was idle longest: no task in progress and no open
|
|
115
|
+
* response (a call or a GET stream). It gives false when each session is busy.
|
|
116
|
+
*/
|
|
117
|
+
const evict = async (): Promise<boolean> => {
|
|
118
|
+
const busy = limits.busySessions?.() ?? new Set<string>();
|
|
119
|
+
let oldest: string | undefined;
|
|
120
|
+
for (const id of sessions.keys()) {
|
|
121
|
+
if (busy.has(id) || (openResponses.get(id) ?? 0) > 0) continue;
|
|
122
|
+
if (oldest === undefined || (lastUsed.get(id) ?? 0) < (lastUsed.get(oldest) ?? 0)) oldest = id;
|
|
123
|
+
}
|
|
124
|
+
if (oldest === undefined) return false;
|
|
125
|
+
const transport = sessions.get(oldest);
|
|
126
|
+
forget(oldest);
|
|
127
|
+
await transport?.close().catch(() => undefined);
|
|
128
|
+
return true;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/** This function starts a session for an `initialize` request whose body it read. */
|
|
132
|
+
const open = async (req: IncomingMessage, res: ServerResponse, body: unknown): Promise<void> => {
|
|
133
|
+
// The limit counts the sessions and the new sessions without an id, so the awaits below cannot
|
|
134
|
+
// pass it. A new session leaves `pending` when it gets its id, or when it gets no session
|
|
135
|
+
pending++;
|
|
136
|
+
let counted = true;
|
|
137
|
+
const release = (): void => {
|
|
138
|
+
if (!counted) return;
|
|
139
|
+
counted = false;
|
|
140
|
+
pending--;
|
|
73
141
|
};
|
|
74
|
-
|
|
75
|
-
|
|
142
|
+
let transport: StreamableHTTPServerTransport | undefined;
|
|
143
|
+
try {
|
|
144
|
+
while (sessions.size + pending > maxSessions) {
|
|
145
|
+
if (!(await evict())) {
|
|
146
|
+
refuse(res, 503, "SESSIONS_FULL", "Each session of the server is busy (a task, a call or a stream): try again later", {
|
|
147
|
+
"retry-after": String(MCP_HTTP_LIMITS.retryAfterSeconds),
|
|
148
|
+
});
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const created: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
|
|
153
|
+
sessionIdGenerator: () => randomUUID(),
|
|
154
|
+
onsessioninitialized: (id) => {
|
|
155
|
+
release();
|
|
156
|
+
sessions.set(id, created);
|
|
157
|
+
lastUsed.set(id, Date.now());
|
|
158
|
+
track(id, res);
|
|
159
|
+
},
|
|
160
|
+
// The SDK reads the body of each later request of the session to the same limit
|
|
161
|
+
maxRequestBodySize: maxBodyBytes,
|
|
162
|
+
});
|
|
163
|
+
transport = created;
|
|
164
|
+
created.onclose = () => {
|
|
165
|
+
if (created.sessionId) forget(created.sessionId);
|
|
166
|
+
};
|
|
167
|
+
await connect(created);
|
|
168
|
+
await created.handleRequest(req, res, body);
|
|
169
|
+
} finally {
|
|
170
|
+
release();
|
|
171
|
+
// No session started (the SDK refused the initialize with 406 or 415, or connect threw): the server closes
|
|
172
|
+
if (transport && !transport.sessionId) await transport.close().catch(() => undefined);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* This function answers a request: in its session, or in a new session for an `initialize`. Only
|
|
178
|
+
* an `initialize` makes a session, so a stray POST makes no MCP server (CLI-35).
|
|
179
|
+
*/
|
|
180
|
+
const serve = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
|
181
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
182
|
+
if (typeof sessionId === "string" || req.method !== "POST") {
|
|
183
|
+
const transport = typeof sessionId === "string" ? sessions.get(sessionId) : undefined;
|
|
184
|
+
if (!transport || typeof sessionId !== "string") {
|
|
185
|
+
refuse(res, 404, "SESSION_NOT_FOUND", "No session: start one with an initialize request");
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
lastUsed.set(sessionId, Date.now());
|
|
189
|
+
// A call or a GET stream keeps its session busy until its response closes
|
|
190
|
+
track(sessionId, res);
|
|
191
|
+
await transport.handleRequest(req, res);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
let body: unknown;
|
|
195
|
+
try {
|
|
196
|
+
body = await readJsonBody(req, maxBodyBytes);
|
|
197
|
+
} catch (error) {
|
|
198
|
+
const status = error instanceof BodyError ? error.httpStatus : 400;
|
|
199
|
+
refuse(res, status, status === 413 ? "PAYLOAD_TOO_LARGE" : "BAD_REQUEST", error instanceof Error ? error.message : String(error));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const initializes = Array.isArray(body) ? body.some((message) => isInitializeRequest(message)) : isInitializeRequest(body);
|
|
203
|
+
if (!initializes) {
|
|
204
|
+
refuse(res, 400, "BAD_REQUEST", "No session: the first request of a session is initialize, or give the mcp-session-id header");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
await open(req, res, body);
|
|
76
208
|
};
|
|
77
209
|
|
|
78
210
|
const handle = (req: IncomingMessage, res: ServerResponse): boolean => {
|
|
@@ -82,29 +214,23 @@ export function createHttpTransport(
|
|
|
82
214
|
refuse(res, 404, "NOT_FOUND", `No MCP endpoint at ${url.pathname}`);
|
|
83
215
|
return true;
|
|
84
216
|
}
|
|
85
|
-
// A web page must not reach the tools: the host and the origin of the request
|
|
86
|
-
// reads cookies trusts a request with ambient credentials only from a
|
|
217
|
+
// A web page must not reach the tools: the host and the origin of the request, then the token
|
|
218
|
+
// (guard.ts). A server that reads cookies trusts a request with ambient credentials only from a
|
|
219
|
+
// named origin (CSRF)
|
|
87
220
|
const ambient = options.ambientCredentials === "always" || hasAmbientCredentials(req.headers);
|
|
88
|
-
const guard =
|
|
221
|
+
const guard = guardMcpRequest(req, {
|
|
222
|
+
...(options.token !== undefined ? { token: options.token } : {}),
|
|
223
|
+
...(options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}),
|
|
224
|
+
...(options.allowedHosts ? { allowedHosts: options.allowedHosts } : {}),
|
|
225
|
+
ambient,
|
|
226
|
+
});
|
|
89
227
|
if (!guard.ok) {
|
|
90
|
-
refuse(res, guard.status, guard.code, guard.message);
|
|
91
|
-
return true;
|
|
92
|
-
}
|
|
93
|
-
if (options.token !== undefined && !tokenMatches(options.token, bearerOf(req.headers["authorization"]))) {
|
|
94
|
-
refuse(res, 401, "UNAUTHORIZED", "Unauthorized: this server requires its token");
|
|
228
|
+
refuse(res, guard.status, guard.code, guard.message, guard.headers);
|
|
95
229
|
return true;
|
|
96
230
|
}
|
|
97
|
-
|
|
98
|
-
.
|
|
99
|
-
|
|
100
|
-
refuse(res, 404, "SESSION_NOT_FOUND", "No session: start one with an initialize request");
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
return transport.handleRequest(req, res);
|
|
104
|
-
})
|
|
105
|
-
.catch((error: unknown) => {
|
|
106
|
-
if (!res.headersSent) refuse(res, 500, "INTERNAL_ERROR", error instanceof Error ? error.message : String(error));
|
|
107
|
-
});
|
|
231
|
+
serve(req, res).catch((error: unknown) => {
|
|
232
|
+
if (!res.headersSent) refuse(res, 500, "INTERNAL_ERROR", error instanceof Error ? error.message : String(error));
|
|
233
|
+
});
|
|
108
234
|
return true;
|
|
109
235
|
};
|
|
110
236
|
const onRequest = (req: IncomingMessage, res: ServerResponse): void => {
|
|
@@ -136,6 +262,8 @@ export function createHttpTransport(
|
|
|
136
262
|
server?.off("request", onRequest);
|
|
137
263
|
const open = [...sessions.values()];
|
|
138
264
|
sessions.clear();
|
|
265
|
+
lastUsed.clear();
|
|
266
|
+
openResponses.clear();
|
|
139
267
|
await Promise.all(open.map((transport) => transport.close().catch(() => undefined)));
|
|
140
268
|
if (owned && server?.listening) {
|
|
141
269
|
await new Promise<void>((resolve) => {
|