@20baht/elysia-openapi-mcp 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/README.md CHANGED
@@ -1,3 +1,629 @@
1
- # Temporary Holding Version
1
+ # elysia-openapi-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Mount an [MCP](https://modelcontextprotocol.io) server on an existing
4
+ [Elysia](https://elysiajs.com) app with one line. Tools are derived from the
5
+ OpenAPI document that [`@elysiajs/openapi`](https://github.com/elysiajs/elysia-openapi)
6
+ already generates — no route changes, no schema duplication, no handler rewrites —
7
+ and the MCP authorization spec's **resource-server** obligations are enforced
8
+ for you.
9
+
10
+ ```ts
11
+ import { Elysia, t } from 'elysia'
12
+ import { openapi } from '@elysiajs/openapi'
13
+ import { mcpify } from '@20baht/elysia-openapi-mcp'
14
+
15
+ new Elysia()
16
+ .use(openapi())
17
+ .use(
18
+ mcpify({
19
+ auth: {
20
+ resource: 'https://api.example.com/mcp',
21
+ authorizationServers: ['https://auth.example.com'],
22
+ },
23
+ }),
24
+ )
25
+ .get('/users', () => db.users.findAll(), {
26
+ detail: { summary: 'List all users' },
27
+ response: t.Array(UserSchema),
28
+ })
29
+ .listen(3000)
30
+ ```
31
+
32
+ `POST https://api.example.com/mcp` now speaks MCP Streamable HTTP. `tools/list`
33
+ returns `list_users` with an `inputSchema` and an `outputSchema`; `tools/call`
34
+ runs the route through the full Elysia lifecycle and returns
35
+ `structuredContent`.
36
+
37
+ **Supported MCP spec revision:** `2026-07-28` (per-request envelope, served by
38
+ `@modelcontextprotocol/server` 2.x) and the 2025 revisions back to
39
+ `2024-11-05`, on one endpoint. Authorization is the resource-server model of
40
+ `2025-06-18` and later (RFC 9728 + RFC 8707). See
41
+ [Compatibility](#compatibility).
42
+
43
+ ## Install
44
+
45
+ ```sh
46
+ bun add @20baht/elysia-openapi-mcp @elysiajs/openapi
47
+ ```
48
+
49
+ Peer: `elysia >= 1.4.0`. `@elysiajs/openapi` is not imported, but its
50
+ `/openapi/json` route is what the plugin reads — mount it before `mcpify()`.
51
+
52
+ ## What you get
53
+
54
+ - **Tools from the OpenAPI document.** The generated document is the source of
55
+ truth. It is loaded in-process through `app.handle('/openapi/json')` on the
56
+ first MCP request (no socket needed), and re-derived whenever routes are
57
+ added. If that route exists but does not hand the document to a caller
58
+ without credentials (you guard `/openapi`), the plugin builds it with
59
+ `toOpenAPISchema(app)` instead (`@elysiajs/openapi` is an optional peer).
60
+ That build lacks the `openapi()` plugin's own options (`documentation`,
61
+ `exclude`, `references`, `mapJsonSchema`); pass `document` when you need
62
+ them.
63
+ - **Server name** from the document's `info.title` / `info.version`
64
+ (`openapi({ documentation: { info } })`), unless `name` / `version` are set.
65
+ `@elysiajs/openapi`'s placeholder (`Elysia Documentation`, `0.0.0`) is
66
+ ignored, leaving `@20baht/elysia-openapi-mcp` / `1.0.0`.
67
+ - **Names** from `detail.operationId`, falling back to `{verb}_{resource}`
68
+ (`GET /users` → `list_users`, `GET /users/:id` → `get_user`,
69
+ `POST /users` → `create_user`, `GET /users/:uid/posts` → `list_user_posts`).
70
+ The `getUsersById`-style id `@elysiajs/openapi` generates by itself is
71
+ recognised and ignored.
72
+ - **Descriptions** from `detail.summary` (+ `detail.description`); parameter
73
+ descriptions from each property's `description`, or, when it has none and
74
+ is a nullable union (`t.Nullable(t.Integer({ description }))`), from its
75
+ only non-null member.
76
+ - **One flat input schema** merging path params, query, and body, with the
77
+ origin of every property tracked so arguments are routed back correctly.
78
+ Collisions are renamed `body_id` / `query_id` and reported at startup.
79
+ Elysia's `t.Numeric()` is collapsed to a plain number at any depth.
80
+ - **`outputSchema` + `structuredContent`** from the route's `response` schema.
81
+ A schema is advertised only when every declared `2xx` response has JSON
82
+ content and they all share the same schema (a `204` next to a `200`, or
83
+ differing `200`/`201` schemas, yield none and a warning naming the tool),
84
+ because an advertised schema obliges every success to carry
85
+ `structuredContent`. Non-object responses (arrays, strings) are wrapped as
86
+ `{ result }` so they still get a schema; disable with
87
+ `wrapNonObjectOutput: false`. Routes without a response schema get none. If
88
+ a tool with an unwrapped object schema gets a non-object body at call time,
89
+ the call returns `isError: true` with an explanation instead of a result
90
+ that violates the schema. Text content is compact JSON.
91
+ `detail.mcp.output` sets the schema without a `response` (see below).
92
+ - **Path parameters are confined to their segment.** Values are
93
+ percent-encoded; `.` and `..` are rejected with `InvalidParams`, and the
94
+ built URL's pathname must equal the substituted template, so an argument can
95
+ never reach a route that is not exposed as a tool.
96
+ - **JSON request bodies only.** Operations whose request body has no JSON
97
+ media type (multipart / file uploads) are skipped with a warning.
98
+ - **Full lifecycle execution.** Each call becomes a synthetic `Request` handled
99
+ by `app.handle()`: derive / resolve / `beforeHandle` / validation / error
100
+ hooks and every plugin run exactly as for HTTP. Incoming headers
101
+ (`Authorization`, `Cookie`, …) are forwarded, so your existing guards apply
102
+ to agent traffic for free.
103
+ - **Streamable HTTP, both protocol eras.** `POST` for JSON-RPC; stateless, a
104
+ fresh server per request. `2026-07-28` clients (`server/discover`, `_meta`
105
+ envelope) and 2025-era clients (`initialize`) are told apart per request and
106
+ both get a plain JSON answer. The server never pushes messages, so an
107
+ authenticated `GET` / `DELETE` gets `405` with `Allow: POST` (anonymous ones
108
+ still get the `401` challenge). CORS + preflight included, with an origin
109
+ allowlist (`cors: { origins }`) and off by default in request mode (requested headers
110
+ such as `Mcp-Method` / `Mcp-Name` are allowed). The route claims the request body (`parse`
111
+ hook), so it works with `new Elysia({ aot: false })` (Cloudflare Workers) and
112
+ with app-level `onParse` hooks, no workaround needed.
113
+ - **Annotations.** `readOnlyHint` for `GET`, `destructiveHint` for `DELETE`,
114
+ `idempotentHint` for `GET`/`PUT`/`DELETE`, `title` from the summary.
115
+
116
+ ### Opting routes in and out
117
+
118
+ ```ts
119
+ .get('/health', () => 'ok', { detail: { mcp: false } }) // hidden from MCP
120
+ .use(mcpify({ auth, allRoutes: false })) // opt-in mode …
121
+ .get('/users', handler, { detail: { mcp: true } }) // … only these
122
+ .use(mcpify({ auth, tags: ['public'] })) // by OpenAPI tag
123
+ .use(mcpify({ auth, exclude: ['/internal', /^\/admin\//] })) // by path
124
+ ```
125
+
126
+ `detail.mcp` also takes an object, which opts the route in like `true` and sets
127
+ its [access rules](#per-tool-access): `{ scopes: ['notes:write'] }`,
128
+ `{ public: true }`, and its output schema: `{ output }`.
129
+
130
+ ### Output schema without a response check
131
+
132
+ A route's `response` schema gives the tool an `outputSchema`, and Elysia also
133
+ checks every answer against it. When answers are typed by inference and a
134
+ strict check would turn an unexpected field into a `422`, describe the result
135
+ for agents only:
136
+
137
+ ```ts
138
+ .get('/servers/:id', ({ params }) => cloud.server(params.id), {
139
+ detail: {
140
+ mcp: { output: t.Object({ id: t.String(), name: t.String({ description: 'Server name' }) }) },
141
+ },
142
+ })
143
+ ```
144
+
145
+ `detail.mcp.output` (TypeBox or plain JSON Schema) becomes the tool's
146
+ `outputSchema`, in place of one derived from `response`. Elysia does not
147
+ enforce it, and the result's `structuredContent` is the route's JSON as
148
+ returned. A non-object schema is wrapped as `{ result }` like a derived one.
149
+
150
+ ### Hearing tool calls
151
+
152
+ ```ts
153
+ import { isToolCall } from '@20baht/elysia-openapi-mcp'
154
+
155
+ app
156
+ .use(
157
+ mcpify({
158
+ auth,
159
+ onToolCall: async ({ tool, args, request, response, durationMs }) => {
160
+ await audit.write({ tool: tool.name, args, status: response.status, durationMs })
161
+ },
162
+ }),
163
+ )
164
+ .derive(({ request }) => ({ viaAgent: isToolCall(request) }))
165
+ ```
166
+
167
+ - `onToolCall` runs after each `tools/call` that reached the app, and is
168
+ awaited before the client gets the result. `request` is the synthetic
169
+ request (forwarded headers included, body spent); `response` is a copy of
170
+ the route's response, free to read. A throw is reported as
171
+ `on-tool-call-error` and the call still answers. Calls stopped before the
172
+ app (unknown tool, bad arguments, auth) are not reported.
173
+ - `isToolCall(request)` is `true` for that synthetic request, in every hook
174
+ and handler. The mark is the object itself (held in a `WeakSet`), not a
175
+ header, so an HTTP client cannot forge it and a `headers` policy cannot
176
+ strip it.
177
+
178
+ `detail.hide: true` (hidden from OpenAPI) also hides from MCP. OAuth endpoints
179
+ (`/authorize`, `/token`, `/register`, `/revoke`, `/introspect`, `/userinfo`)
180
+ and everything under `/.well-known/` are excluded by default
181
+ (`DEFAULT_EXCLUDED_PATHS`). `exclude` adds to those defaults; pass
182
+ `excludeDefaults: false` to drop them.
183
+
184
+ ### Recipe: scopes enforced inside the route
185
+
186
+ [`detail.mcp.scopes`](#per-tool-access) enforces scopes on `tools/call` only.
187
+ When the same OAuth token can also reach the route over plain HTTP, enforce the
188
+ scope _inside the route_ instead, with a tiny Elysia macro — it then applies
189
+ whether the call came over HTTP or through `tools/call`, while first-party
190
+ sessions (no OAuth scopes at all) are never limited:
191
+
192
+ ```ts
193
+ const scopePlugin = new Elysia({ name: 'scope' }).macro({
194
+ scope: (required: string) => ({
195
+ async beforeHandle({ request, status }) {
196
+ const user = await resolveUser(request) // your token → user (+ oauthScopes | null)
197
+ if (user?.oauthScopes && !user.oauthScopes.includes(required))
198
+ return status(403, { code: 'INSUFFICIENT_SCOPE', message: `needs "${required}"` })
199
+ },
200
+ }),
201
+ })
202
+
203
+ new Elysia({ prefix: '/it-service-requests' })
204
+ .use(scopePlugin)
205
+ .get('/', list, {
206
+ scope: 'requests:read',
207
+ detail: { mcp: true, summary: 'List IT service requests', description: 'Newest first …' },
208
+ query: listQuerySchema,
209
+ response: { 200: pageSchema, 401: errorSchema },
210
+ })
211
+ .post('/:id/decision', decide, {
212
+ scope: 'requests:write',
213
+ detail: { mcp: true, summary: 'Approve or reject an IT service request' },
214
+ body: t.Object({
215
+ decision: t.UnionEnum(['approved', 'rejected']),
216
+ comment: t.Optional(t.String()),
217
+ }),
218
+ })
219
+ ```
220
+
221
+ Tool names fall out of the path (`list_it_service_requests`,
222
+ `create_it_service_request`, `decide_it_service_request`), so a route factory
223
+ shared by many resources produces a consistent tool set for free. Put the
224
+ human-readable rules in `detail.description` — that text is what the agent
225
+ reads before calling, and the `response` schema becomes its `outputSchema`.
226
+
227
+ ## Authorization (resource server)
228
+
229
+ `mcpify` is **only** a resource server. It validates tokens; it never issues
230
+ them, never runs a login flow, never exposes `/authorize` or `/token`. Pair it
231
+ with any OAuth 2.1 authorization server —
232
+ [`@20baht/elysia-oauth-provider`](https://www.npmjs.com/package/elysia-oauth-provider)
233
+ is built for exactly this. No authorization server, just an API key or a
234
+ session cookie? Use [request mode](#request-mode-api-key-or-session-cookie).
235
+
236
+ ```
237
+ MCP client → POST /mcp (no token)
238
+ ← 401 WWW-Authenticate: Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"
239
+ → GET that URL
240
+ ← { "resource": "https://api.example.com/mcp", "authorization_servers": ["https://auth.example.com"] }
241
+ → OAuth 2.1 + PKCE against the AS with resource=https://api.example.com/mcp
242
+ → POST /mcp Authorization: Bearer <token>
243
+ mcpify → verify signature + iss + aud (+ exp, scopes) → unflatten args → app.handle() → your route
244
+ ```
245
+
246
+ What is enforced on every MCP request (`POST`, `GET`, `DELETE`; after it passes, `GET`/`DELETE` answer `405`):
247
+
248
+ | Check | Failure |
249
+ | --------------------------------------------------------- | ------------------------------------------------------------- |
250
+ | `Authorization: Bearer …` present | `401` + challenge with `resource_metadata` (RFC 9728 §5.1) |
251
+ | token genuine (signature, not expired) | `401 invalid_token` |
252
+ | `iss` is one of `authorizationServers` | `401 invalid_token` |
253
+ | **`aud` contains `resource`** — missing `aud` is rejected | `401 invalid_token` "audience does not include this resource" |
254
+ | `auth.scopes` ⊆ token scopes | `403 insufficient_scope` |
255
+
256
+ Then, per JSON-RPC message, the [per-tool access rules](#per-tool-access).
257
+
258
+ `resource` is compared after normalisation (trailing slash, fragment). A token
259
+ minted for `https://a.example/mcp` is rejected by `https://b.example/mcp` —
260
+ that is the whole point.
261
+
262
+ The client's bearer token is forwarded only into the **in-process** synthetic
263
+ request (so your route guards see it); the plugin makes no outbound calls with
264
+ it. If your handlers call upstream APIs, obtain the server's own credentials
265
+ there — do not replay the client's token (confused deputy).
266
+
267
+ ### Per-tool access
268
+
269
+ > [!WARNING]
270
+ > **What is exposed by default.** `allRoutes` defaults to `true`, so every
271
+ > OpenAPI operation not excluded becomes a tool. A tool without
272
+ > `detail.mcp.scopes` can be called by **any token issued for `auth.resource`**
273
+ > that holds `auth.scopes`. Nothing else limits it, apart from your route's own
274
+ > guards. When some routes need more than "signed in to this resource", do one
275
+ > of the following:
276
+ >
277
+ > - Set `auth.requireToolScopes: true`. Then only tools that declare
278
+ > `detail.mcp.scopes` or `detail.mcp: { public: true }` are exposed. The rest
279
+ > are left out of `tools/list` and `tools/call`, with a startup warning for
280
+ > each one.
281
+ > - Set `allRoutes: false` and opt routes in one at a time with `detail.mcp`.
282
+
283
+ **Scopes.** `detail.mcp: { scopes: [...] }` requires those scopes, on top of
284
+ `auth.scopes`, for `tools/call` of that tool. `tools/list` still shows every
285
+ tool. A token without them gets `403 insufficient_scope` whose challenge asks
286
+ for the scopes the token already has plus the missing ones, so a client that
287
+ steps up (re-authorizes with that `scope`) keeps access to the other tools.
288
+
289
+ ```ts
290
+ .get('/notes', list, { detail: { mcp: { scopes: ['notes:read'] } } })
291
+ .post('/notes', create, { detail: { mcp: { scopes: ['notes:read', 'notes:write'] } } })
292
+ ```
293
+
294
+ ```
295
+ POST /mcp tools/call create_note (token scope: "notes:read")
296
+ ← 403 WWW-Authenticate: Bearer …, error="insufficient_scope", scope="notes:read notes:write"
297
+ ```
298
+
299
+ **Anonymous access.** With `auth.allowAnonymous: true`, a request with no
300
+ `Authorization` header may connect (`initialize` / `server/discover`), `ping`,
301
+ list tools, and call tools marked `detail.mcp: { public: true }`. Any other
302
+ call gets the plain `401` challenge (with the tool's scopes as the `scope`
303
+ hint), which is what makes a host start sign-in at that moment rather than at
304
+ connection time. A token that _is_ present is always verified — a bad one is
305
+ `401 invalid_token`, never a silent downgrade to anonymous — and `auth.scopes`
306
+ apply to signed-in callers only. Unknown tool names get the same challenge, so
307
+ they cannot be probed signed out.
308
+
309
+ ```ts
310
+ mcpify({ auth: { resource, authorizationServers, allowAnonymous: true } })
311
+ .get('/status', status, { detail: { mcp: { public: true } } }) // callable signed out
312
+ .get('/notes', list, { detail: { mcp: { scopes: ['notes:read'] } } })
313
+ ```
314
+
315
+ Public tools still run through your route's own guards, with no
316
+ `Authorization` header forwarded.
317
+
318
+ ### Protected Resource Metadata
319
+
320
+ Served at `/.well-known/oauth-protected-resource` + the resource's path
321
+ (RFC 9728 §3.1), e.g. `/.well-known/oauth-protected-resource/mcp`:
322
+
323
+ ```json
324
+ {
325
+ "resource": "https://api.example.com/mcp",
326
+ "authorization_servers": ["https://auth.example.com"],
327
+ "bearer_methods_supported": ["header"],
328
+ "scopes_supported": ["expenses:read"],
329
+ "resource_name": "Expense API"
330
+ }
331
+ ```
332
+
333
+ Several `authorization_servers` are allowed; the client picks one and the
334
+ token's `iss` decides which JWKS is used.
335
+
336
+ ### Token verification
337
+
338
+ **Default — JWT via JWKS.** For each configured issuer the plugin discovers
339
+ `jwks_uri` from `/.well-known/oauth-authorization-server[/path]` (RFC 8414),
340
+ then OIDC discovery, and verifies with `jose` (`RS*`, `PS*`, `ES*`, `EdDSA`).
341
+ Keys are cached and refreshed on unknown `kid`, so rotation just works.
342
+
343
+ ```ts
344
+ auth: {
345
+ resource: 'https://api.example.com/mcp',
346
+ authorizationServers: ['https://auth.example.com'],
347
+ jwks: {
348
+ uri: 'https://auth.example.com/.well-known/jwks.json', // skip discovery (string, or { issuer: uri })
349
+ algorithms: ['ES256'],
350
+ clockTolerance: 30, // seconds, default 30
351
+ typ: 'at+jwt', // required JOSE typ header, default 'at+jwt'; false skips the check
352
+ fetch: customFetch, // e.g. app.handle-based in tests
353
+ },
354
+ }
355
+ ```
356
+
357
+ Tokens must carry the `typ: at+jwt` header (RFC 9068 §4; `application/at+jwt`
358
+ also matches). This keeps an ID token signed with the same keys from passing as
359
+ an access token. Set `jwks.typ: false` only for an authorization server that
360
+ does not set the header.
361
+
362
+ The same tolerance is applied to the gate's own `exp` check, so a token the
363
+ verifier accepts within the tolerance is not rejected a second time. It
364
+ defaults to `jwks.clockTolerance` (30) and to `0` when you supply `verify`;
365
+ set `auth.clockTolerance` (seconds) to override either.
366
+
367
+ **Co-located `@20baht/elysia-oauth-provider` (opaque or JWT tokens).** When both run in
368
+ one process you can validate against its store directly, which also honours
369
+ revocation:
370
+
371
+ ```ts
372
+ import { oauthProvider } from '@20baht/elysia-oauth-provider'
373
+ import { mcpify, verifyWithOAuthProvider } from '@20baht/elysia-openapi-mcp'
374
+
375
+ const auth = oauthProvider({ issuer, storage, resource: `${issuer}/mcp`, handleAuthorize })
376
+
377
+ new Elysia()
378
+ .use(auth)
379
+ .use(openapi())
380
+ .use(
381
+ mcpify({
382
+ auth: {
383
+ resource: `${issuer}/mcp`,
384
+ authorizationServers: [issuer],
385
+ verify: verifyWithOAuthProvider(auth.decorator.oauthProvider, issuer),
386
+ },
387
+ }),
388
+ )
389
+ ```
390
+
391
+ **Anything else.** `verify: (token, { request }) => TokenClaims | null` — return
392
+ the claims of a genuine token (`iss`, `sub`, `aud`, `scope`, `exp`, …) or
393
+ `null`. RFC 7662 introspection fits here. `iss`, `aud`, `exp` and scopes are
394
+ still checked by the plugin afterwards, so a verifier cannot accidentally
395
+ skip audience binding.
396
+
397
+ ### OpenAPI routes disabled in production?
398
+
399
+ `openapi({ enabled: false })` removes `/openapi/json`, and with no route there
400
+ is nothing to fall back from. Build the document in-process instead — same
401
+ generator, no HTTP route:
402
+
403
+ ```ts
404
+ import { toOpenAPISchema } from '@elysiajs/openapi'
405
+
406
+ mcpify({ document: ({ app }) => toOpenAPISchema(app), auth })
407
+ ```
408
+
409
+ ### Request mode (API key or session cookie)
410
+
411
+ An app that already guards its routes itself (an API-key header, a session
412
+ cookie) has no authorization server to point clients at. Give `auth` a
413
+ `verify(request)` instead of `resource` + `authorizationServers`:
414
+
415
+ ```ts
416
+ app.use(
417
+ mcpify({
418
+ auth: {
419
+ verify: (request) => request.headers.get('x-api-key') === process.env.API_KEY,
420
+ // or: async (request) => (await sessions.fromCookie(request.headers.get('cookie'))) !== null
421
+ },
422
+ }),
423
+ )
424
+ ```
425
+
426
+ - `verify` sees **every** MCP request, `initialize` and `tools/list` included,
427
+ before the body is read. It answers with one of:
428
+ - `true`: admitted, every tool.
429
+ - a refusal `{ status, code?, message }`: answered with that HTTP `status`
430
+ (400-599) and JSON-RPC error (`code` defaults to `-32001`), so a person
431
+ who is signed in but may not use the endpoint learns why.
432
+ - an admission `{ scopes?, tools?, readOnly? }`: admitted, with the tool set
433
+ filtered for this request. `scopes` are what the caller holds; a tool
434
+ that declares `detail.mcp.scopes` is kept only when all of them are
435
+ there (as in OAuth mode; tools without scopes are kept). `readOnly: true`
436
+ keeps the `readOnlyHint` tools (`GET` routes). `tools: (tool) => boolean`
437
+ is any other rule. A tool left out is missing from `tools/list`, and
438
+ calling it answers `Tool <name> not found`, exactly like a name that does
439
+ not exist.
440
+ - anything else (`false`, `1`, a thrown error): a bare `401` (fail closed).
441
+ A throw, a malformed refusal or admission, or an object that is neither
442
+ is reported once to `warn` (kind `verify-error`).
443
+
444
+ ```ts
445
+ verify: async (request) => {
446
+ const who = await sessions.fromCookie(request.headers.get('cookie'))
447
+ if (!who) return false
448
+ if (!who.project) return { status: 403, message: 'Pick a project first.' }
449
+ return who.key?.readOnly ? { readOnly: true } : { scopes: who.scopes }
450
+ }
451
+ ```
452
+
453
+ - A rejection is `401` with a JSON-RPC error body
454
+ (`{ "error": { "code": -32001, "message": "Unauthorized." } }`) and
455
+ `Cache-Control: no-store`, and **no** `WWW-Authenticate` header. A
456
+ `Bearer resource_metadata=...` challenge would tell MCP clients to start an
457
+ OAuth flow that cannot succeed here, so none is sent (strict RFC 9110 wants a
458
+ challenge on every `401`; the MCP-correct choice wins). Configure the client
459
+ to send the key or cookie up front.
460
+ - No Protected Resource Metadata document is served and `public` means
461
+ nothing. `detail.mcp.scopes` is enforced only for requests admitted with
462
+ `{ scopes }`; the first time a request is admitted without them (`true`,
463
+ or an admission with only `tools` / `readOnly`), a `scopes-not-enforced`
464
+ warning names each scoped tool.
465
+ - **CORS is off by default** in this mode: `verify` may trust a cookie, and a
466
+ reflected `Origin` would let any site call the tools from a signed-in
467
+ browser. Allow your own front ends with `cors: { origins: ['https://app.example'] }`
468
+ (or a predicate); other origins get no `Access-Control-Allow-Origin`.
469
+ `cors: true` reflects every origin and warns (`cors-reflects-origin`).
470
+ Preflight (`OPTIONS`) is answered without calling `verify`.
471
+ - Headers still reach the synthetic request, so your route guards run as
472
+ before on every `tools/call`.
473
+ - Mixing modes is an error: `verify` with any OAuth-only key
474
+ (`authorizationServers`, `jwks`, `scopes`, ...) but no `resource` throws at
475
+ startup rather than running an OAuth config as request mode. With
476
+ `resource` set, `verify` is the OAuth token verifier as before.
477
+
478
+ ### Running without auth
479
+
480
+ `mcpify()` requires either `auth` (OAuth or request mode) or
481
+ `unsafeNoAuth: true`, and throws at setup when given neither (or both). With
482
+ `unsafeNoAuth: true` anyone who can reach the endpoint can list the tools, and
483
+ calls are guarded only by your routes. A banner is printed at startup (kind
484
+ `unauthenticated`). Use it for local development only.
485
+
486
+ ```ts
487
+ mcpify({ unsafeNoAuth: true }) // local development only
488
+ mcpify({ unsafeNoAuth: true, warnings: { unauthenticated: false } }) // ...and quietly
489
+ ```
490
+
491
+ ## Configuration
492
+
493
+ ```ts
494
+ interface McpifyOptions {
495
+ path?: string // default "/mcp"
496
+ name?: string // MCP server name (initialize); default document info.title
497
+ version?: string // default document info.version
498
+ instructions?: string // how to use the tools as a whole (initialize)
499
+ allRoutes?: boolean // default true
500
+ tags?: string[] // only operations with one of these tags
501
+ exclude?: (string | RegExp)[] // added to DEFAULT_EXCLUDED_PATHS
502
+ excludeDefaults?: boolean // default true; false drops DEFAULT_EXCLUDED_PATHS
503
+ headerParams?: boolean // default false; expose `in: header` params as tool arguments
504
+ specPath?: string // default "/openapi/json"
505
+ document?: OpenAPIDocument | (ctx: { origin, app }) => OpenAPIDocument | Promise<OpenAPIDocument>
506
+ wrapNonObjectOutput?: boolean // default true
507
+ headers?: (incoming: Headers) => HeadersInit // which headers reach the synthetic request
508
+ cors?: boolean | { origins: string[] | ((origin: string) => boolean) }
509
+ // default false with `auth: { verify }`, true otherwise
510
+ onToolCall?: (e: { tool, args, request, response, durationMs }) => void | Promise<void>
511
+ warn?: (message: string, kind: McpifyWarningKind) => void // default console.warn, once per message per process
512
+ warnings?: Partial<Record<McpifyWarningKind, boolean>> // `false` silences that kind
513
+ unsafeNoAuth?: true // required when `auth` is omitted; exclusive with `auth`
514
+ auth?: { // request mode
515
+ verify: (request: Request) => RequestAuthResult | Promise<RequestAuthResult>
516
+ // RequestAuthResult = boolean
517
+ // | { status: number; code?: number; message: string } // refusal
518
+ // | { scopes?: string[]; tools?: (tool) => boolean; readOnly?: boolean } // admission
519
+ } | { // OAuth resource server
520
+ resource: string
521
+ authorizationServers: string[]
522
+ verify?: TokenVerifier
523
+ prmPath?: string // default "/.well-known/oauth-protected-resource<resource path>"
524
+ scopes?: string[] // required on every signed-in MCP request
525
+ allowAnonymous?: boolean // default false; tokenless discovery + `public` tools
526
+ requireToolScopes?: boolean // default false; expose only tools with scopes or `public`
527
+ scopesSupported?: string[] // advertised in PRM + challenge
528
+ resourceName?: string
529
+ resourceDocumentation?: string
530
+ clockTolerance?: number // exp slack in seconds; default jwks.clockTolerance (30), 0 with `verify`
531
+ jwks?: { uri?, algorithms?, clockTolerance?, typ?, fetch? }
532
+ }
533
+ }
534
+ ```
535
+
536
+ Mount `mcpify()` on the root app (the instance whose `handle()` sees every
537
+ route). Routes declared after `.use(mcpify())` in the chain are included.
538
+ Routes nested under the MCP path itself (`/mcp/expenses`, the natural layout
539
+ when tokens are audience-bound to `…/mcp`) drop that prefix in derived names:
540
+ `list_expenses`, not `list_mcp_expenses`.
541
+
542
+ ### Header parameters
543
+
544
+ By default `in: 'header'` parameters are not tool arguments. With
545
+ `headerParams: true` they are flattened into the input schema (a collision
546
+ with path / query is renamed `header_<name>`, same as `body_<name>`) and sent as
547
+ headers on the synthetic request, overriding any forwarded header of the same
548
+ name. `Accept`, `Content-Type` and `Authorization` parameters are ignored, as
549
+ OpenAPI specifies.
550
+
551
+ ### Errors
552
+
553
+ If the OpenAPI document cannot be loaded, the client gets a `500` with a
554
+ generic `server_error` description; the detail goes to `warn`.
555
+
556
+ ### Startup warnings
557
+
558
+ Emitted once each per `mcpify()` instance, through `warn(message, kind)`. The
559
+ default sink (`console.warn`) prints each distinct message once per process,
560
+ so an app mounted twice, or rebuilt in every test, does not repeat itself; a
561
+ custom `warn` gets every warning of its instance. Turn one kind off with
562
+ `warnings: { kind: false }`; the rest stay on. An unknown kind throws, so a
563
+ typo does not quietly keep the noise. The list is exported as
564
+ `MCPIFY_WARNING_KINDS`.
565
+
566
+ | Kind | When |
567
+ | ------------------------ | ------------------------------------------------------------------------------------------ |
568
+ | `unauthenticated` | `unsafeNoAuth: true` (the startup banner) |
569
+ | `path-param-description` | a path parameter without `description` |
570
+ | `argument-description` | a query / header / body argument without `description` (agents choose from these) |
571
+ | `argument-collision` | a name in more than one of path / query / header / body (renamed `body_<name>`, …) |
572
+ | `duplicate-name` | two operations derive one tool name (the later gets `_2`; set `detail.operationId`) |
573
+ | `stray-path-param` | a declared path parameter missing from the path template |
574
+ | `header-param` | a required header parameter that is not a tool argument (no `headerParams`) |
575
+ | `non-json-body` | an operation skipped because its request body has no JSON media type |
576
+ | `no-output-schema` | `2xx` responses differ or lack JSON content, or `detail.mcp.output` is malformed |
577
+ | `invalid-scopes` | `detail.mcp.scopes` is not a list of OAuth scope tokens |
578
+ | `scopes-not-enforced` | `detail.mcp.scopes` set with `unsafeNoAuth`, or request mode admitted without `{ scopes }` |
579
+ | `tool-hidden` | a tool left out by `auth.requireToolScopes` |
580
+ | `no-tools` | the document yielded no tools |
581
+ | `document` | the OpenAPI document could not be loaded (at request time; the client got a `500`) |
582
+ | `verify-error` | request-mode `auth.verify` threw or returned a malformed result (the client got a `401`) |
583
+ | `on-tool-call-error` | `onToolCall` threw or rejected (the tool call still answered) |
584
+ | `cors-reflects-origin` | `cors: true` set explicitly with `auth: { verify }` |
585
+
586
+ ```ts
587
+ mcpify({
588
+ auth,
589
+ // Elysia path params rarely carry a description; keep the rest.
590
+ warnings: { 'path-param-description': false },
591
+ // Or route by kind yourself:
592
+ warn: (message, kind) => (kind === 'document' ? log.error(message) : log.warn(message)),
593
+ })
594
+ ```
595
+
596
+ `deriveTools()` returns the same entries as `diagnostics: { kind, message }[]`
597
+ next to the plain `warnings: string[]`.
598
+
599
+ ## Compatibility
600
+
601
+ | Component | Version / revision |
602
+ | --------------------------- | ------------------------------------------------------------------------------------------------------------ |
603
+ | MCP authorization semantics | `2025-06-18` and later (`2025-11-25`, `2026-07-28`): RS-only model, RFC 9728 PRM, RFC 8707 audience |
604
+ | MCP transport | Streamable HTTP via `@modelcontextprotocol/server` ^2.3: `2026-07-28`, and `2025-11-25` down to `2024-11-05` |
605
+ | Not supported | `2025-03-26` "MCP server is the AS" model (superseded); resources / prompts (tools only) |
606
+ | Elysia | `^1.4.0` |
607
+ | `@elysiajs/openapi` | `>= 1.4` (`detail.*` pass-through, `/openapi/json`) |
608
+ | Bun | `>= 1.2` |
609
+
610
+ ## Prior art
611
+
612
+ Tool derivation and the naming convention follow
613
+ [`@8monkey/elysia-mcp`](https://github.com/8monkey-ai/elysia-mcp), which reads
614
+ Elysia's route table directly. This package reads the OpenAPI document instead
615
+ (so `@elysiajs/openapi` options such as `exclude`, `references` and
616
+ `mapJsonSchema` are honoured) and adds the resource-server layer.
617
+
618
+ ## Development
619
+
620
+ ```sh
621
+ bun install
622
+ bun test # unit + integration + oauth-provider e2e
623
+ bun run --filter @20baht/elysia-openapi-mcp build
624
+ bun run --filter example-basic start # examples/openapi-mcp-basic on :3000
625
+ ```
626
+
627
+ ## License
628
+
629
+ MIT
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Per-message access policy, applied after the token gate and before the SDK
3
+ * sees the payload: anonymous callers reach only discovery and public tools,
4
+ * and each tool's `detail.mcp.scopes` is enforced with a step-up challenge.
5
+ */
6
+ import type { AuthInfo } from '@modelcontextprotocol/server';
7
+ import type { ToolSpec } from '../openapi/derive.js';
8
+ import type { ResolvedAuth } from './resolve.js';
9
+ /** A tool's own `detail.mcp.scopes` are all among `granted` (vacuously true without any). */
10
+ export declare const holdsToolScopes: (tool: ToolSpec, granted: readonly string[]) => boolean;
11
+ /** `null` lets the payload through; otherwise the challenge to answer with. */
12
+ export declare function checkAccess(body: unknown, tools: ReadonlyMap<string, ToolSpec>, auth: ResolvedAuth, authInfo: AuthInfo | undefined): Response | null;
13
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/auth/access.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAuBjD,6FAA6F;AAC7F,eAAO,MAAM,eAAe,GAAI,MAAM,QAAQ,EAAE,SAAS,SAAS,MAAM,EAAE,YAC3B,CAAC;AAIhD,+EAA+E;AAE/E,wBAAgB,WAAW,CACzB,IAAI,EAAE,OAAO,EACb,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,EACpC,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,QAAQ,GAAG,SAAS,GAC7B,QAAQ,GAAG,IAAI,CAgCjB"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The resource-server gate in front of `/mcp`. Every failure is a proper
3
+ * RFC 6750 / RFC 9728 response so clients can discover the authorization
4
+ * server and retry.
5
+ */
6
+ import type { AuthInfo } from '@modelcontextprotocol/server';
7
+ import { type BearerErrorCode } from './bearer.js';
8
+ import type { ResolvedAuth } from './resolve.js';
9
+ import type { TokenClaims } from './verify.js';
10
+ export declare const NO_STORE: Record<string, string>;
11
+ export type AuthOutcome = {
12
+ ok: true;
13
+ claims: TokenClaims;
14
+ authInfo: AuthInfo;
15
+ } | {
16
+ ok: false;
17
+ response: Response;
18
+ };
19
+ /** An RFC 6750 error response carrying the RFC 9728 `resource_metadata` challenge. */
20
+ export declare function challengeResponse(auth: ResolvedAuth, status: 401 | 403, error: BearerErrorCode | undefined, description: string | undefined, scope: readonly string[] | undefined): Response;
21
+ /** Does `aud` (string or array) name this resource? Absent → false. */
22
+ export declare function audienceMatches(aud: unknown, resource: string): boolean;
23
+ export declare function authenticate(request: Request, auth: ResolvedAuth): Promise<AuthOutcome>;
24
+ //# sourceMappingURL=authenticate.d.ts.map