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