ovr 6.2.4 → 7.0.0-next.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.
Files changed (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
@@ -0,0 +1,988 @@
1
+ import { agents, direct, mount } from "../app/index.js";
2
+ import { agent } from "../context/index.js";
3
+ import { forms } from "../form/index.js";
4
+ import { Route, parameters, schemas } from "../route/index.js";
5
+ import { Schema } from "../schema/index.js";
6
+ import { Codec, Header, Method, Mime, Size, noStore } from "../util/index.js";
7
+ /** JSON-RPC error */
8
+ class RpcError extends Error {
9
+ /** JSON-RPC error code */
10
+ code;
11
+ /** HTTP status */
12
+ status;
13
+ /** Error data */
14
+ data;
15
+ /**
16
+ * @param code JSON-RPC error code
17
+ * @param message Error message
18
+ * @param status HTTP status
19
+ * @param data Error data
20
+ */
21
+ constructor(code, message, status = 200, data) {
22
+ super(message);
23
+ this.code = code;
24
+ this.status = status;
25
+ this.data = data;
26
+ }
27
+ }
28
+ /**
29
+ * Model Context Protocol endpoint. Agents use the app's routes as tools, and
30
+ * read its pages as Markdown resources.
31
+ *
32
+ * ```ts
33
+ * app.use(new Mcp({ instructions: "Save and organize bookmarks." }));
34
+ * ```
35
+ */
36
+ export class Mcp {
37
+ /** Supported protocol versions */
38
+ static #versions = ["2026-07-28"];
39
+ /**
40
+ * Earlier versions, which start with `initialize`, newest first. Clients
41
+ * such as ChatGPT's still use them.
42
+ */
43
+ static #legacy = ["2025-11-25", "2025-06-18"];
44
+ /** `_meta` key prefix */
45
+ static #meta = "io.modelcontextprotocol/";
46
+ /** Largest response an agent reads from a route */
47
+ static #output = 4 * Size.mb;
48
+ /**
49
+ * Scheme that names a page of an app agents sign in to. An `https` name
50
+ * says the agent can fetch the page itself, which it cannot without the
51
+ * user's session, so it reads the page through this endpoint.
52
+ */
53
+ static #scheme = "page:";
54
+ /** Redirects followed after a tool call */
55
+ static #redirects = 5;
56
+ /**
57
+ * Path of the protected resource metadata, RFC 9728, which the endpoint's
58
+ * path follows
59
+ */
60
+ static #discovery = "/.well-known/oauth-protected-resource";
61
+ #options;
62
+ /** App the endpoint is mounted on */
63
+ #app;
64
+ /**
65
+ * The user's language for each request: what the client prefers, passed to
66
+ * the routes it calls, and what a route answered in
67
+ */
68
+ #languages = new WeakMap();
69
+ /** @param options MCP server options */
70
+ constructor(options = {}) {
71
+ this.#options = { ...options, path: options.path ?? "/mcp" };
72
+ }
73
+ /**
74
+ * Mounted by `app.use(mcp)`.
75
+ *
76
+ * @param app App to serve
77
+ * @returns The MCP endpoint routes, and the endpoints agents sign in with
78
+ */
79
+ [mount](app) {
80
+ if (this.#app)
81
+ throw new TypeError("An Mcp endpoint can only be mounted on one app.");
82
+ this.#app = app;
83
+ const { path, auth } = this.#options;
84
+ const routes = [
85
+ Route.post(path).use((c) => this.#handle(c)),
86
+ // only POST is used, there are no streams to open or sessions to end
87
+ ...[Method.get, "DELETE"].map((method) => new Route(method, path).use((c) => {
88
+ c.res.headers.set("allow", Method.post);
89
+ return c.text("Method Not Allowed", 405);
90
+ })),
91
+ ];
92
+ // the endpoint is the way in for agents, not a page of the app: its
93
+ // request is not the app's to handle. The request it makes to a route
94
+ // for the agent is, once, as the agent's user
95
+ for (const route of routes)
96
+ direct.add(route);
97
+ if (auth) {
98
+ // protected resource metadata, RFC 9728
99
+ // by the configured origin, the one tokens are issued for, and not the
100
+ // request's host, which anyone can choose
101
+ const { origin } = auth[agents];
102
+ const metadata = (c) => {
103
+ c.res.headers.set("access-control-allow-origin", "*");
104
+ c.json({
105
+ resource: new URL(path, origin).href,
106
+ authorization_servers: [origin],
107
+ bearer_methods_supported: ["header"],
108
+ resource_name: this.#options.name ?? new URL(origin).host,
109
+ });
110
+ };
111
+ // part of the way in too, an agent reads it before it has a token
112
+ const discovery = Route.get(Mcp.#discovery + path).use(metadata);
113
+ direct.add(discovery);
114
+ routes.push(discovery);
115
+ return [
116
+ ...routes,
117
+ auth[agents].mount(app, new URL(path, auth[agents].origin).href),
118
+ ];
119
+ }
120
+ return routes;
121
+ }
122
+ /** @param c Request context */
123
+ async #handle(c) {
124
+ noStore(c.res.headers);
125
+ let id = null;
126
+ const reply = (body, status) => c.json({ jsonrpc: "2.0", id, ...body }, status);
127
+ try {
128
+ const origin = c.req.headers.get(Header.name.origin);
129
+ if (origin !== null && (origin !== c.url.origin || Mcp.#rebound(c)))
130
+ throw new RpcError(-32600, "Invalid origin", 403);
131
+ const session = await this.#authorize(c);
132
+ const message = await this.#read(c);
133
+ if (!("id" in message)) {
134
+ // notification, answered with no content
135
+ c.res.status = 202;
136
+ c.res.body = null;
137
+ return;
138
+ }
139
+ id = message.id;
140
+ const method = message.method;
141
+ const params = (message.params ?? {});
142
+ const meta = (params._meta ?? {});
143
+ const version = meta[`${Mcp.#meta}protocolVersion`];
144
+ const header = c.req.headers.get("mcp-protocol-version");
145
+ // a request with a version in `_meta` is 2026-07-28's, which removed it
146
+ if (method === "initialize" && version === undefined) {
147
+ // an earlier version's handshake, answered with the requested
148
+ // version when supported, otherwise the newest earlier one
149
+ const requested = params.protocolVersion;
150
+ reply({
151
+ result: {
152
+ protocolVersion: typeof requested === "string" && Mcp.#legacy.includes(requested)
153
+ ? requested
154
+ : Mcp.#legacy[0],
155
+ ...this.#server(),
156
+ serverInfo: this.#info(c),
157
+ },
158
+ });
159
+ return;
160
+ }
161
+ // after `initialize`, an earlier version is only in the header
162
+ const legacy = version === undefined &&
163
+ header !== null &&
164
+ Mcp.#legacy.includes(header);
165
+ if (legacy) {
166
+ if (method === "server/discover")
167
+ throw new RpcError(-32601, "Method not found", 404);
168
+ // earlier clients need not send them, but sent ones must match, so
169
+ // a proxy routing on them sees the request that runs
170
+ Mcp.#mirror(c, method, params, true);
171
+ }
172
+ else
173
+ this.#validate(c, method, params, meta, version, header);
174
+ const language = this.#language(c, meta, legacy);
175
+ const { ttlMs, cacheScope, ...result } = await this.#dispatch(c, method, params, session, legacy);
176
+ reply({
177
+ result: legacy
178
+ ? result
179
+ : {
180
+ resultType: "complete",
181
+ ttlMs,
182
+ cacheScope,
183
+ ...result,
184
+ _meta: {
185
+ [`${Mcp.#meta}serverInfo`]: this.#info(c),
186
+ ...(language.content && {
187
+ [`${Mcp.#meta}contentLanguage`]: language.content,
188
+ }),
189
+ },
190
+ },
191
+ });
192
+ if (language.content) {
193
+ // the language a route answered in, which varies by the preference
194
+ c.res.headers.set("content-language", language.content);
195
+ c.res.headers.append("vary", "accept-language");
196
+ }
197
+ }
198
+ catch (error) {
199
+ if (!(error instanceof RpcError))
200
+ throw error;
201
+ reply({
202
+ error: { code: error.code, message: error.message, data: error.data },
203
+ }, error.status);
204
+ }
205
+ }
206
+ /**
207
+ * DNS rebinding: a site whose name resolves to this machine, so the user's
208
+ * browser sends its requests here, with the site as both host and origin.
209
+ * A browser request from this machine for another host is one.
210
+ *
211
+ * @param c Request context
212
+ * @returns `true` when a local client asks for a host that is not local
213
+ */
214
+ static #rebound(c) {
215
+ const local = (host) => host === "localhost" ||
216
+ host.endsWith(".localhost") ||
217
+ /^127\.|^\[?::1\]?$|^\[?::ffff:127\./.test(host);
218
+ return Boolean(c.ip && local(c.ip) && !local(c.url.hostname));
219
+ }
220
+ /**
221
+ * Reads the user's language preference, which the routes a request calls
222
+ * receive as `Accept-Language`, as a person's browser sends it.
223
+ *
224
+ * @param c Request context
225
+ * @param meta Request `_meta`
226
+ * @param legacy An earlier protocol version, where it is only a header
227
+ * @returns The request's languages, the route's is set once it answers
228
+ */
229
+ #language(c, meta, legacy) {
230
+ const valid = (value) => typeof value === "string" && /^[\w*,;=. -]{1,256}$/.test(value);
231
+ const header = c.req.headers.get("accept-language");
232
+ const stated = legacy ? undefined : meta[`${Mcp.#meta}acceptLanguage`];
233
+ if (stated !== undefined) {
234
+ if (!valid(stated))
235
+ throw new RpcError(-32602, "Invalid acceptLanguage", 400);
236
+ // a proxy may remove the header, but one that is sent must be the same
237
+ if (header !== null && header !== stated)
238
+ throw Mcp.#mismatch("Accept-Language");
239
+ }
240
+ const accept = stated ?? (valid(header) ? header : undefined);
241
+ const language = accept
242
+ ? { accept }
243
+ : {};
244
+ this.#languages.set(c.req, language);
245
+ return language;
246
+ }
247
+ /**
248
+ * @param c Request context
249
+ * @returns The session, or `null` without auth
250
+ */
251
+ async #authorize(c) {
252
+ const { auth, path } = this.#options;
253
+ if (!auth)
254
+ return null;
255
+ const session = await auth[agents].bearer(c, new URL(path, c.url).href);
256
+ if (session)
257
+ return session;
258
+ c.res.headers.set("www-authenticate", `Bearer resource_metadata="${new URL(Mcp.#discovery + path, c.url).href}"`);
259
+ throw new RpcError(-32001, "Unauthorized", 401);
260
+ }
261
+ /**
262
+ * @param c Request context
263
+ * @returns Parsed JSON-RPC message
264
+ */
265
+ async #read(c) {
266
+ const [type] = Header.shift(c.req.headers.get(Header.name.type));
267
+ if (type?.trim() !== Mime.type.json)
268
+ throw new RpcError(-32700, "Expected application/json", 415);
269
+ // read into memory, so within what the app allows a form's body there:
270
+ // a tool's file arguments are in it
271
+ const limit = this.#app.memory;
272
+ const length = Number(c.req.headers.get("content-length"));
273
+ const text = length > limit ? undefined : await Mcp.#text(c.req.body, limit);
274
+ if (text === undefined)
275
+ throw new RpcError(-32600, "Request too large", 413);
276
+ const invalid = () => new RpcError(-32700, "Parse error", 400);
277
+ if (text === null)
278
+ throw invalid();
279
+ let message;
280
+ try {
281
+ message = JSON.parse(text);
282
+ }
283
+ catch {
284
+ throw invalid();
285
+ }
286
+ if (!message ||
287
+ typeof message !== "object" ||
288
+ Array.isArray(message) ||
289
+ message.jsonrpc !== "2.0" ||
290
+ typeof message.method !== "string" ||
291
+ // MCP request IDs are strings or integers
292
+ ("id" in message &&
293
+ typeof message.id !== "string" &&
294
+ !Number.isSafeInteger(message.id))) {
295
+ throw new RpcError(-32600, "Invalid request", 400);
296
+ }
297
+ return message;
298
+ }
299
+ /**
300
+ * Its own function, so the body's bytes are let go once decoded: a
301
+ * variable that held them would keep them while the text is parsed.
302
+ *
303
+ * @param body Request body
304
+ * @param limit Largest size in bytes
305
+ * @returns The body's text, `undefined` when it is too large, or `null`
306
+ * when it is not UTF-8
307
+ */
308
+ static async #text(body, limit) {
309
+ const bytes = await Codec.read(body, limit);
310
+ if (!bytes)
311
+ return;
312
+ try {
313
+ return Codec.decode(bytes);
314
+ }
315
+ catch {
316
+ return null;
317
+ }
318
+ }
319
+ /**
320
+ * Checks the protocol version, and the headers a request must mirror from
321
+ * its body, for the 2026-07-28 version.
322
+ *
323
+ * @param c Request context
324
+ * @param method JSON-RPC method
325
+ * @param params Request params
326
+ * @param meta Request `_meta`, which carries the version and capabilities
327
+ * @param version Protocol version in `_meta`
328
+ * @param header `MCP-Protocol-Version` header
329
+ */
330
+ #validate(c, method, params, meta, version, header) {
331
+ const invalid = (field) => new RpcError(-32602, `Invalid params: _meta needs ${Mcp.#meta}${field}`, 400);
332
+ if (version === undefined) {
333
+ // this version by its header, so what is missing is the field
334
+ if (header !== null && Mcp.#versions.includes(header))
335
+ throw invalid("protocolVersion");
336
+ }
337
+ else if (typeof version !== "string") {
338
+ throw invalid("protocolVersion");
339
+ }
340
+ else if (header !== version) {
341
+ // before the version is judged: a proxy routes on the header
342
+ throw Mcp.#mismatch("MCP-Protocol-Version");
343
+ }
344
+ if (version === undefined || !Mcp.#versions.includes(version))
345
+ throw new RpcError(-32022, "Unsupported protocol version", 400, {
346
+ supported: [...Mcp.#versions, ...Mcp.#legacy],
347
+ requested: version ?? header,
348
+ });
349
+ const capabilities = meta[`${Mcp.#meta}clientCapabilities`];
350
+ if (!capabilities ||
351
+ typeof capabilities !== "object" ||
352
+ Array.isArray(capabilities))
353
+ throw invalid("clientCapabilities");
354
+ Mcp.#mirror(c, method, params);
355
+ }
356
+ /**
357
+ * @param header Header that does not match the request
358
+ * @param part What it should match
359
+ * @returns The JSON-RPC error
360
+ */
361
+ static #mismatch(header, part = "the request") {
362
+ return new RpcError(-32020, `Header mismatch: ${header} does not match ${part}`, 400);
363
+ }
364
+ /**
365
+ * Checks the headers a request mirrors from its body.
366
+ *
367
+ * @param c Request context
368
+ * @param method JSON-RPC method
369
+ * @param params Request params
370
+ * @param optional Check only the headers that are sent
371
+ */
372
+ static #mirror(c, method, params, optional) {
373
+ const sent = c.req.headers.get("mcp-method");
374
+ if ((sent !== null || !optional) && sent !== method)
375
+ throw Mcp.#mismatch("Mcp-Method", "the request method");
376
+ const name = method === "tools/call" || method === "prompts/get"
377
+ ? params.name
378
+ : method === "resources/read"
379
+ ? params.uri
380
+ : undefined;
381
+ if (name !== undefined) {
382
+ let value = c.req.headers.get("mcp-name");
383
+ if (value === null && optional)
384
+ return;
385
+ const encoded = value && /^=\?base64\?(.*)\?=$/.exec(value);
386
+ if (encoded) {
387
+ try {
388
+ value = Codec.decode(Codec.Base64.decode(encoded[1]));
389
+ }
390
+ catch {
391
+ value = null;
392
+ }
393
+ }
394
+ if (value !== name)
395
+ throw Mcp.#mismatch("Mcp-Name");
396
+ }
397
+ }
398
+ /**
399
+ * @param c Request context
400
+ * @returns Server name and version
401
+ */
402
+ #info(c) {
403
+ return {
404
+ name: this.#options.name ?? c.url.host,
405
+ // required by the protocol, and only shown in clients
406
+ version: "1.0.0",
407
+ };
408
+ }
409
+ /** @returns Server capabilities and instructions */
410
+ #server() {
411
+ return {
412
+ capabilities: { tools: {}, resources: {} },
413
+ instructions: this.#options.instructions,
414
+ };
415
+ }
416
+ /**
417
+ * @param c Request context
418
+ * @param method JSON-RPC method
419
+ * @param params Request params
420
+ * @param session Session the token authorizes
421
+ * @returns Method result
422
+ */
423
+ async #dispatch(c, method, params, session, legacy) {
424
+ const cache = { ttlMs: 60_000, cacheScope: "public" };
425
+ switch (method) {
426
+ case "server/discover":
427
+ return {
428
+ supportedVersions: [...Mcp.#versions, ...Mcp.#legacy],
429
+ ...this.#server(),
430
+ ...cache,
431
+ };
432
+ case "ping":
433
+ // removed in 2026-07-28
434
+ if (legacy)
435
+ return {};
436
+ break;
437
+ case "tools/list":
438
+ return { tools: this.#tools(), ...cache };
439
+ case "tools/call":
440
+ return this.#call(c, params, session);
441
+ case "resources/list":
442
+ case "resources/templates/list": {
443
+ // pages with parameters are templates
444
+ const templates = method !== "resources/list";
445
+ return {
446
+ [templates ? "resourceTemplates" : "resources"]: this.#app.routes.filter((route) => route.method === Method.get &&
447
+ route.description &&
448
+ /[:*]/.test(route.pattern) === templates).map((route) => {
449
+ const href = this.#name(new URL(route.pattern.replace(parameters, (_, name) => name ? `{${name}}` : "{+wildcard}"), c.url));
450
+ return {
451
+ [templates ? "uriTemplate" : "uri"]: templates
452
+ ? href.replaceAll("%7B", "{").replaceAll("%7D", "}")
453
+ : href,
454
+ name: route.pattern,
455
+ description: route.description,
456
+ mimeType: Mime.type.md,
457
+ };
458
+ }),
459
+ ...cache,
460
+ };
461
+ }
462
+ case "resources/read":
463
+ return this.#resource(c, params, session, legacy);
464
+ }
465
+ throw new RpcError(-32601, "Method not found", 404);
466
+ }
467
+ /**
468
+ * Built for each request, so routes mounted after the endpoint are
469
+ * included. Mounted routes are final, so their tools do not change.
470
+ *
471
+ * @returns Tool definitions, from the app's current routes
472
+ */
473
+ #tools() {
474
+ const tools = [];
475
+ for (const route of this.#app.routes) {
476
+ const { tool } = route;
477
+ if (!tool)
478
+ continue;
479
+ const { name, read } = tool;
480
+ const shape = forms.get(route)?.shape;
481
+ // names are unique, app.use() throws for two routes sharing one
482
+ const properties = {};
483
+ const required = new Set();
484
+ if (shape) {
485
+ const schema = Mcp.#json(Schema.object(shape));
486
+ Object.assign(properties, schema.properties);
487
+ for (const field of (schema.required ?? []))
488
+ required.add(field);
489
+ // a tool's arguments are JSON, so a file is sent as its contents
490
+ for (const name in shape) {
491
+ const field = shape[name];
492
+ if (field.type === "file")
493
+ properties[name] = {
494
+ ...properties[name],
495
+ ...(field.parts > 1 ? { items: Mcp.#file } : Mcp.#file),
496
+ };
497
+ }
498
+ }
499
+ for (const [param, key] of Mcp.#params(route)) {
500
+ const schema = route[schemas]?.[key];
501
+ properties[param] = schema ? Mcp.#json(schema) : { type: "string" };
502
+ required.add(param);
503
+ }
504
+ tools.push({
505
+ name,
506
+ description: tool.description,
507
+ inputSchema: {
508
+ type: "object",
509
+ properties,
510
+ ...(required.size > 0 && { required: [...required] }),
511
+ // a form takes only its fields. Other routes are left open: a
512
+ // handler may read the query or the body itself
513
+ ...(shape && !read && { additionalProperties: false }),
514
+ },
515
+ // no destructiveHint, so clients treat any tool that writes as one
516
+ // that may need confirming
517
+ annotations: { readOnlyHint: read, openWorldHint: false },
518
+ });
519
+ }
520
+ return tools;
521
+ }
522
+ /**
523
+ * @param route Route a tool calls
524
+ * @returns Pattern parameters by the argument that fills them, `wildcard`
525
+ * fills `*`
526
+ */
527
+ static #params(route) {
528
+ return new Map(Array.from(route.pattern.matchAll(parameters), ([, name]) => name ? [name, name] : ["wildcard", "*"]));
529
+ }
530
+ /** A file as a tool argument, for a file field */
531
+ static #file = {
532
+ type: "object",
533
+ description: "A file. Send its contents as `text`, or as `base64` when it is not text.",
534
+ properties: {
535
+ name: { type: "string", description: "File name, such as notes.txt" },
536
+ type: { type: "string", description: "Media type, such as text/plain" },
537
+ text: { type: "string" },
538
+ base64: { type: "string", contentEncoding: "base64" },
539
+ },
540
+ required: ["name"],
541
+ };
542
+ /**
543
+ * @param value Tool argument for a file field
544
+ * @returns The file, `undefined` when the argument does not describe one
545
+ */
546
+ static #upload(value) {
547
+ if (typeof value !== "object" || !value)
548
+ return;
549
+ const argument = value;
550
+ const { name, type, text, base64 } = argument;
551
+ if (typeof name !== "string" || !name)
552
+ return;
553
+ let contents;
554
+ if (typeof text === "string")
555
+ contents = text;
556
+ else if (typeof base64 !== "string")
557
+ return;
558
+ else {
559
+ try {
560
+ contents = Codec.Base64.decode(base64);
561
+ }
562
+ catch {
563
+ // not base64
564
+ return;
565
+ }
566
+ }
567
+ // the request's message stays reachable until the route answers, so
568
+ // its contents would be held twice: as the file, and as its text
569
+ delete argument.text;
570
+ delete argument.base64;
571
+ return new File([contents], name, typeof type === "string" ? { type } : undefined);
572
+ }
573
+ /**
574
+ * @param schema Schema
575
+ * @returns JSON Schema for the accepted input
576
+ */
577
+ static #json(schema) {
578
+ const { $schema: _, ...json } = schema.toJsonSchema({
579
+ io: "input",
580
+ unrepresentable: "any",
581
+ });
582
+ return json;
583
+ }
584
+ /**
585
+ * Calls a route as the agent's user.
586
+ *
587
+ * @param c Request context
588
+ * @param params `tools/call` params
589
+ * @param session Session the token authorizes
590
+ * @returns Tool result
591
+ */
592
+ async #call(c, params, session) {
593
+ // only the tool called: the list builds every tool's JSON Schema, which
594
+ // for an app with many tools is megabytes for each call
595
+ const route = typeof params.name === "string"
596
+ ? this.#app.routes.find((route) => route.tool?.name === params.name)
597
+ : undefined;
598
+ if (!route)
599
+ throw new RpcError(-32602, `Unknown tool: ${params.name}`);
600
+ const pathParams = Mcp.#params(route);
601
+ const args = (params.arguments ?? {});
602
+ if (typeof args !== "object" || Array.isArray(args))
603
+ throw new RpcError(-32602, "Tool arguments must be an object");
604
+ // reported like the form's issues, where a browser would get a 404
605
+ const issues = [];
606
+ for (const [param, key] of pathParams) {
607
+ const value = args[param];
608
+ for (const { message } of typeof value === "string" ||
609
+ typeof value === "number"
610
+ ? (route[schemas]?.[key]?.parse(String(value)).issues ?? [])
611
+ : [{ message: "Required field" }])
612
+ issues.push({ path: param, message });
613
+ }
614
+ if (issues.length)
615
+ return Mcp.#result(Mcp.#issues(issues), true);
616
+ let url;
617
+ try {
618
+ url = new URL(route.url({
619
+ params: Object.fromEntries(Array.from(pathParams, ([param, key]) => [
620
+ key,
621
+ String(args[param]),
622
+ ])),
623
+ }), c.url.origin);
624
+ }
625
+ catch (error) {
626
+ // a value such as `..` or `/host` would leave its place in the path,
627
+ // and one with a lone surrogate cannot be encoded
628
+ if (!(error instanceof TypeError || error instanceof URIError))
629
+ throw error;
630
+ }
631
+ // a more specific pattern could select another route
632
+ if (!url || this.#app.find(route.method, url.pathname)?.route !== route)
633
+ return Mcp.#result(`Parameters do not match ${route.pattern}`, true);
634
+ const read = route.method === Method.get;
635
+ const body = new FormData();
636
+ const shape = forms.get(route)?.shape;
637
+ if (shape && !read) {
638
+ // named here, the form would only count one part too many
639
+ const unexpected = Object.keys(args).filter((name) => !Object.hasOwn(shape, name) && !pathParams.has(name));
640
+ if (unexpected.length)
641
+ return Mcp.#result(Mcp.#issues(unexpected.map((path) => ({
642
+ path,
643
+ message: "Unexpected argument",
644
+ }))), true);
645
+ }
646
+ for (const [name, value] of Object.entries(args)) {
647
+ const field = shape && Object.hasOwn(shape, name) ? shape[name] : undefined;
648
+ // a parameter is in the path, and also sent when a field has its name
649
+ if (pathParams.has(name) && !field)
650
+ continue;
651
+ const upload = !read && field?.type === "file";
652
+ for (const item of Array.isArray(value) ? value : [value]) {
653
+ if (item == null || item === false)
654
+ continue;
655
+ if (upload) {
656
+ const file = Mcp.#upload(item);
657
+ if (!file)
658
+ return Mcp.#result(Mcp.#issues([
659
+ {
660
+ path: name,
661
+ message: "Expected a file: its name, and its contents as text or base64",
662
+ },
663
+ ]), true);
664
+ body.append(name, file);
665
+ continue;
666
+ }
667
+ const text = item === true
668
+ ? "on"
669
+ : typeof item === "object"
670
+ ? JSON.stringify(item)
671
+ : String(item);
672
+ if (read)
673
+ url.searchParams.append(name, text);
674
+ else
675
+ body.append(name, text);
676
+ }
677
+ }
678
+ return this.#fetch(c, session, url, read ? undefined : { method: route.method, body });
679
+ }
680
+ /**
681
+ * Reads a page as Markdown.
682
+ *
683
+ * @param c Request context
684
+ * @param params `resources/read` params
685
+ * @param session Session the token authorizes
686
+ * @returns Resource contents
687
+ */
688
+ async #resource(c, params, session, legacy) {
689
+ const uri = String(params.uri);
690
+ let url;
691
+ try {
692
+ url = new URL(uri);
693
+ // a page by its name, or by its address, as a link in a page gives it
694
+ if (url.protocol === Mcp.#scheme)
695
+ url = new URL(url.pathname + url.search + url.hash, `${c.url.protocol}//${url.host}`);
696
+ }
697
+ catch {
698
+ throw new RpcError(-32602, "Invalid resource URI");
699
+ }
700
+ // its own code before 2026-07-28, invalid params since
701
+ const missing = () => new RpcError(legacy ? -32002 : -32602, "Resource not found", 200, {
702
+ uri,
703
+ });
704
+ // a page read as the user is theirs alone, and may change at any time
705
+ const cache = {
706
+ ttlMs: 0,
707
+ cacheScope: this.#options.auth ? "private" : "public",
708
+ };
709
+ if (!this.#readable(c, url))
710
+ throw missing();
711
+ const res = await this.#run(c, session, url);
712
+ // the page's form has issues, such as a search with invalid parameters
713
+ if (typeof res === "string")
714
+ throw new RpcError(-32602, res);
715
+ if (res.status >= 500)
716
+ throw await Mcp.#failed(res);
717
+ // a stream is only from a page that succeeds, so it passes the checks below
718
+ const { type, live, ...body } = await Mcp.#body(res);
719
+ if (res.status === 404)
720
+ throw missing();
721
+ // refused, such as a 403: the request's to change, where a server error
722
+ // above is the app's
723
+ if (!res.ok) {
724
+ const retry = res.headers.get("retry-after");
725
+ throw new RpcError(-32602, `${res.status} ${body.text || res.statusText}`.trim(), 200, {
726
+ uri,
727
+ status: res.status,
728
+ ...(retry !== null && { retryAfter: retry }),
729
+ });
730
+ }
731
+ return {
732
+ contents: [
733
+ {
734
+ uri: this.#name(url),
735
+ ...(live
736
+ ? { mimeType: Mime.type.text, text: this.#stream(url) }
737
+ : { mimeType: type ?? Mime.type.md, ...body }),
738
+ },
739
+ ],
740
+ ...cache,
741
+ };
742
+ }
743
+ /**
744
+ * @param url A page's address
745
+ * @returns The page's resource name: its address, or with sign-in the same
746
+ * host and path as a `page:` URI
747
+ */
748
+ #name(url) {
749
+ return this.#options.auth
750
+ ? `${Mcp.#scheme}//${url.host}${url.pathname}${url.search}${url.hash}`
751
+ : url.href;
752
+ }
753
+ /**
754
+ * @param url Address of a route that answers with an event stream
755
+ * @returns What to tell the agent, a stream may never end so it is not read
756
+ */
757
+ #stream(url) {
758
+ return this.#options.auth
759
+ ? `This is a live event stream, which is not read through this connection. It needs the user's sign-in, so the user can open it in their browser: ${url.href}`
760
+ : `This is a live event stream. Request the address yourself to read its events as they arrive, and close the connection to stop: ${url.href}`;
761
+ }
762
+ /**
763
+ * @param c Request context
764
+ * @returns The name of the tool a form submits to, so the page an agent
765
+ * reads points to the tool instead of repeating its fields
766
+ */
767
+ #tool(c) {
768
+ return (method, action) => {
769
+ const match = this.#find(c, method, action);
770
+ const name = match?.route.tool?.name;
771
+ if (!name)
772
+ return;
773
+ // the address's parameters, as the arguments the tool takes them by
774
+ const args = {};
775
+ for (const param in match.params)
776
+ args[param === "*" ? "wildcard" : param] = match.params[param];
777
+ return { name, args };
778
+ };
779
+ }
780
+ /**
781
+ * @param c Request context
782
+ * @param url URL to read
783
+ * @returns `true` if the URL is a page agents can read
784
+ */
785
+ #readable(c, url) {
786
+ return Boolean(this.#find(c, Method.get, url)?.route.description);
787
+ }
788
+ /**
789
+ * @param c Request context
790
+ * @param method Request method
791
+ * @param url URL of a page of the app
792
+ * @returns The route that answers it, `undefined` for another site's
793
+ */
794
+ #find(c, method, url) {
795
+ // credentials are no part of a page's address
796
+ if (url.origin === c.url.origin && !url.username && !url.password)
797
+ return this.#app.find(method, url.pathname);
798
+ }
799
+ /** Media types read as text, any other is a file */
800
+ static #texts = /^text\/|[/+](?:json|xml)$|^application\/(?:javascript|x-www-form-urlencoded)$/i;
801
+ /**
802
+ * @param res Response from a route
803
+ * @returns The body, bounded in size: its text, or a file such as an image
804
+ * or a PDF in base64
805
+ */
806
+ static async #body(res) {
807
+ const [type] = Header.shift(res.headers.get(Header.name.type));
808
+ if (res.ok && type?.toLowerCase() === "text/event-stream") {
809
+ // not read, it may never end: the route stops here
810
+ await res.body?.cancel();
811
+ return { type, live: true };
812
+ }
813
+ const bytes = await Codec.read(res.body, Mcp.#output);
814
+ if (!bytes)
815
+ throw new RpcError(-32603, "Response too large");
816
+ if (!type || Mcp.#texts.test(type)) {
817
+ try {
818
+ return { type, text: Codec.decode(bytes) };
819
+ }
820
+ catch {
821
+ // not text after all
822
+ }
823
+ }
824
+ return {
825
+ type: type || "application/octet-stream",
826
+ blob: Codec.Base64.encode(bytes),
827
+ };
828
+ }
829
+ /**
830
+ * Requests a page of the app as the agent.
831
+ *
832
+ * @param c Request context
833
+ * @param session Session the token authorizes
834
+ * @param url URL to request
835
+ * @param init Method and body
836
+ * @returns The response, or the form's issues instead of the redirect back to it
837
+ */
838
+ async #run(c, session, url, init) {
839
+ const language = this.#languages.get(c.req);
840
+ const req = new Request(url, {
841
+ ...init,
842
+ headers: {
843
+ accept: Mime.type.md,
844
+ origin: c.url.origin,
845
+ "sec-fetch-site": "same-origin",
846
+ ...(language?.accept && { "accept-language": language.accept }),
847
+ },
848
+ signal: c.req.signal,
849
+ });
850
+ const call = {
851
+ session,
852
+ tool: this.#tool(c),
853
+ };
854
+ agent.set(req, call);
855
+ const res = await this.#app.fetch(req, { ip: c.ip });
856
+ // the last page read, after any redirects
857
+ const content = res.headers.get("content-language");
858
+ if (language && content)
859
+ language.content = content;
860
+ if (!call.issues)
861
+ return res;
862
+ await res.body?.cancel();
863
+ return Mcp.#issues(call.issues);
864
+ }
865
+ /**
866
+ * Calls the app as the agent, following redirects to pages it can read.
867
+ *
868
+ * @param c Request context
869
+ * @param session Session the token authorizes
870
+ * @param url URL to request
871
+ * @param init Method and body
872
+ * @returns Tool result
873
+ */
874
+ async #fetch(c, session, url, init) {
875
+ let redirected;
876
+ /** The call writes, so a redirect from it means it was done */
877
+ const wrote = init !== undefined;
878
+ /** A page of this app, by its path */
879
+ const redirect = (page) => `Redirected to ${page.pathname}${page.search}`;
880
+ for (let i = 0;; i++) {
881
+ const res = await this.#run(c, session, url, init);
882
+ if (typeof res === "string")
883
+ return Mcp.#result(res, true);
884
+ const location = res.headers.get(Header.name.loc);
885
+ if (location && res.status >= 300 && res.status < 400) {
886
+ await res.body?.cancel();
887
+ const next = new URL(location, url);
888
+ const readable = this.#readable(c, next);
889
+ if (readable && i < Mcp.#redirects) {
890
+ url = redirected = next;
891
+ init = undefined;
892
+ continue;
893
+ }
894
+ // another site is where the app sends the user, such as a checkout,
895
+ // but the address of a page of this app that agents cannot read
896
+ // stays private, with any token in it
897
+ return Mcp.#result(next.origin !== c.url.origin
898
+ ? `Redirected to ${next.href}`
899
+ : readable
900
+ ? redirect(next)
901
+ : "Redirected");
902
+ }
903
+ // the route answered a write by redirecting, so the write is done. A
904
+ // page it sends to that then fails, such as on a rate limit, must not
905
+ // read as the write failing, or an agent would make it again
906
+ if (redirected && wrote && !res.ok) {
907
+ await res.body?.cancel();
908
+ return Mcp.#result(`${redirect(redirected)}, which could not be read: ${Mcp.#status(res)}`);
909
+ }
910
+ if (res.status >= 500)
911
+ throw await Mcp.#failed(res);
912
+ const { type, text, blob, live } = await Mcp.#body(res);
913
+ if (live)
914
+ return Mcp.#result(this.#stream(url), false,
915
+ // a link only where the agent can open it
916
+ this.#options.auth
917
+ ? undefined
918
+ : {
919
+ type: "resource_link",
920
+ uri: url.href,
921
+ name: url.pathname,
922
+ mimeType: type,
923
+ });
924
+ const [kind] = type?.split("/") ?? [];
925
+ return Mcp.#result([redirected && redirect(redirected), !res.ok && Mcp.#status(res), text]
926
+ .filter(Boolean)
927
+ .join("\n\n"), !res.ok,
928
+ // a file, as a person would download or see it
929
+ blob === undefined
930
+ ? undefined
931
+ : kind === "image" || kind === "audio"
932
+ ? { type: kind, data: blob, mimeType: type }
933
+ : {
934
+ type: "resource",
935
+ resource: { uri: this.#name(url), mimeType: type, blob },
936
+ });
937
+ }
938
+ }
939
+ /**
940
+ * @param res Response that is not a success
941
+ * @returns Its status, and when to try again if it says, such as a rate limit's
942
+ */
943
+ static #status(res) {
944
+ const retry = res.headers.get("retry-after");
945
+ return [
946
+ `${res.status} ${res.statusText}`.trim(),
947
+ // seconds, or a date
948
+ retry &&
949
+ `Retry after ${/^\d+$/.test(retry) ? `${retry} seconds` : retry}`,
950
+ ]
951
+ .filter(Boolean)
952
+ .join("\n\n");
953
+ }
954
+ /**
955
+ * A server error is the app's to fix, not something the agent can act on
956
+ * as it can on a form's issues, so it is a protocol error and not a result.
957
+ * The app's own error page stays with the app.
958
+ *
959
+ * @param res Response the app answered a failure with
960
+ * @returns The JSON-RPC internal error
961
+ */
962
+ static async #failed(res) {
963
+ await res.body?.cancel();
964
+ return new RpcError(-32603, "Internal error", 200, { status: res.status });
965
+ }
966
+ /**
967
+ * @param issues Form issues `c.data()` recorded
968
+ * @returns Message for the agent with each field's issue
969
+ */
970
+ static #issues(issues) {
971
+ return `422 Unprocessable Content\n\n${JSON.stringify({ issues })}`;
972
+ }
973
+ /**
974
+ * @param text Text for the agent
975
+ * @param isError The call failed
976
+ * @param file A file the route answered with, after the text if any
977
+ * @returns Tool result
978
+ */
979
+ static #result(text, isError = false, file) {
980
+ return {
981
+ content: [
982
+ ...(text || !file ? [{ type: "text", text }] : []),
983
+ ...(file ? [file] : []),
984
+ ],
985
+ isError,
986
+ };
987
+ }
988
+ }