@bensandee/mcp-server 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +338 -2
- package/dist/index.d.mts +18 -0
- package/dist/index.mjs +831 -0
- package/dist/testing.d.mts +101 -0
- package/dist/testing.mjs +172 -0
- package/dist/types-B7gttgCL.d.mts +140 -0
- package/package.json +52 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { bodyLimit } from "hono/body-limit";
|
|
3
|
+
import { StreamableHTTPTransport } from "@hono/mcp";
|
|
4
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
5
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { HTTPException } from "hono/http-exception";
|
|
7
|
+
import { LRUCache } from "lru-cache";
|
|
8
|
+
import { rateLimiter } from "hono-rate-limiter";
|
|
9
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
10
|
+
import { createLocalJWKSet, createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors, jwtVerify } from "jose";
|
|
11
|
+
// src/document.ts
|
|
12
|
+
/** The path prefix the protected resource document is served under. */
|
|
13
|
+
const DOCUMENT_PREFIX = "/.well-known/oauth-protected-resource";
|
|
14
|
+
/**
|
|
15
|
+
* Builds the document a client reads to find the endpoint and its issuers.
|
|
16
|
+
*
|
|
17
|
+
* `scopes_supported` is left out when there are no scopes, because an empty list
|
|
18
|
+
* tells a client to ask for nothing.
|
|
19
|
+
*/
|
|
20
|
+
function buildResourceDocument(options) {
|
|
21
|
+
const scopes = options.scopes ?? [];
|
|
22
|
+
const document = {
|
|
23
|
+
resource: options.origin + options.path,
|
|
24
|
+
authorization_servers: options.issuers.map((issuer) => issuer.issuer),
|
|
25
|
+
bearer_methods_supported: ["header"]
|
|
26
|
+
};
|
|
27
|
+
return scopes.length === 0 ? document : {
|
|
28
|
+
...document,
|
|
29
|
+
scopes_supported: scopes
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** The route the document is served at for an endpoint at `path`. */
|
|
33
|
+
function documentPath(path) {
|
|
34
|
+
return `${DOCUMENT_PREFIX}${path}`;
|
|
35
|
+
}
|
|
36
|
+
/** The document's full URL, which the challenge names as its metadata. */
|
|
37
|
+
function documentUrl(origin, path) {
|
|
38
|
+
return `${origin}${documentPath(path)}`;
|
|
39
|
+
}
|
|
40
|
+
// src/messages.ts
|
|
41
|
+
/**
|
|
42
|
+
* The fixed texts the package answers with.
|
|
43
|
+
*
|
|
44
|
+
* Every refusal, limit and fault gets one of these, so no reason for a refusal
|
|
45
|
+
* and no error's own text can reach a caller.
|
|
46
|
+
*/
|
|
47
|
+
/**
|
|
48
|
+
* The fixed body of each error status, keyed by the status that sends it.
|
|
49
|
+
*
|
|
50
|
+
* One body per status, the same for every reason behind it: a caller can tell a
|
|
51
|
+
* refusal from a server fault, and nothing more.
|
|
52
|
+
*/
|
|
53
|
+
const ERROR_BODIES = {
|
|
54
|
+
/** The caller sent a request the MCP transport rejected. */
|
|
55
|
+
400: { error: "bad_request" },
|
|
56
|
+
/** No token, or a token that was refused. */
|
|
57
|
+
401: { error: "unauthorized" },
|
|
58
|
+
/** A valid token whose user `identify` did not allow. */
|
|
59
|
+
403: { error: "forbidden" },
|
|
60
|
+
/** No route of this package serves the path. */
|
|
61
|
+
404: { error: "not_found" },
|
|
62
|
+
/** The endpoint serves POST, and this was another method. */
|
|
63
|
+
405: { error: "method_not_allowed" },
|
|
64
|
+
/** The body is larger than the limit allows. */
|
|
65
|
+
413: { error: "payload_too_large" },
|
|
66
|
+
/** A rate limit is spent. */
|
|
67
|
+
429: { error: "too_many_requests" },
|
|
68
|
+
/** The endpoint could not complete its own work. */
|
|
69
|
+
503: { error: "unavailable" }
|
|
70
|
+
};
|
|
71
|
+
/** The text of a tool result that stands in for a tool that threw. */
|
|
72
|
+
const TOOL_FAULT_TEXT = "The tool failed.";
|
|
73
|
+
/** The JSON-RPC code for a request that is structurally wrong, such as a batch. */
|
|
74
|
+
const BATCH_NOT_SUPPORTED_CODE = -32600;
|
|
75
|
+
/** The text of a refused JSON-RPC batch. */
|
|
76
|
+
const BATCH_NOT_SUPPORTED_TEXT = "Batch requests are not supported.";
|
|
77
|
+
/** The JSON-RPC code for a body that is not JSON. */
|
|
78
|
+
const PARSE_ERROR_CODE = -32700;
|
|
79
|
+
/** The text of a body that is not JSON. */
|
|
80
|
+
const PARSE_ERROR_TEXT = "Parse error.";
|
|
81
|
+
/** Builds a JSON-RPC error response with a null id. */
|
|
82
|
+
function jsonRpcErrorBody(detail) {
|
|
83
|
+
return {
|
|
84
|
+
jsonrpc: "2.0",
|
|
85
|
+
id: null,
|
|
86
|
+
error: detail
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// src/endpoint.ts
|
|
90
|
+
/**
|
|
91
|
+
* Builds the handler that serves one stateless MCP POST.
|
|
92
|
+
*
|
|
93
|
+
* Each request gets a fresh MCP server and transport, answered as one JSON body
|
|
94
|
+
* with no session id and no stream. A tool that throws becomes a fixed tool
|
|
95
|
+
* error, and a request the transport rejects gets its own status back with a
|
|
96
|
+
* fixed body, so no error's text reaches the caller.
|
|
97
|
+
*/
|
|
98
|
+
function createEndpointHandler(options) {
|
|
99
|
+
return async (c) => {
|
|
100
|
+
const body = await readBody(c);
|
|
101
|
+
if (body.kind === "unreadable") return c.json(jsonRpcErrorBody({
|
|
102
|
+
code: PARSE_ERROR_CODE,
|
|
103
|
+
message: PARSE_ERROR_TEXT
|
|
104
|
+
}), 400);
|
|
105
|
+
if (body.kind === "batch") return c.json(jsonRpcErrorBody({
|
|
106
|
+
code: BATCH_NOT_SUPPORTED_CODE,
|
|
107
|
+
message: BATCH_NOT_SUPPORTED_TEXT
|
|
108
|
+
}), 400);
|
|
109
|
+
const transport = new StreamableHTTPTransport({ enableJsonResponse: true });
|
|
110
|
+
const server = createServer(c, options);
|
|
111
|
+
try {
|
|
112
|
+
await server.connect(transport);
|
|
113
|
+
return answer(await transport.handleRequest(c, body.value), c);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
const status = clientErrorStatus(error);
|
|
116
|
+
if (status === void 0) throw error;
|
|
117
|
+
return c.json(ERROR_BODIES[400], status);
|
|
118
|
+
} finally {
|
|
119
|
+
await server.close();
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Replaces the transport's empty answer with an empty-body 202.
|
|
125
|
+
*
|
|
126
|
+
* `@hono/mcp` 0.3.5 answers a POST that held only notifications with a 202 whose
|
|
127
|
+
* body is the JSON text `null`, and the spec asks for no body at all.
|
|
128
|
+
*/
|
|
129
|
+
function answer(response, c) {
|
|
130
|
+
if (response === void 0 || response.status === 202) return c.body(null, 202);
|
|
131
|
+
return response;
|
|
132
|
+
}
|
|
133
|
+
/** Parses the request body, keeping a batch and an unreadable body apart. */
|
|
134
|
+
async function readBody(c) {
|
|
135
|
+
let value;
|
|
136
|
+
try {
|
|
137
|
+
value = await c.req.json();
|
|
138
|
+
} catch {
|
|
139
|
+
return { kind: "unreadable" };
|
|
140
|
+
}
|
|
141
|
+
return Array.isArray(value) ? { kind: "batch" } : {
|
|
142
|
+
kind: "message",
|
|
143
|
+
value
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Builds the MCP server for one request and wires the app's tools into it.
|
|
148
|
+
*
|
|
149
|
+
* The tool call handler catches everything the app throws, so a tool fault is a
|
|
150
|
+
* result the client can read rather than a JSON-RPC error that would carry the
|
|
151
|
+
* error's own text.
|
|
152
|
+
*/
|
|
153
|
+
function createServer(c, options) {
|
|
154
|
+
const server = new Server({
|
|
155
|
+
name: options.server.name,
|
|
156
|
+
version: options.server.version
|
|
157
|
+
}, {
|
|
158
|
+
capabilities: { tools: {} },
|
|
159
|
+
instructions: options.server.instructions
|
|
160
|
+
});
|
|
161
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [...options.tools] }));
|
|
162
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
163
|
+
const call = {
|
|
164
|
+
name: request.params.name,
|
|
165
|
+
arguments: request.params.arguments ?? {}
|
|
166
|
+
};
|
|
167
|
+
try {
|
|
168
|
+
return await options.callTool(call, c.get("mcpUser"));
|
|
169
|
+
} catch (error) {
|
|
170
|
+
options.emit({
|
|
171
|
+
type: "tool_error",
|
|
172
|
+
tool: call.name,
|
|
173
|
+
error
|
|
174
|
+
});
|
|
175
|
+
return toolFaultResult();
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
return server;
|
|
179
|
+
}
|
|
180
|
+
/** The result a tool call answers with when the app's tool threw. */
|
|
181
|
+
function toolFaultResult() {
|
|
182
|
+
return {
|
|
183
|
+
content: [{
|
|
184
|
+
type: "text",
|
|
185
|
+
text: TOOL_FAULT_TEXT
|
|
186
|
+
}],
|
|
187
|
+
isError: true
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The status of a 4xx `HTTPException`, or `undefined` for anything else.
|
|
192
|
+
*
|
|
193
|
+
* The transport raises one for a wrong `Accept` or `Content-Type` header, a body
|
|
194
|
+
* that is not a JSON-RPC message, or a protocol version it does not support. All
|
|
195
|
+
* of those are the caller's mistake, so the caller gets its own status back with
|
|
196
|
+
* a fixed body and the request is not reported as a fault of the server. Any
|
|
197
|
+
* other throw is left to the caller of this handler.
|
|
198
|
+
*/
|
|
199
|
+
function clientErrorStatus(error) {
|
|
200
|
+
if (!(error instanceof HTTPException)) return void 0;
|
|
201
|
+
if (error.status < 400 || error.status >= 500) return void 0;
|
|
202
|
+
return error.status;
|
|
203
|
+
}
|
|
204
|
+
// src/errors.ts
|
|
205
|
+
/** Thrown when the endpoint options are invalid at construction time. */
|
|
206
|
+
var McpEndpointConfigError = class extends Error {};
|
|
207
|
+
// src/flood.ts
|
|
208
|
+
/** Milliseconds in a second, for the seconds a rate limit header carries. */
|
|
209
|
+
const MILLISECONDS_PER_SECOND = 1e3;
|
|
210
|
+
/**
|
|
211
|
+
* Builds the flood ceiling and the store of recently accepted tokens.
|
|
212
|
+
*
|
|
213
|
+
* The accepted store takes its clock from `Date.now()`, because `lru-cache`
|
|
214
|
+
* otherwise reads the real `performance` object, which a faked clock never
|
|
215
|
+
* moves. Its resolution is zero for the same reason: the cache's own one second
|
|
216
|
+
* debounce of the clock would hold an expired entry live.
|
|
217
|
+
*/
|
|
218
|
+
function createFloodCeiling(options) {
|
|
219
|
+
const accepted = new LRUCache({
|
|
220
|
+
max: options.maxAccepted,
|
|
221
|
+
perf: { now: () => Date.now() },
|
|
222
|
+
ttlResolution: 0
|
|
223
|
+
});
|
|
224
|
+
let windowStart = Date.now();
|
|
225
|
+
let refusals = 0;
|
|
226
|
+
let announced = false;
|
|
227
|
+
/** Closes a window that has run its length, opening the next one. */
|
|
228
|
+
const closeWindow = (now) => {
|
|
229
|
+
if (now - windowStart < options.windowMs) return;
|
|
230
|
+
windowStart = now;
|
|
231
|
+
refusals = 0;
|
|
232
|
+
announced = false;
|
|
233
|
+
};
|
|
234
|
+
const countRefusal = (now) => {
|
|
235
|
+
closeWindow(now);
|
|
236
|
+
refusals += 1;
|
|
237
|
+
};
|
|
238
|
+
/** True when the request carries a token the store recently accepted. */
|
|
239
|
+
const passes = (c) => {
|
|
240
|
+
const key = c.get("tokenKey");
|
|
241
|
+
return key !== void 0 && accepted.has(key);
|
|
242
|
+
};
|
|
243
|
+
/** Answers 429 with the headers `hono-rate-limiter` writes for draft-7. */
|
|
244
|
+
const refuse = (c, now) => {
|
|
245
|
+
if (!announced) {
|
|
246
|
+
announced = true;
|
|
247
|
+
options.emit({
|
|
248
|
+
type: "limit",
|
|
249
|
+
limit: "flood"
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
const remaining = Math.max(options.limit - refusals, 0);
|
|
253
|
+
const windowSeconds = Math.ceil(options.windowMs / MILLISECONDS_PER_SECOND);
|
|
254
|
+
const resetSeconds = Math.max(Math.ceil((windowStart + options.windowMs - now) / MILLISECONDS_PER_SECOND), 0);
|
|
255
|
+
c.header("RateLimit-Policy", `${options.limit};w=${windowSeconds}`);
|
|
256
|
+
c.header("RateLimit", `limit=${options.limit}, remaining=${remaining}, reset=${resetSeconds}`);
|
|
257
|
+
c.header("Retry-After", String(resetSeconds));
|
|
258
|
+
return c.json(ERROR_BODIES[429], 429);
|
|
259
|
+
};
|
|
260
|
+
const middleware = async (c, next) => {
|
|
261
|
+
const now = Date.now();
|
|
262
|
+
closeWindow(now);
|
|
263
|
+
if (refusals >= options.limit && !passes(c)) return refuse(c, now);
|
|
264
|
+
await next();
|
|
265
|
+
const status = c.res.status;
|
|
266
|
+
if (status === 401 || status === 403) countRefusal(Date.now());
|
|
267
|
+
};
|
|
268
|
+
const recordAccepted = (tokenKey, expiresAt) => {
|
|
269
|
+
const ttl = Math.min(options.windowMs, expiresAt - Date.now());
|
|
270
|
+
if (ttl <= 0) return;
|
|
271
|
+
accepted.set(tokenKey, true, { ttl });
|
|
272
|
+
};
|
|
273
|
+
return {
|
|
274
|
+
middleware,
|
|
275
|
+
recordAccepted,
|
|
276
|
+
acceptedCount: () => accepted.size
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
// src/store.ts
|
|
280
|
+
/**
|
|
281
|
+
* The cap a `CappedStore` keeps when none is given.
|
|
282
|
+
*
|
|
283
|
+
* `hono-rate-limiter`'s own store grows without limit, so one entry per junk
|
|
284
|
+
* token could exhaust the process; this cap bounds that memory.
|
|
285
|
+
*/
|
|
286
|
+
const DEFAULT_MAX_KEYS = 1e4;
|
|
287
|
+
/**
|
|
288
|
+
* A fixed-window counter store for `hono-rate-limiter`, capped at `maxKeys`.
|
|
289
|
+
*
|
|
290
|
+
* Evicting a key only drops that key's count, which starts it over; the count
|
|
291
|
+
* exists to stop endless retries, so a reset key is a fresh start, not a hole.
|
|
292
|
+
*/
|
|
293
|
+
var CappedStore = class {
|
|
294
|
+
#entries;
|
|
295
|
+
#windowMs = 0;
|
|
296
|
+
constructor(options = {}) {
|
|
297
|
+
this.#entries = new LRUCache({ max: options.maxKeys ?? 1e4 });
|
|
298
|
+
}
|
|
299
|
+
/** The number of keys currently held. */
|
|
300
|
+
get size() {
|
|
301
|
+
return this.#entries.size;
|
|
302
|
+
}
|
|
303
|
+
/** Takes the window length from the middleware's options. */
|
|
304
|
+
init(options) {
|
|
305
|
+
this.#windowMs = options.windowMs;
|
|
306
|
+
}
|
|
307
|
+
/** Counts one hit, opening a new window when the key is new or its window closed. */
|
|
308
|
+
increment(key) {
|
|
309
|
+
const now = Date.now();
|
|
310
|
+
const entry = this.#entries.get(key);
|
|
311
|
+
if (entry !== void 0 && entry.resetTime.getTime() > now) {
|
|
312
|
+
entry.hits += 1;
|
|
313
|
+
return {
|
|
314
|
+
totalHits: entry.hits,
|
|
315
|
+
resetTime: entry.resetTime
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
const resetTime = new Date(now + this.#windowMs);
|
|
319
|
+
this.#entries.set(key, {
|
|
320
|
+
hits: 1,
|
|
321
|
+
resetTime
|
|
322
|
+
});
|
|
323
|
+
return {
|
|
324
|
+
totalHits: 1,
|
|
325
|
+
resetTime
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/** Lowers a live key's count by one, stopping at zero. */
|
|
329
|
+
decrement(key) {
|
|
330
|
+
const entry = this.#entries.get(key);
|
|
331
|
+
if (entry === void 0 || entry.resetTime.getTime() <= Date.now()) return;
|
|
332
|
+
entry.hits = Math.max(0, entry.hits - 1);
|
|
333
|
+
}
|
|
334
|
+
/** Forgets one key. */
|
|
335
|
+
resetKey(key) {
|
|
336
|
+
this.#entries.delete(key);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
// src/limits.ts
|
|
340
|
+
/** True for the statuses the package sends when it refuses a request. */
|
|
341
|
+
function isRefusal(status) {
|
|
342
|
+
return status === 401 || status === 403;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Builds the per-token refusal limit.
|
|
346
|
+
*
|
|
347
|
+
* `hono-rate-limiter` counts every request, then gives back the count of a
|
|
348
|
+
* request it calls successful. Here a success is any status other than 401 or
|
|
349
|
+
* 403, so only refused requests spend a token's count; a token that works, a
|
|
350
|
+
* 413, or a fault leaves the count where it was.
|
|
351
|
+
*
|
|
352
|
+
* A request with no `Authorization` header is skipped before the key is read.
|
|
353
|
+
* That is the same test the middleware before this one makes before it sets the
|
|
354
|
+
* token key, so every request that reaches the key generator carries one.
|
|
355
|
+
*/
|
|
356
|
+
function createRefusalLimit(options) {
|
|
357
|
+
return rateLimiter({
|
|
358
|
+
windowMs: options.windowMs,
|
|
359
|
+
limit: options.limit,
|
|
360
|
+
standardHeaders: "draft-7",
|
|
361
|
+
store: new CappedStore({ maxKeys: DEFAULT_MAX_KEYS }),
|
|
362
|
+
skip: (c) => c.req.header("authorization") === void 0,
|
|
363
|
+
skipSuccessfulRequests: true,
|
|
364
|
+
requestWasSuccessful: (c) => !isRefusal(c.res.status),
|
|
365
|
+
keyGenerator: (c) => c.get("tokenKey"),
|
|
366
|
+
handler: (c) => {
|
|
367
|
+
options.emit({
|
|
368
|
+
type: "limit",
|
|
369
|
+
limit: "refusals"
|
|
370
|
+
});
|
|
371
|
+
return c.json(ERROR_BODIES[429], 429);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Builds the per-caller limit.
|
|
377
|
+
*
|
|
378
|
+
* It runs after sign-in, so every request that reaches it has a user, and every
|
|
379
|
+
* request counts: a caller spends the limit whatever the answer turns out to be.
|
|
380
|
+
*/
|
|
381
|
+
function createCallerLimit(options) {
|
|
382
|
+
return rateLimiter({
|
|
383
|
+
windowMs: options.windowMs,
|
|
384
|
+
limit: options.limit,
|
|
385
|
+
standardHeaders: "draft-7",
|
|
386
|
+
store: new CappedStore({ maxKeys: DEFAULT_MAX_KEYS }),
|
|
387
|
+
keyGenerator: (c) => options.callerKey(c.get("mcpUser")),
|
|
388
|
+
handler: (c) => {
|
|
389
|
+
options.emit({
|
|
390
|
+
type: "limit",
|
|
391
|
+
limit: "callers"
|
|
392
|
+
});
|
|
393
|
+
return c.json(ERROR_BODIES[429], 429);
|
|
394
|
+
}
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
// src/token-key.ts
|
|
398
|
+
/**
|
|
399
|
+
* Builds a keyed hash for an `Authorization` header.
|
|
400
|
+
*
|
|
401
|
+
* The key is made once per call and never leaves this closure, so a key stays
|
|
402
|
+
* useless outside the process that made it: an attacker who reads a key from a
|
|
403
|
+
* log cannot match it to a token.
|
|
404
|
+
*/
|
|
405
|
+
function createTokenKeyer() {
|
|
406
|
+
const secret = randomBytes(32);
|
|
407
|
+
return (authorization) => createHmac("sha256", secret).update(authorization).digest("hex");
|
|
408
|
+
}
|
|
409
|
+
// src/verify.ts
|
|
410
|
+
/** The bearer scheme in any case, one or more spaces, then a token with no spaces. */
|
|
411
|
+
const BEARER_PATTERN = /^bearer +(\S+)$/i;
|
|
412
|
+
/** The clock skew a token's `exp` may be past, in seconds. */
|
|
413
|
+
const CLOCK_TOLERANCE = 30;
|
|
414
|
+
/**
|
|
415
|
+
* Marks a failure that came from the key resolver rather than from the token.
|
|
416
|
+
*
|
|
417
|
+
* The wrapper around each resolver raises it, so the caller can tell a key set
|
|
418
|
+
* it could not read from a token it should refuse: a key fault is always the
|
|
419
|
+
* key server's failure, never the token's.
|
|
420
|
+
*/
|
|
421
|
+
var KeyFault = class extends Error {
|
|
422
|
+
/** The error the resolver raised. */
|
|
423
|
+
original;
|
|
424
|
+
constructor(original) {
|
|
425
|
+
super("The token key resolver failed.");
|
|
426
|
+
this.original = original;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
/**
|
|
430
|
+
* Reads the token from an `Authorization` header.
|
|
431
|
+
*
|
|
432
|
+
* The scheme matches in any case, as RFC 9110 requires, and needs one or more
|
|
433
|
+
* spaces before a token that holds no spaces of its own. Anything else gives
|
|
434
|
+
* `undefined`, so no token.
|
|
435
|
+
*/
|
|
436
|
+
function readBearer(header) {
|
|
437
|
+
if (header === void 0) return void 0;
|
|
438
|
+
return BEARER_PATTERN.exec(header)?.[1];
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Builds a checker for bearer tokens.
|
|
442
|
+
*
|
|
443
|
+
* Each issuer's key resolver is made then and there, so no key is fetched until
|
|
444
|
+
* a token gets far enough to need one. A token is checked in a fixed order:
|
|
445
|
+
* header and claim pre-checks that need no key, then the signature, expiry,
|
|
446
|
+
* type and subject checks that do.
|
|
447
|
+
*/
|
|
448
|
+
function createTokenChecker(options) {
|
|
449
|
+
const entries = options.issuers.map(createEntry);
|
|
450
|
+
return (token) => checkToken(token, entries, options.requireAccessTokenType);
|
|
451
|
+
}
|
|
452
|
+
function createEntry(issuer) {
|
|
453
|
+
return {
|
|
454
|
+
issuer: issuer.issuer,
|
|
455
|
+
audiences: issuer.audiences,
|
|
456
|
+
resolve: "jwks" in issuer ? createLocalJWKSet(issuer.jwks) : createRemoteJWKSet(new URL(issuer.jwksUrl))
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
async function checkToken(token, entries, requireAccessTokenType) {
|
|
460
|
+
const decoded = decodeToken(token);
|
|
461
|
+
if (decoded === void 0) return refused("not_jwt");
|
|
462
|
+
const { header, payload } = decoded;
|
|
463
|
+
if (header.alg !== "RS256") return refused("algorithm");
|
|
464
|
+
if (typeof header.kid !== "string" || header.kid === "") return refused("key_id");
|
|
465
|
+
const entry = entries.find((candidate) => candidate.issuer === payload.iss);
|
|
466
|
+
if (entry === void 0) return refused("issuer");
|
|
467
|
+
if (!hasAudience(payload.aud, entry.audiences)) return refused("audience");
|
|
468
|
+
return verifySignature(token, entry, requireAccessTokenType);
|
|
469
|
+
}
|
|
470
|
+
async function verifySignature(token, entry, requireAccessTokenType) {
|
|
471
|
+
let verified;
|
|
472
|
+
try {
|
|
473
|
+
verified = (await jwtVerify(token, wrapResolver(entry.resolve), verifyOptions(entry, requireAccessTokenType))).payload;
|
|
474
|
+
} catch (error) {
|
|
475
|
+
if (error instanceof KeyFault) return {
|
|
476
|
+
kind: "key_fault",
|
|
477
|
+
error: error.original
|
|
478
|
+
};
|
|
479
|
+
return refused(refusalReason(error));
|
|
480
|
+
}
|
|
481
|
+
if (typeof verified.sub !== "string" || verified.sub === "") return refused("claims");
|
|
482
|
+
if (typeof verified.exp !== "number") return refused("claims");
|
|
483
|
+
return {
|
|
484
|
+
kind: "accepted",
|
|
485
|
+
claims: {
|
|
486
|
+
issuer: entry.issuer,
|
|
487
|
+
subject: verified.sub,
|
|
488
|
+
payload: verified
|
|
489
|
+
},
|
|
490
|
+
expiresAt: verified.exp * 1e3
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Decodes a token's header and claims without checking them.
|
|
495
|
+
*
|
|
496
|
+
* A string that is not a JWT at all fails here, which keeps every later check
|
|
497
|
+
* free of decode errors.
|
|
498
|
+
*/
|
|
499
|
+
function decodeToken(token) {
|
|
500
|
+
try {
|
|
501
|
+
return {
|
|
502
|
+
header: decodeProtectedHeader(token),
|
|
503
|
+
payload: decodeJwt(token)
|
|
504
|
+
};
|
|
505
|
+
} catch {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function hasAudience(aud, audiences) {
|
|
510
|
+
if (typeof aud === "string") return audiences.includes(aud);
|
|
511
|
+
if (!Array.isArray(aud)) return false;
|
|
512
|
+
return aud.some((value) => audiences.includes(value));
|
|
513
|
+
}
|
|
514
|
+
function verifyOptions(entry, requireAccessTokenType) {
|
|
515
|
+
const options = {
|
|
516
|
+
issuer: entry.issuer,
|
|
517
|
+
audience: [...entry.audiences],
|
|
518
|
+
algorithms: ["RS256"],
|
|
519
|
+
clockTolerance: CLOCK_TOLERANCE,
|
|
520
|
+
requiredClaims: ["exp", "sub"]
|
|
521
|
+
};
|
|
522
|
+
return requireAccessTokenType ? {
|
|
523
|
+
...options,
|
|
524
|
+
typ: "at+jwt"
|
|
525
|
+
} : options;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Wraps a key resolver so that a failure to read the keys is told apart from a
|
|
529
|
+
* failure of the token.
|
|
530
|
+
*
|
|
531
|
+
* The resolver is the only place a key is fetched or selected, so any error
|
|
532
|
+
* from it that is not one of jose's selection faults means the key set could not
|
|
533
|
+
* be read: a timeout, an unreachable host, a bad answer. A token can make the
|
|
534
|
+
* resolver run, but it cannot make it fail, so a key fault is always the key
|
|
535
|
+
* server's failure, never the token's.
|
|
536
|
+
*/
|
|
537
|
+
function wrapResolver(resolve) {
|
|
538
|
+
return async (header, token) => {
|
|
539
|
+
try {
|
|
540
|
+
return await resolve(header, token);
|
|
541
|
+
} catch (error) {
|
|
542
|
+
if (isSelectionFault(error)) throw error;
|
|
543
|
+
throw new KeyFault(error);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
/** True for the resolver errors that say the token matched no key, or too many. */
|
|
548
|
+
function isSelectionFault(error) {
|
|
549
|
+
return error instanceof errors.JWKSNoMatchingKey || error instanceof errors.JWKSMultipleMatchingKeys || error instanceof errors.JOSENotSupported;
|
|
550
|
+
}
|
|
551
|
+
/** Maps a jose error raised after the pre-checks to the reason to report. */
|
|
552
|
+
function refusalReason(error) {
|
|
553
|
+
if (error instanceof errors.JWTExpired) return "expired";
|
|
554
|
+
if (error instanceof errors.JWTClaimValidationFailed) return claimReason(error.claim);
|
|
555
|
+
if (error instanceof errors.JWSSignatureVerificationFailed) return "signature";
|
|
556
|
+
if (error instanceof errors.JWKSNoMatchingKey) return "signature";
|
|
557
|
+
if (error instanceof errors.JWKSMultipleMatchingKeys) return "signature";
|
|
558
|
+
return "invalid";
|
|
559
|
+
}
|
|
560
|
+
function claimReason(claim) {
|
|
561
|
+
switch (claim) {
|
|
562
|
+
case "aud": return "audience";
|
|
563
|
+
case "iss": return "issuer";
|
|
564
|
+
case "typ": return "token_type";
|
|
565
|
+
case "exp":
|
|
566
|
+
case "sub": return "claims";
|
|
567
|
+
default: return "invalid";
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function refused(reason) {
|
|
571
|
+
return {
|
|
572
|
+
kind: "refused",
|
|
573
|
+
reason
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
// src/create.ts
|
|
577
|
+
/** The path the endpoint serves when the options name none. */
|
|
578
|
+
const DEFAULT_PATH = "/mcp";
|
|
579
|
+
/** The largest body accepted when the options name no size. */
|
|
580
|
+
const DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
581
|
+
/** The refusal limit used when the options name none: 30 refusals in 15 minutes. */
|
|
582
|
+
const DEFAULT_REFUSALS = {
|
|
583
|
+
limit: 30,
|
|
584
|
+
windowMs: 9e5
|
|
585
|
+
};
|
|
586
|
+
/** The caller limit used when the options name none: 120 requests a minute. */
|
|
587
|
+
const DEFAULT_CALLERS = {
|
|
588
|
+
limit: 120,
|
|
589
|
+
windowMs: 6e4
|
|
590
|
+
};
|
|
591
|
+
/** The flood ceiling used when the options name none: 600 refusals a minute. */
|
|
592
|
+
const DEFAULT_FLOOD = {
|
|
593
|
+
limit: 600,
|
|
594
|
+
windowMs: 6e4
|
|
595
|
+
};
|
|
596
|
+
/**
|
|
597
|
+
* Marks a throw from a stage whose code the endpoint called.
|
|
598
|
+
*
|
|
599
|
+
* `onError` sees this marker, so it can name the stage in its fault event and
|
|
600
|
+
* answer with the fixed 503, while the original error stays for the log hook.
|
|
601
|
+
*/
|
|
602
|
+
var StageError = class extends Error {
|
|
603
|
+
/** The stage whose code threw. */
|
|
604
|
+
stage;
|
|
605
|
+
/** The error that stage threw. */
|
|
606
|
+
original;
|
|
607
|
+
constructor(stage, original) {
|
|
608
|
+
super(`The ${stage} stage failed.`);
|
|
609
|
+
this.stage = stage;
|
|
610
|
+
this.original = original;
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
/**
|
|
614
|
+
* Builds the sub-app that serves one MCP endpoint and its protected resource
|
|
615
|
+
* document.
|
|
616
|
+
*
|
|
617
|
+
* Mount it at the app's root (`app.route("/", createMcpEndpoint(...))`), so one
|
|
618
|
+
* call serves both routes and no route below the endpoint's path escapes the
|
|
619
|
+
* guard. Every request to the endpoint is answered in one fixed order: the
|
|
620
|
+
* challenge, the token key, the flood ceiling, the refusal limit, sign-in, the
|
|
621
|
+
* caller limit, the body limit, then the endpoint itself.
|
|
622
|
+
* An error thrown anywhere inside this app is reported through the log hook and
|
|
623
|
+
* answered with a fixed body; it never reaches the host app's error handler.
|
|
624
|
+
*/
|
|
625
|
+
function createMcpEndpoint(options) {
|
|
626
|
+
const setup = readSetup(options);
|
|
627
|
+
const emit = createEmitter(options.onEvent);
|
|
628
|
+
const keyer = createTokenKeyer();
|
|
629
|
+
const checkToken = createTokenChecker({
|
|
630
|
+
issuers: options.issuers,
|
|
631
|
+
requireAccessTokenType: options.requireAccessTokenType ?? false
|
|
632
|
+
});
|
|
633
|
+
const serveEndpoint = createEndpointHandler({
|
|
634
|
+
server: options.server,
|
|
635
|
+
tools: options.tools,
|
|
636
|
+
callTool: options.callTool,
|
|
637
|
+
emit
|
|
638
|
+
});
|
|
639
|
+
const limits = createLimiters({
|
|
640
|
+
limits: options.limits,
|
|
641
|
+
callerKey: options.callerKey,
|
|
642
|
+
emit
|
|
643
|
+
});
|
|
644
|
+
const challenge = `Bearer resource_metadata="${setup.documentUrl}"`;
|
|
645
|
+
const app = new Hono();
|
|
646
|
+
app.onError((error, c) => {
|
|
647
|
+
const fault = readFault(error);
|
|
648
|
+
emit({
|
|
649
|
+
type: "fault",
|
|
650
|
+
stage: fault.stage,
|
|
651
|
+
error: fault.error
|
|
652
|
+
});
|
|
653
|
+
return c.json(ERROR_BODIES[503], 503);
|
|
654
|
+
});
|
|
655
|
+
app.get(setup.documentPath, (c) => c.json(setup.document));
|
|
656
|
+
app.use(setup.path, async (c, next) => {
|
|
657
|
+
await next();
|
|
658
|
+
if (c.res.status !== 401) return;
|
|
659
|
+
const sent = readBearer(c.req.header("authorization")) !== void 0;
|
|
660
|
+
c.header("WWW-Authenticate", sent ? `${challenge}, error="invalid_token"` : challenge);
|
|
661
|
+
});
|
|
662
|
+
app.use(setup.path, async (c, next) => {
|
|
663
|
+
const authorization = c.req.header("authorization");
|
|
664
|
+
if (authorization !== void 0) c.set("tokenKey", keyer(authorization));
|
|
665
|
+
await next();
|
|
666
|
+
});
|
|
667
|
+
app.use(setup.path, limits.flood.middleware, limits.refusal);
|
|
668
|
+
app.use(setup.path, async (c, next) => {
|
|
669
|
+
const token = readBearer(c.req.header("authorization"));
|
|
670
|
+
if (token === void 0) {
|
|
671
|
+
emit({
|
|
672
|
+
type: "refusal",
|
|
673
|
+
status: 401,
|
|
674
|
+
reason: "no_token"
|
|
675
|
+
});
|
|
676
|
+
return c.json(ERROR_BODIES[401], 401);
|
|
677
|
+
}
|
|
678
|
+
const check = await checkToken(token);
|
|
679
|
+
if (check.kind === "key_fault") {
|
|
680
|
+
emit({
|
|
681
|
+
type: "fault",
|
|
682
|
+
stage: "keys",
|
|
683
|
+
error: check.error
|
|
684
|
+
});
|
|
685
|
+
return c.json(ERROR_BODIES[503], 503);
|
|
686
|
+
}
|
|
687
|
+
if (check.kind === "refused") {
|
|
688
|
+
emit({
|
|
689
|
+
type: "refusal",
|
|
690
|
+
status: 401,
|
|
691
|
+
reason: check.reason
|
|
692
|
+
});
|
|
693
|
+
return c.json(ERROR_BODIES[401], 401);
|
|
694
|
+
}
|
|
695
|
+
const identified = await runStage("identify", () => options.identify(check.claims, c.req.raw));
|
|
696
|
+
if (!identified.ok) {
|
|
697
|
+
emit({
|
|
698
|
+
type: "refusal",
|
|
699
|
+
status: identified.status,
|
|
700
|
+
reason: "identify",
|
|
701
|
+
message: identified.message
|
|
702
|
+
});
|
|
703
|
+
return c.json(ERROR_BODIES[identified.status], identified.status);
|
|
704
|
+
}
|
|
705
|
+
c.set("mcpUser", identified.user);
|
|
706
|
+
limits.flood.recordAccepted(c.get("tokenKey"), check.expiresAt);
|
|
707
|
+
return await next();
|
|
708
|
+
});
|
|
709
|
+
app.use(setup.path, limits.caller);
|
|
710
|
+
app.use(setup.path, bodyLimit({
|
|
711
|
+
maxSize: setup.maxBodyBytes,
|
|
712
|
+
onError: (c) => c.json(ERROR_BODIES[413], 413)
|
|
713
|
+
}));
|
|
714
|
+
app.post(setup.path, serveEndpoint);
|
|
715
|
+
app.all(setup.path, (c) => {
|
|
716
|
+
c.header("Allow", "POST");
|
|
717
|
+
return c.json(ERROR_BODIES[405], 405);
|
|
718
|
+
});
|
|
719
|
+
app.all(`${setup.path}/*`, (c) => c.json(ERROR_BODIES[404], 404));
|
|
720
|
+
return app;
|
|
721
|
+
}
|
|
722
|
+
/** Runs one stage's code and marks any throw with that stage's name. */
|
|
723
|
+
async function runStage(stage, run) {
|
|
724
|
+
try {
|
|
725
|
+
return await run();
|
|
726
|
+
} catch (error) {
|
|
727
|
+
throw new StageError(stage, error);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
/** Reads the app's key for one caller, marking a throw with its stage. */
|
|
731
|
+
function readCallerKey(callerKey, user) {
|
|
732
|
+
try {
|
|
733
|
+
return callerKey(user);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
throw new StageError("caller_key", error);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/** The stage and original error to report for a throw that reached `onError`. */
|
|
739
|
+
function readFault(error) {
|
|
740
|
+
if (error instanceof StageError) return {
|
|
741
|
+
stage: error.stage,
|
|
742
|
+
error: error.original
|
|
743
|
+
};
|
|
744
|
+
return {
|
|
745
|
+
stage: "endpoint",
|
|
746
|
+
error
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Wraps the app's log hook so a throw from it changes nothing.
|
|
751
|
+
*
|
|
752
|
+
* The hook is the only place the endpoint reports a refusal, a limit hit, a tool
|
|
753
|
+
* error or a fault, and a hook that throws must not change an answer.
|
|
754
|
+
*/
|
|
755
|
+
function createEmitter(hook) {
|
|
756
|
+
return (event) => {
|
|
757
|
+
try {
|
|
758
|
+
hook?.(event);
|
|
759
|
+
} catch (_error) {}
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
/** Reads the options into the values every request uses, refusing a bad one. */
|
|
763
|
+
function readSetup(options) {
|
|
764
|
+
const origin = readOrigin(options.publicUrl);
|
|
765
|
+
const path = readPath(options.path ?? DEFAULT_PATH);
|
|
766
|
+
checkIssuers(options.issuers);
|
|
767
|
+
return {
|
|
768
|
+
path,
|
|
769
|
+
documentUrl: documentUrl(origin, path),
|
|
770
|
+
documentPath: documentPath(path),
|
|
771
|
+
document: buildResourceDocument({
|
|
772
|
+
origin,
|
|
773
|
+
path,
|
|
774
|
+
issuers: options.issuers,
|
|
775
|
+
scopes: options.scopes
|
|
776
|
+
}),
|
|
777
|
+
maxBodyBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
/** Builds the three limits the endpoint runs, in the order it runs them. */
|
|
781
|
+
function createLimiters(options) {
|
|
782
|
+
const limits = readLimits(options.limits);
|
|
783
|
+
return {
|
|
784
|
+
flood: createFloodCeiling({
|
|
785
|
+
...limits.flood,
|
|
786
|
+
maxAccepted: DEFAULT_MAX_KEYS,
|
|
787
|
+
emit: options.emit
|
|
788
|
+
}),
|
|
789
|
+
refusal: createRefusalLimit({
|
|
790
|
+
...limits.refusals,
|
|
791
|
+
emit: options.emit
|
|
792
|
+
}),
|
|
793
|
+
caller: createCallerLimit({
|
|
794
|
+
...limits.callers,
|
|
795
|
+
callerKey: (user) => readCallerKey(options.callerKey, user),
|
|
796
|
+
emit: options.emit
|
|
797
|
+
})
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
/** Reads each limit from the options, falling back to its default. */
|
|
801
|
+
function readLimits(limits = {}) {
|
|
802
|
+
return {
|
|
803
|
+
refusals: limits.refusals ?? DEFAULT_REFUSALS,
|
|
804
|
+
callers: limits.callers ?? DEFAULT_CALLERS,
|
|
805
|
+
flood: limits.flood ?? DEFAULT_FLOOD
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
/** The public URL's origin, refused unless it names that origin and nothing else. */
|
|
809
|
+
function readOrigin(publicUrl) {
|
|
810
|
+
let url;
|
|
811
|
+
try {
|
|
812
|
+
url = new URL(publicUrl);
|
|
813
|
+
} catch {
|
|
814
|
+
throw new McpEndpointConfigError("publicUrl must be an absolute URL.");
|
|
815
|
+
}
|
|
816
|
+
if (url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new McpEndpointConfigError("publicUrl must name an origin only: no path, query or hash.");
|
|
817
|
+
return url.origin;
|
|
818
|
+
}
|
|
819
|
+
/** The endpoint path, refused unless it is a plain route below the root. */
|
|
820
|
+
function readPath(path) {
|
|
821
|
+
if (!path.startsWith("/")) throw new McpEndpointConfigError("path must start with \"/\".");
|
|
822
|
+
if (path.endsWith("/")) throw new McpEndpointConfigError("path must not end with \"/\".");
|
|
823
|
+
if (path.includes("*") || path.includes(":")) throw new McpEndpointConfigError("path must not hold \"*\" or \":\", which the router reads.");
|
|
824
|
+
return path;
|
|
825
|
+
}
|
|
826
|
+
/** Refuses an issuer list whose issuers could accept no token. */
|
|
827
|
+
function checkIssuers(issuers) {
|
|
828
|
+
if (issuers.length === 0) throw new McpEndpointConfigError("issuers must name at least one issuer.");
|
|
829
|
+
if (issuers.some((issuer) => issuer.audiences.length === 0)) throw new McpEndpointConfigError("each issuer needs at least one audience.");
|
|
830
|
+
}
|
|
831
|
+
export { McpEndpointConfigError, createMcpEndpoint };
|