mcp-trellis 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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +595 -0
  3. package/dist/adapters/node.d.ts +47 -0
  4. package/dist/adapters/node.d.ts.map +1 -0
  5. package/dist/adapters/node.js +116 -0
  6. package/dist/adapters/node.js.map +1 -0
  7. package/dist/app.d.ts +69 -0
  8. package/dist/app.d.ts.map +1 -0
  9. package/dist/app.js +101 -0
  10. package/dist/app.js.map +1 -0
  11. package/dist/auth/bearer.d.ts +21 -0
  12. package/dist/auth/bearer.d.ts.map +1 -0
  13. package/dist/auth/bearer.js +32 -0
  14. package/dist/auth/bearer.js.map +1 -0
  15. package/dist/clients.d.ts +33 -0
  16. package/dist/clients.d.ts.map +1 -0
  17. package/dist/clients.js +63 -0
  18. package/dist/clients.js.map +1 -0
  19. package/dist/dispatch.d.ts +7 -0
  20. package/dist/dispatch.d.ts.map +1 -0
  21. package/dist/dispatch.js +79 -0
  22. package/dist/dispatch.js.map +1 -0
  23. package/dist/http.d.ts +17 -0
  24. package/dist/http.d.ts.map +1 -0
  25. package/dist/http.js +38 -0
  26. package/dist/http.js.map +1 -0
  27. package/dist/jsonrpc.d.ts +32 -0
  28. package/dist/jsonrpc.d.ts.map +1 -0
  29. package/dist/jsonrpc.js +17 -0
  30. package/dist/jsonrpc.js.map +1 -0
  31. package/dist/methods.d.ts +52 -0
  32. package/dist/methods.d.ts.map +1 -0
  33. package/dist/methods.js +114 -0
  34. package/dist/methods.js.map +1 -0
  35. package/dist/oauth/authorize.d.ts +3 -0
  36. package/dist/oauth/authorize.d.ts.map +1 -0
  37. package/dist/oauth/authorize.js +109 -0
  38. package/dist/oauth/authorize.js.map +1 -0
  39. package/dist/oauth/base64url.d.ts +5 -0
  40. package/dist/oauth/base64url.d.ts.map +1 -0
  41. package/dist/oauth/base64url.js +17 -0
  42. package/dist/oauth/base64url.js.map +1 -0
  43. package/dist/oauth/clientauth.d.ts +19 -0
  44. package/dist/oauth/clientauth.d.ts.map +1 -0
  45. package/dist/oauth/clientauth.js +76 -0
  46. package/dist/oauth/clientauth.js.map +1 -0
  47. package/dist/oauth/codes.d.ts +30 -0
  48. package/dist/oauth/codes.d.ts.map +1 -0
  49. package/dist/oauth/codes.js +93 -0
  50. package/dist/oauth/codes.js.map +1 -0
  51. package/dist/oauth/constants.d.ts +32 -0
  52. package/dist/oauth/constants.d.ts.map +1 -0
  53. package/dist/oauth/constants.js +30 -0
  54. package/dist/oauth/constants.js.map +1 -0
  55. package/dist/oauth/metadata.d.ts +45 -0
  56. package/dist/oauth/metadata.d.ts.map +1 -0
  57. package/dist/oauth/metadata.js +36 -0
  58. package/dist/oauth/metadata.js.map +1 -0
  59. package/dist/oauth/pkce.d.ts +4 -0
  60. package/dist/oauth/pkce.d.ts.map +1 -0
  61. package/dist/oauth/pkce.js +17 -0
  62. package/dist/oauth/pkce.js.map +1 -0
  63. package/dist/oauth/redirect.d.ts +11 -0
  64. package/dist/oauth/redirect.d.ts.map +1 -0
  65. package/dist/oauth/redirect.js +26 -0
  66. package/dist/oauth/redirect.js.map +1 -0
  67. package/dist/oauth/resource.d.ts +7 -0
  68. package/dist/oauth/resource.d.ts.map +1 -0
  69. package/dist/oauth/resource.js +44 -0
  70. package/dist/oauth/resource.js.map +1 -0
  71. package/dist/oauth/revoke.d.ts +4 -0
  72. package/dist/oauth/revoke.d.ts.map +1 -0
  73. package/dist/oauth/revoke.js +30 -0
  74. package/dist/oauth/revoke.js.map +1 -0
  75. package/dist/oauth/router.d.ts +18 -0
  76. package/dist/oauth/router.d.ts.map +1 -0
  77. package/dist/oauth/router.js +105 -0
  78. package/dist/oauth/router.js.map +1 -0
  79. package/dist/oauth/scope.d.ts +11 -0
  80. package/dist/oauth/scope.d.ts.map +1 -0
  81. package/dist/oauth/scope.js +24 -0
  82. package/dist/oauth/scope.js.map +1 -0
  83. package/dist/oauth/token.d.ts +3 -0
  84. package/dist/oauth/token.d.ts.map +1 -0
  85. package/dist/oauth/token.js +137 -0
  86. package/dist/oauth/token.js.map +1 -0
  87. package/dist/oauth/types.d.ts +115 -0
  88. package/dist/oauth/types.d.ts.map +1 -0
  89. package/dist/oauth/types.js +28 -0
  90. package/dist/oauth/types.js.map +1 -0
  91. package/dist/oauth/wellknown.d.ts +8 -0
  92. package/dist/oauth/wellknown.d.ts.map +1 -0
  93. package/dist/oauth/wellknown.js +35 -0
  94. package/dist/oauth/wellknown.js.map +1 -0
  95. package/dist/protocol.d.ts +4 -0
  96. package/dist/protocol.d.ts.map +1 -0
  97. package/dist/protocol.js +14 -0
  98. package/dist/protocol.js.map +1 -0
  99. package/dist/registry.d.ts +37 -0
  100. package/dist/registry.d.ts.map +1 -0
  101. package/dist/registry.js +61 -0
  102. package/dist/registry.js.map +1 -0
  103. package/dist/server.d.ts +11 -0
  104. package/dist/server.d.ts.map +1 -0
  105. package/dist/server.js +11 -0
  106. package/dist/server.js.map +1 -0
  107. package/dist/tools.d.ts +80 -0
  108. package/dist/tools.d.ts.map +1 -0
  109. package/dist/tools.js +97 -0
  110. package/dist/tools.js.map +1 -0
  111. package/dist/validate.d.ts +23 -0
  112. package/dist/validate.d.ts.map +1 -0
  113. package/dist/validate.js +88 -0
  114. package/dist/validate.js.map +1 -0
  115. package/docs/diagrams/architecture.svg +1 -0
  116. package/docs/diagrams/first-connection.svg +1 -0
  117. package/docs/diagrams/ports.svg +1 -0
  118. package/package.json +68 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amir Ben Shimol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,595 @@
1
+ # mcp-trellis
2
+
3
+ [![CI](https://github.com/amir1824/mcp-trellis/actions/workflows/ci.yml/badge.svg)](https://github.com/amir1824/mcp-trellis/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+
6
+ **Host-agnostic MCP + OAuth ports** — you bring the runtime and IdP; the library owns the connector protocol.
7
+
8
+ Web-standard `Request` → `Response`. Same handler on Cloudflare Workers, Next.js App Router, Deno, Bun, and Node HTTP via `mcp-trellis/node`. Zero runtime dependencies.
9
+
10
+ ## Why mcp-trellis
11
+
12
+ Pick this when you want **the whole connector stack in one package** — the MCP
13
+ handler *and* a real OAuth 2.1 authorization server — with no database to run
14
+ and no vendor to sign up with:
15
+
16
+ | | mcp-trellis | Official MCP SDK | `workers-oauth-provider` | `@mcpauth/auth` | Auth0 / Clerk / Authlete |
17
+ |---|---|---|---|---|---|
18
+ | MCP handler | ✅ | ✅ | ❌ | ❌ | ❌ |
19
+ | OAuth 2.1 authorization server | ✅ | ❌ bring your own | ✅ | ✅ | ✅ |
20
+ | Runtime | any Web-standard | any Web-standard | Workers only | Node | — |
21
+ | Database | none | — | KV (optional) | **required** — Prisma/Drizzle, with migrations | — |
22
+ | Runtime dependencies | **zero** | several | several | several | — |
23
+ | Self-hosted | ✅ | ✅ | ✅ | ✅ | ❌ SaaS |
24
+ | Named connector profiles (Claude / Gemini / Codex), enforced not just advertised | ✅ | ❌ | ❌ | ❌ | ❌ |
25
+
26
+ Prefer the official SDK when you already have (or want) a separate
27
+ authorization server — it doesn't ship one. Prefer `workers-oauth-provider`
28
+ when you're committed to Workers and want Cloudflare's own implementation.
29
+ Prefer a managed IdP (Auth0, Clerk, Authlete, WorkOS) when you'd rather pay
30
+ than operate one. Prefer mcp-trellis when you want the protocol layer and the
31
+ AS in one package, with **nothing to provision** — you still own login, token
32
+ minting, and storage; the library owns the protocol.
33
+
34
+ ## Requirements
35
+
36
+ - **Node ≥ 20** for Node hosts (global WebCrypto in ESM)
37
+ - Or any runtime with WebCrypto + `fetch` (Workers, Deno, Bun)
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ npm install mcp-trellis
43
+ ```
44
+
45
+ ## 60-second server
46
+
47
+ One call mounts the MCP endpoint, the OAuth authorization server, and both
48
+ discovery documents — and routes between them:
49
+
50
+ ```ts
51
+ import { createMcpApp } from "mcp-trellis";
52
+
53
+ const app = createMcpApp({
54
+ serverInfo: { name: "demo", version: "1.0.0" },
55
+ clients: ["claude"],
56
+ tools: [
57
+ {
58
+ name: "echo",
59
+ description: "Echo text back",
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: { text: { type: "string" } },
63
+ required: ["text"],
64
+ },
65
+ scope: "mcp",
66
+ handler: (_ctx, args) => String(args.text ?? ""),
67
+ },
68
+ ],
69
+ auth: {
70
+ codeSecret: process.env.OAUTH_CODE_SECRET!,
71
+ resolveUser: async (req) => getSession(req),
72
+ loginUrl: (_req, next) => `/login?next=${encodeURIComponent(next)}`,
73
+ mintAccessToken: async ({ userId, scope, resource }) => ({
74
+ // Embed `resource` as the token audience (RFC 8707).
75
+ accessToken: await issueUserToken(userId, { aud: resource, scope }),
76
+ expiresIn: 3600,
77
+ }),
78
+ verifyToken: async (token) => {
79
+ const claims = await readUserToken(token);
80
+ if (!claims) return null;
81
+ return {
82
+ userId: claims.sub,
83
+ scopes: claims.scope.split(" "),
84
+ audience: claims.aud,
85
+ };
86
+ },
87
+ },
88
+ });
89
+
90
+ export default { fetch: (req: Request) => app.fetch(req) };
91
+ ```
92
+
93
+ You return the token's `audience`; **the library rejects tokens minted for a
94
+ different resource** before any tool runs. That check is the one preventing
95
+ confused-deputy attacks, so it is not yours to remember.
96
+
97
+ Smoke-test with `initialize` (public — no Bearer needed):
98
+
99
+ ```bash
100
+ curl -s http://127.0.0.1:8787/mcp \
101
+ -H 'content-type: application/json' \
102
+ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}'
103
+ ```
104
+
105
+ ## Client compatibility
106
+
107
+ Name the connector clients you serve; the AS is configured to match.
108
+
109
+ | Client | Registration | Token endpoint auth | Notes |
110
+ |--------|--------------|---------------------|-------|
111
+ | `claude` | Dynamic (DCR), public + PKCE | `none` | Claude Custom Connectors callback is allowlisted for you |
112
+ | `gemini` | **Pre-registered**, confidential | `client_secret_basic`, `client_secret_post` | Gemini Enterprise is registered with your org's IdP — supply `auth.clientStore` |
113
+ | `codex` | OAuth 2.1 per MCP auth spec, public + PKCE | `none` | ChatGPT / Codex share one connector contract |
114
+
115
+ ```ts
116
+ createMcpApp({
117
+ clients: ["claude", "gemini"],
118
+ auth: {
119
+ // …
120
+ clientStore: {
121
+ get: async (clientId) => lookupClient(clientId),
122
+ verifySecret: async (clientId, presented) =>
123
+ checkSecret(clientId, presented),
124
+ },
125
+ },
126
+ });
127
+ ```
128
+
129
+ Naming a pre-registered client without a `clientStore` throws at construction
130
+ rather than failing at the first token exchange. Secret storage and comparison
131
+ stay in your `clientStore` — the library never sees or persists credentials.
132
+
133
+ Naming only pre-registered clients (`clients: ["gemini"]`, no `claude` /
134
+ `codex`) sets `allowUnregisteredClients: false`: `/register` is unmounted
135
+ and dropped from AS metadata, unknown ids are rejected with
136
+ `unauthorized_client` at `authorize` and `invalid_client` at `token` and
137
+ `revoke`. Naming `claude` or `codex` alongside `gemini` reopens dynamic
138
+ registration.
139
+
140
+ ## How it fits together
141
+
142
+ What `createMcpApp` wires for you — two pieces, one deciding which requests go
143
+ to the other:
144
+
145
+ ![Architecture: connector → edge → OAuth or MCP → your ports](docs/diagrams/architecture.svg)
146
+
147
+ Typical first-connection path:
148
+
149
+ ![Sequence: OAuth authorize and token, then MCP tool call](docs/diagrams/first-connection.svg)
150
+
151
+ You only touch this routing directly if you skip `createMcpApp` — see
152
+ [Advanced: compose the primitives](#advanced-compose-the-primitives).
153
+
154
+ ## Package surface
155
+
156
+ | Import | What you get |
157
+ |--------|----------------|
158
+ | `mcp-trellis` | `createMcpApp`, client profiles, MCP handler, tool registry, bearer helpers, HTTP utils |
159
+ | `mcp-trellis/oauth` | OAuth 2.1 AS router, PKCE, auth codes, client auth, metadata |
160
+ | `mcp-trellis/node` | `asNodeHandler` + `resolveOrigin` for Node `(req, res)` |
161
+
162
+ `createMcpApp` is the batteries-included layer. `createMcpHandler` and
163
+ `createOAuthRouter` remain exported and unchanged — reach for them when you want
164
+ to own the routing or mount the two halves separately.
165
+
166
+ ### Default OAuth routes
167
+
168
+ With defaults `resourcePath: "/mcp"` and `oauthPath: "/mcp/oauth"`:
169
+
170
+ | Path | Purpose |
171
+ |------|---------|
172
+ | `/.well-known/oauth-protected-resource` (+ `/mcp`) | Protected resource metadata |
173
+ | `/.well-known/oauth-authorization-server` (+ `/mcp`) | Authorization server metadata |
174
+ | `/mcp/oauth/register` | Dynamic client registration (unmounted when DCR is off) |
175
+ | `/mcp/oauth/authorize` | Authorization endpoint |
176
+ | `/mcp/oauth/token` | Token endpoint |
177
+ | `/mcp/oauth/revoke` | Token revocation (RFC 7009; mounted only when `revokeToken` is set) |
178
+
179
+ ## Recipes
180
+
181
+ ### Cloudflare Worker, Next.js, Deno, Bun
182
+
183
+ `createMcpApp` returns a plain `fetch`, so the same object mounts everywhere:
184
+
185
+ ```ts
186
+ // Worker
187
+ export default { fetch: (req: Request, env: Env) => buildApp(env).fetch(req) };
188
+
189
+ // Next.js App Router — app/[[...mcp]]/route.ts
190
+ export const GET = (req: Request) => app.fetch(req);
191
+ export const POST = (req: Request) => app.fetch(req);
192
+ export const OPTIONS = (req: Request) => app.fetch(req);
193
+
194
+ // Node / Express / Cloud Run
195
+ import { asNodeHandler } from "mcp-trellis/node";
196
+ export const mcp = asNodeHandler(app, { origin: process.env.MCP_PUBLIC_ORIGIN! });
197
+ ```
198
+
199
+ The Node bridge reads the request stream when `req.body` is absent, so raw
200
+ `http.createServer` works without a body-parser. Runnable recipe:
201
+ [`examples/http-server.ts`](examples/http-server.ts).
202
+
203
+ ## Advanced: compose the primitives
204
+
205
+ Skip `createMcpApp` when you want to own the routing. Same behavior, more wiring:
206
+
207
+ ```ts
208
+ import { createMcpHandler, createToolRegistry, parseBearer } from "mcp-trellis";
209
+ import { createOAuthRouter } from "mcp-trellis/oauth";
210
+
211
+ type Ctx = { userId: string };
212
+ type Env = { OAUTH_CODE_SECRET: string };
213
+
214
+ const registry = createToolRegistry<Ctx>([
215
+ {
216
+ name: "ping_db",
217
+ description: "Health check",
218
+ inputSchema: { type: "object", properties: {} },
219
+ scope: "read",
220
+ handler: async () => "ok",
221
+ },
222
+ ]);
223
+
224
+ const handler = createMcpHandler<Ctx>({
225
+ registry,
226
+ serverInfo: { name: "my-app", version: "1.0.0" },
227
+ instructions: "Tools available to authenticated clients.",
228
+ wwwAuthenticate: (req) => ({
229
+ realm: "my-app",
230
+ resourceMetadataUrl: `${new URL(req.url).origin}/.well-known/oauth-protected-resource/mcp`,
231
+ }),
232
+ ports: {
233
+ authenticate: async (req) => {
234
+ const token = parseBearer(req.headers.get("authorization"));
235
+ if (!token) return null;
236
+ // Reject tokens whose aud ≠ this server's canonical resource.
237
+ return { id: "user-1", scopes: ["read"] };
238
+ },
239
+ context: async (_req, principal) => ({
240
+ userId: principal?.id ?? "",
241
+ }),
242
+ },
243
+ });
244
+
245
+ export default {
246
+ async fetch(request: Request, env: Env): Promise<Response> {
247
+ const oauth = createOAuthRouter({
248
+ ports: {
249
+ codeSecret: env.OAUTH_CODE_SECRET,
250
+ resolveUser: async () => ({ id: "user-1" }),
251
+ loginUrl: (req, next) =>
252
+ `${new URL(req.url).origin}/login?next=${encodeURIComponent(next)}`,
253
+ mintAccessToken: async ({ userId, resource }) => ({
254
+ // Embed `resource` as the token audience (RFC 8707).
255
+ accessToken: await issueUserToken(userId, { aud: resource }),
256
+ expiresIn: 3600,
257
+ scope: "mcp",
258
+ }),
259
+ },
260
+ });
261
+
262
+ const oauthResponse = await oauth.tryHandle(request);
263
+ if (oauthResponse) return oauthResponse;
264
+ if (new URL(request.url).pathname === "/mcp") return handler.fetch(request);
265
+ return new Response("Not found", { status: 404 });
266
+ },
267
+ };
268
+ ```
269
+
270
+ ### Next.js App Router
271
+
272
+ Delegate Web `Request` straight through — same handler as above:
273
+
274
+ ```ts
275
+ // app/mcp/route.ts
276
+ import { handler, oauth } from "@/lib/mcp"; // your shared setup
277
+
278
+ export async function GET(req: Request) {
279
+ const oauthResponse = await oauth.tryHandle(req);
280
+ if (oauthResponse) return oauthResponse;
281
+ return handler.fetch(req);
282
+ }
283
+
284
+ export async function POST(req: Request) {
285
+ const oauthResponse = await oauth.tryHandle(req);
286
+ if (oauthResponse) return oauthResponse;
287
+ return handler.fetch(req);
288
+ }
289
+
290
+ export async function OPTIONS() {
291
+ return handler.fetch(new Request("https://local/mcp", { method: "OPTIONS" }));
292
+ }
293
+ ```
294
+
295
+ Also mount `.well-known/*` and `/mcp/oauth/*` the same way (or route everything through one catch-all that calls `oauth.tryHandle` first).
296
+
297
+ ### Node HTTP `(req, res)`
298
+
299
+ Express, Cloud Functions, Cloud Run, `http.createServer` — bridge with
300
+ `asNodeHandler`. Runnable recipe: [`examples/http-server.ts`](examples/http-server.ts)
301
+ (`npx tsx examples/http-server.ts`).
302
+
303
+ ## Ports — what you implement
304
+
305
+ The library stays protocol-shaped. Your app plugs in the seams:
306
+
307
+ ![Ports: library calls into your authenticate, context, resolveUser, mintAccessToken](docs/diagrams/ports.svg)
308
+
309
+ ### App (`createMcpApp`)
310
+
311
+ | Port | Role |
312
+ |------|------|
313
+ | `verifyToken(token, req)` | Decode a bearer and return `{ userId, scopes, audience }`, or `null`. **The library compares `audience` against this server's canonical resource** — you cannot forget the check |
314
+ | `resolveUser`, `loginUrl`, `mintAccessToken`, `codeSecret` | Same as the OAuth ports below |
315
+ | `clientStore?` | Pre-registered clients; required for confidential clients like Gemini |
316
+ | `refreshAccessToken?` | If set, metadata advertises `refresh_token` |
317
+ | `revokeToken?` | RFC 7009; presence mounts `/revoke` and advertises `revocation_endpoint` |
318
+ | `context?`, `audit?` | Same as the MCP ports below; `context` defaults to an empty object |
319
+
320
+ ### MCP (`createMcpHandler`)
321
+
322
+ The lower-level handler. Here the audience check is **yours** — prefer
323
+ `createMcpApp` unless you need the control.
324
+
325
+ | Port | Role |
326
+ |------|------|
327
+ | `authenticate(req, method, tool?)` | Return `{ id, scopes }`, or `null` → 401 + `WWW-Authenticate`. **Must reject tokens whose audience is not this server’s canonical resource** (see Threat model) |
328
+ | `context(req, principal)` | Build per-request ctx for tools (DB, env, …) |
329
+ | `audit?(entry)` | Optional telemetry: tool results **and** every denial (bad token, missing scope, query-string token). `entry.method` is `""` for transport-level denials made before parsing. Throwing from this port never fails the request |
330
+
331
+ `wwwAuthenticate` can be a static object or `(req) => …` when the PRM URL depends on origin.
332
+
333
+ By default `initialize`, `ping`, and notifications are public. Override `publicMethods` if every method must require Bearer.
334
+
335
+ ### OAuth (`createOAuthRouter`)
336
+
337
+ | Port | Role |
338
+ |------|------|
339
+ | `codeSecret` | HMAC secret for signed auth codes (string or `(req) => string`) |
340
+ | `resolveUser` | Consenting user, or `null` → redirect to `loginUrl` |
341
+ | `loginUrl` | Where unauthenticated authorize requests go |
342
+ | `mintAccessToken` | Issue a **user-bound**, **audience-bound** access token (`resource` is the RFC 8707 URI) — never a shared god token |
343
+ | `refreshAccessToken?` | If set, metadata advertises `refresh_token`; also receives `resource` |
344
+ | `revokeToken?` | If set, mounts `/revoke` and advertises `revocation_endpoint`. Well-formed authenticated revoke → 200 even if the token is unknown; `invalid_request` 400 and `invalid_client` 401 still apply |
345
+ | `codeStore?` | Shared single-use jti store for multi-instance (`consume(jti, expMs)`); pruning in-memory default otherwise |
346
+ | `clientStore?` | Pre-registered clients: `get(clientId)` returns registered redirect URIs and auth method; `verifySecret(clientId, presented)` authenticates confidential clients. Credentials never enter the library |
347
+
348
+ Auth codes carry `userId`, `resource`, and the granted `scope`. Clients **must** send `resource` on authorize and token (MCP MUST) — omitting it is a **breaking** requirement vs earlier 0.1.x drafts that ignored the parameter. Advertised grants come only from the handlers you configure. AS metadata sets `resource_parameter_supported: true`.
349
+
350
+ **Scope is negotiated:** `authorize` validates the requested `scope` against `scopes` (default `["mcp"]`) and rejects anything outside it with `invalid_scope`; an omitted `scope` grants the full advertised set. The auth code carries the grant, and `mintAccessToken` receives it — so `ToolDef.scope` and `principal.scopes` sit on a chain that actually reaches the OAuth layer.
351
+
352
+ **Client authentication:** unknown `client_id`s are public (PKCE only) unless `allowUnregisteredClients` is `false` — then DCR is unmounted, dropped from metadata, and unrecognized ids are rejected (`unauthorized_client` at authorize, `invalid_client` at token and revoke). `createMcpApp` derives the flag from `clients` via `hasDynamicClient`.
353
+
354
+ ## Tool registry
355
+
356
+ Schema and handler live in one place — no parallel “defs” and “handlers” lists to keep in sync:
357
+
358
+ ```ts
359
+ createToolRegistry(tools, { validateArgs: false }) // default: off, easy adoption
360
+ // onToolError?: (exc) => string — default redacts to "Tool execution failed"
361
+ ```
362
+
363
+ - Handler may return a `string` or `{ content, isError? }`
364
+ - Unknown tools and thrown errors become `isError: true` (not transport errors)
365
+ - Thrown exceptions are **redacted** by default (`"Tool execution failed"`); pass `onToolError` to map them. An `onToolError` that itself throws or returns a non-string falls back to the redacted default
366
+ - Duplicate tool names throw at registry construction
367
+ - Turn `validateArgs: true` once clients send schema-valid args
368
+
369
+ ### Wrapping an API as a tool
370
+
371
+ `ToolDef` stays the primitive. `defineTool` and `apiTool` are optional sugar for
372
+ the common case — turning "I have an API" into "I have an MCP tool" without
373
+ hand-rolling arg validation or fetch/error plumbing each time:
374
+
375
+ ```ts
376
+ import { apiTool } from "mcp-trellis";
377
+
378
+ const getWeather = apiTool({
379
+ name: "get_weather",
380
+ description: "Current weather for a city",
381
+ inputSchema: {
382
+ type: "object",
383
+ properties: { city: { type: "string" } },
384
+ required: ["city"],
385
+ },
386
+ // any Standard Schema v1 validator (https://standardschema.dev)
387
+ input: citySchema,
388
+ request: (_ctx, { city }) =>
389
+ `https://api.example.com/weather?city=${encodeURIComponent(city)}`,
390
+ respond: async (res) => {
391
+ const data = await res.json();
392
+ return `${data.tempC}°C, ${data.condition}`;
393
+ },
394
+ });
395
+ ```
396
+
397
+ - **`inputSchema` stays required** — it's what `tools/list` actually advertises to
398
+ clients, and there's no library-agnostic way to derive JSON Schema from an
399
+ arbitrary Standard Schema validator. Keep the two in sync.
400
+ - **`input`** (optional) parses and types `args` before your handler runs — any
401
+ [Standard Schema](https://standardschema.dev)-compliant validator works,
402
+ nothing library-specific. A validation failure returns `isError: true` with
403
+ the issues and never calls your handler.
404
+ - **`apiTool`** builds on `defineTool`: give it `request` (build the outgoing
405
+ call from typed args) and optionally `respond` (shape a 2xx response;
406
+ default is the body as text). Non-2xx becomes `isError: true` automatically.
407
+ `fetch` is overridable — testing, request signing, a custom agent.
408
+ - `defineTool` alone (without `request`/`respond`) is just the typed-args
409
+ layer over a regular `ToolDef` — use it for anything, not only REST calls.
410
+
411
+ ## Reference
412
+
413
+ ### Supported MCP methods
414
+
415
+ | Method | Auth | Notes |
416
+ |--------|------|-------|
417
+ | `initialize` | public | Negotiates protocol version; returns `capabilities.tools` |
418
+ | `ping` | public | Empty result |
419
+ | `tools/list` | Bearer | Lists registry entries |
420
+ | `tools/call` | Bearer + scope | Runs the tool; missing scope → 401 |
421
+ | `notifications/*` | public | HTTP 202 empty body |
422
+
423
+ Anything else → JSON-RPC `-32601`. Capabilities advertise **tools only**.
424
+
425
+ ### HTTP and JSON-RPC status codes
426
+
427
+ | HTTP | When |
428
+ |------|------|
429
+ | **202** | Notification (empty body) |
430
+ | **400** | Parse error, batch array, invalid request |
431
+ | **401** | Missing/invalid Bearer; includes `WWW-Authenticate` |
432
+ | **405** | Wrong HTTP verb on MCP |
433
+
434
+ | JSON-RPC code | Constant |
435
+ |---------------|----------|
436
+ | `-32700` | `JSONRPC_PARSE_ERROR` |
437
+ | `-32600` | `JSONRPC_INVALID_REQUEST` (batches) |
438
+ | `-32601` | `JSONRPC_METHOD_NOT_FOUND` |
439
+ | `-32602` | `JSONRPC_INVALID_PARAMS` |
440
+ | `-32603` | `JSONRPC_INTERNAL_ERROR` |
441
+ | `-32001` | `JSONRPC_UNAUTHORIZED` |
442
+
443
+ ### `createMcpHandler` options
444
+
445
+ | Option | Required | Description |
446
+ |--------|----------|-------------|
447
+ | `registry` | yes | From `createToolRegistry` |
448
+ | `ports` | yes | `authenticate`, `context`, optional `audit` |
449
+ | `serverInfo` | yes | `{ name, version }` |
450
+ | `wwwAuthenticate` | yes | Static or `(req) => …` for RFC 9728 PRM URL |
451
+ | `instructions` | no | Returned on `initialize` |
452
+ | `publicMethods` | no | Default: `initialize`, `ping`, notifications |
453
+
454
+ ### `createOAuthRouter` options
455
+
456
+ | Option | Default | Description |
457
+ |--------|---------|-------------|
458
+ | `ports` | — | Required OAuth ports (see above) |
459
+ | `resourcePath` | `"/mcp"` | MCP resource path in PRM |
460
+ | `oauthPath` | `"/mcp/oauth"` | Prefix for authorize / token / register / revoke |
461
+ | `realm` | — | Optional realm string |
462
+ | `scopes` | `["mcp"]` | Advertised in metadata, and the ceiling `authorize` validates against |
463
+ | `tokenEndpointAuthMethods` | `["none"]` | Advertised client auth methods |
464
+ | `allowUnregisteredClients` | `true` | `false` requires `clientStore`, unmounts DCR, and rejects unknown `client_id`s (`unauthorized_client` / `invalid_client`) |
465
+ | `redirect` | see below | Redirect URI allowlist |
466
+
467
+ **`redirect` (`RedirectAllowlistOptions`):**
468
+
469
+ | Field | Default | Description |
470
+ |-------|---------|-------------|
471
+ | `extra` | `[]` | Exact-match redirect URIs |
472
+ | `allowLoopback` | `true` | Allow `http(s)` loopback — `127.0.0.1`, `[::1]`, `localhost` |
473
+ | `allowClaude` | `true` | Allow the Claude.ai Custom Connector callback |
474
+
475
+ Pre-registered clients bypass this allowlist entirely — they are validated
476
+ against their own `redirectUris` from `clientStore`.
477
+
478
+ ### `createMcpApp` options
479
+
480
+ | Option | Default | Description |
481
+ |--------|---------|-------------|
482
+ | `serverInfo`, `tools`, `auth` | — | Required |
483
+ | `clients` | `["claude"]` | Connector profiles to serve |
484
+ | `resourcePath` | `"/mcp"` | MCP endpoint path |
485
+ | `oauthPath` | `` `${resourcePath}/oauth` `` | OAuth prefix |
486
+ | `scopes` | `["mcp"]` | Scopes this server grants |
487
+ | `realm` | `serverInfo.name` | `WWW-Authenticate` realm |
488
+ | `extraRedirectUris` | `[]` | Callbacks beyond the client profiles |
489
+ | `allowLoopback` | `true` | Allow loopback redirects |
490
+ | `instructions`, `validateArgs`, `onToolError`, `context`, `audit` | — | Passed through |
491
+
492
+ ### Exports
493
+
494
+ <details>
495
+ <summary><code>mcp-trellis</code></summary>
496
+
497
+ - `createMcpApp`, `createMcpHandler`, `createToolRegistry`
498
+ - `defineTool`, `apiTool` — typed, validated tool authoring on top of `ToolDef`
499
+ - `CLIENT_PROFILES`, `DEFAULT_CLIENTS`, `authMethodsFor`, `redirectUrisFor`, `preRegisteredClients`, `hasDynamicClient`
500
+ - `parseBearer`, `timingSafeEqual`, `matchesAny`, `wwwAuthenticateHeader`, `rejectQueryToken`
501
+ - `validateAgainstSchema`, `JSON_SCHEMA_TYPES`
502
+ - `rpcResult`, `rpcError`, JSON-RPC error constants
503
+ - `pickProtocolVersion`, `PROTOCOL_VERSIONS`, `DEFAULT_PROTOCOL_VERSION`
504
+ - `jsonResponse`, `emptyResponse`, `optionsResponse`, `corsHeaders`, `methodNotAllowed`
505
+ - Types: `McpApp`, `McpAppOptions`, `McpAppAuth`, `VerifiedToken`, `ClientName`, `ClientProfile`, `McpHandler`, `McpHandlerOptions`, `McpPorts`, `Principal`, `AuditEntry`, `ServerInfo`, `ToolDef`, `ToolHandler`, `ToolResult`, `ToolRegistry`, `JsonSchema`, `StandardSchemaV1`, `DefineToolOptions`, `ApiToolOptions`, `ApiRequest`, …
506
+
507
+ </details>
508
+
509
+ <details>
510
+ <summary><code>mcp-trellis/oauth</code></summary>
511
+
512
+ - `createOAuthRouter`
513
+ - `authorizationServerMetadata`, `protectedResourceMetadata`, `mcpWwwAuthenticate`
514
+ - `canonicalResource`, `resourcesEqual`, `firstResourceError`, `DEFAULT_RESOURCE_PATH`
515
+ - `isAllowedRedirectUri`, `CLAUDE_CALLBACK`
516
+ - `issueAuthCode`, `consumeAuthCode`, `newClientId`
517
+ - `verifyPkceS256`, `sha256Base64Url`, `randomBase64Url`
518
+ - `readClientAuth`, `firstClientAuthError`, `unregisteredClientsAllowed`
519
+ - `parseScope`, `formatScope`, `requestedScopes`, `firstScopeError`
520
+ - `GRANT_TYPES`, `OAUTH_ERRORS`, `DEFAULT_SCOPE`, `TOKEN_ENDPOINT_AUTH_METHODS`
521
+ - Types: `OAuthUser`, `MintedToken`, `OAuthPorts`, `OAuthRouterOptions`, `AuthCodeRecord`, `CodeStore`, `ClientStore`, `RegisteredClient`, `ClientAuth`, `TokenEndpointAuthMethod`, `MintAccessTokenInput`, `RefreshAccessTokenInput`, `RevokeTokenInput`
522
+
523
+ </details>
524
+
525
+ <details>
526
+ <summary><code>mcp-trellis/node</code></summary>
527
+
528
+ - `asNodeHandler`, `resolveOrigin`, `toWebRequest`, `sendWebResponse`, `readNodeBody`
529
+ - Types: `NodeRequestLike`, `NodeResponseLike`, `AsNodeHandlerOptions`
530
+
531
+ </details>
532
+
533
+ ## Protocol promises
534
+
535
+ - Notifications → HTTP **202** with an empty body
536
+ - Batch arrays → `-32600` (MCP 2025-06-18)
537
+ - Protocol version negotiated from client `initialize` params
538
+ - Query-string tokens rejected (`token` and RFC 6750 `access_token`)
539
+ - `tools/call` checks `principal.scopes` (`*` = all), and the OAuth grant that produced them is validated at `authorize`
540
+ - With `createMcpApp`, tokens whose audience is not this server's canonical resource are rejected by the library
541
+ - **`fetch` never rejects.** If a host port you supply (`authenticate`, `context`, `resolveUser`, `mintAccessToken`, `clientStore`, …) throws, `createMcpHandler`, `createOAuthRouter`, and `createMcpApp` all catch it and return a real `500` (`-32603` for MCP, `server_error` for OAuth) instead of an unhandled rejection — whose shape and whether it even reaches the client varies by runtime. `asNodeHandler` catches independently too, since on raw `http.createServer` a rejection there leaves the socket open with no response ever sent.
542
+
543
+ ## Threat model (library)
544
+
545
+ This is a **library** threat model, not a third-party audit badge.
546
+
547
+ | Risk | Mitigation |
548
+ |------|------------|
549
+ | Confused deputy (token usable at the wrong MCP) | RFC 8707: `resource` required on authorize + token; bound into the auth code; must equal this AS’s canonical resource (`canonicalResource(origin, resourcePath)`). Passed into `mintAccessToken` / `refreshAccessToken` so you can embed `aud`. |
550
+ | Refresh token replayed at another resource on the same AS | Library cannot inspect opaque refresh tokens — **`refreshAccessToken` MUST reject tokens not originally issued for the given `resource`** |
551
+ | Audience not enforced at the RS | **`createMcpApp` enforces this** — `verifyToken` returns the token's `audience` and the library rejects any mismatch against `canonicalResource(origin, resourcePath)`. With bare `createMcpHandler`, the check is yours. |
552
+ | Open redirect after login | Your login page must validate `next` is same-origin before redirecting |
553
+ | Auth-code replay across instances | Pass a shared `codeStore`; in-memory jti map is process-local only |
554
+ | Origin spoofing on Node | Pass explicit `origin`, or `trustProxy: true` only behind a proxy that strips client `X-Forwarded-*` |
555
+ | Scope escalation at authorize | Requested `scope` is validated against the advertised `scopes` and rejected with `invalid_scope`; the grant is bound into the auth code and handed to `mintAccessToken` |
556
+ | Stolen access or refresh token | Host `revokeToken` (denylist or equivalent) that `verifyToken` and `refreshAccessToken` consult. Unknown / wrong-client tokens MUST no-op, not throw. Well-formed authenticated revoke is 200 even if the token is unknown |
557
+ | Stolen confidential-client secret | `clientStore.verifySecret` owns comparison — store hashes, not plaintext. The library never sees or persists credentials |
558
+ | Registration-free DCR | `/register` returns a random `client_id` that is **never stored**; any unknown `client_id` works with an allowlisted `redirect_uri`. Defensible for public clients with PKCE — the model dynamic connectors (Claude, Codex) actually need. Pre-registered clients bypass this entirely, bound to their own `redirectUris` and auth method. CIMD replaces this model |
559
+ | Naming only confidential clients doesn't actually block public ones | `clients: ["gemini"]` (or `allowUnregisteredClients: false`) is **enforced**: DCR unmounted, dropped from AS metadata, unresolved `client_id` rejected with `unauthorized_client` at `authorize` and `invalid_client` at `token` and `revoke` |
560
+
561
+ **Also designed in:** PKCE S256 (timing-safe, length-capped); HMAC auth codes bind `userId`, `clientId`, `redirectUri`, challenge, and `resource`; redirect allowlist + DCR filter; no query-string tokens (`token` and `access_token`); honest `grant_types_supported`; `/token` and `/revoke` omit CORS `*`; audit fires on auth/scope denial as well as tool results.
562
+
563
+ **Known limits:** in-memory jti map is process-local (multi-instance needs `codeStore`); loopback redirect allowlist permits any path/port on `localhost` / `127.0.0.1` (expected for native clients); DCR does not bind credentials to a stored client record until CIMD.
564
+
565
+ ## Not in scope
566
+
567
+ Explicitly **out** of this package (do not expect parity with full MCP hosts or enterprise AS products):
568
+
569
+ - **Tools only** — no `resources/*`, no `prompts/*`, and capabilities advertise tools alone
570
+ - **No server-initiated messages** — Streamable HTTP is served as a single JSON response per POST (which the spec permits, and which Gemini Enterprise requires). No SSE response streams, so no `notifications/progress` and no long-running tool keepalive
571
+ - **No sessions** — removed from the protocol in `2026-07-28` anyway
572
+ - **No enterprise-managed auth** — no ID-JAG, no IdP product integration; you wire login + minting
573
+ - **No embedded product surface** — no token store, sessions, or login UI
574
+ - **No stdio** transport; no batch JSON-RPC arrays
575
+ - **No DPoP, PAR, or `client_credentials`** — this AS is authorization_code (+ optional refresh and revoke)
576
+ - **No paid external security audit** claimed here — see Threat model above
577
+
578
+ See [docs/ROADMAP.md](docs/ROADMAP.md) for what is next — CIMD and the
579
+ `2026-07-28` stateless core are the two open items.
580
+
581
+ ## Scripts
582
+
583
+ ```bash
584
+ npm test
585
+ npm run build
586
+ npm run typecheck
587
+ ```
588
+
589
+ ## Contributing
590
+
591
+ PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).
592
+
593
+ ## License
594
+
595
+ MIT
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Node HTTP `(req, res)` adapter — Express, Cloud Functions, `http.createServer`, etc.
3
+ * Bridges duck-typed Node request/response objects to Web `Request`/`Response`.
4
+ */
5
+ export type NodeRequestLike = {
6
+ method?: string;
7
+ url?: string;
8
+ headers: Record<string, string | string[] | undefined>;
9
+ body?: unknown;
10
+ };
11
+ export type NodeResponseLike = {
12
+ statusCode: number;
13
+ setHeader: (name: string, value: string | number | readonly string[]) => void;
14
+ end: (chunk?: string | Uint8Array) => void;
15
+ };
16
+ export type ToWebRequestOptions = {
17
+ /** Absolute origin, e.g. https://app.example.com. */
18
+ origin: string;
19
+ /** Pre-read body. Overrides `req.body` when supplied. */
20
+ body?: unknown;
21
+ };
22
+ export type ResolveOriginOptions = {
23
+ /**
24
+ * Trust `X-Forwarded-Host` / `X-Forwarded-Proto`.
25
+ * Uses the **last** forwarded value (rightmost = closest proxy).
26
+ */
27
+ trustProxy?: boolean;
28
+ };
29
+ export type AsNodeHandlerOptions = {
30
+ /**
31
+ * Absolute origin. Required unless `trustProxy: true`
32
+ * (then derived from X-Forwarded-* / Host).
33
+ */
34
+ origin?: string;
35
+ trustProxy?: boolean;
36
+ };
37
+ /** Derive origin from Host, or from forwarded headers when trustProxy. */
38
+ export declare const resolveOrigin: (req: NodeRequestLike, options?: ResolveOriginOptions) => string;
39
+ export declare const toWebRequest: (req: NodeRequestLike, options: ToWebRequestOptions) => Request;
40
+ /** Prefer `req.body`; else drain the stream (raw `http.createServer`). */
41
+ export declare const readNodeBody: (req: NodeRequestLike) => Promise<unknown>;
42
+ export declare const sendWebResponse: (res: NodeResponseLike, response: Response) => Promise<void>;
43
+ /** One-liner: Node `(req, res)` → MCP / OAuth Web handler. */
44
+ export declare const asNodeHandler: (mcp: {
45
+ fetch: (request: Request) => Promise<Response>;
46
+ }, options?: AsNodeHandlerOptions) => (req: NodeRequestLike, res: NodeResponseLike) => Promise<void>;
47
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,MAAM,EAAE,KAAK,IAAI,CAAC;IAC9E,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,UAAU,KAAK,IAAI,CAAC;CAC5C,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,qDAAqD;IACrD,MAAM,EAAE,MAAM,CAAC;IACf,yDAAyD;IACzD,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,CAAC;AAUF,0EAA0E;AAC1E,eAAO,MAAM,aAAa,GACxB,KAAK,eAAe,EACpB,UAAS,oBAAyB,KACjC,MAgBF,CAAC;AA+BF,eAAO,MAAM,YAAY,GACvB,KAAK,eAAe,EACpB,SAAS,mBAAmB,KAC3B,OAuBF,CAAC;AAiBF,0EAA0E;AAC1E,eAAO,MAAM,YAAY,GACvB,KAAK,eAAe,KACnB,OAAO,CAAC,OAAO,CAWjB,CAAC;AAEF,eAAO,MAAM,eAAe,GAC1B,KAAK,gBAAgB,EACrB,UAAU,QAAQ,KACjB,OAAO,CAAC,IAAI,CAId,CAAC;AASF,8DAA8D;AAC9D,eAAO,MAAM,aAAa,GACxB,KAAK;IAAE,KAAK,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;CAAE,EACvD,UAAU,oBAAoB,MAMhB,KAAK,eAAe,EAAE,KAAK,gBAAgB,KAAG,OAAO,CAAC,IAAI,CAWzE,CAAC"}