@bensandee/mcp-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orange Bike Labs, LLC
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 CHANGED
@@ -1,3 +1,339 @@
1
- # Temporary Holding Version
1
+ # @bensandee/mcp-server
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
+ One guarded MCP endpoint for Hono apps. It serves the OAuth protected resource document, checks
4
+ the caller's bearer token, applies three limits in memory, and runs your tools.
5
+
6
+ ## Installation
7
+
8
+ ```sh
9
+ pnpm add @bensandee/mcp-server hono @hono/node-server @modelcontextprotocol/sdk @hono/mcp zod hono-rate-limiter
10
+ ```
11
+
12
+ The package declares five peer dependencies, and each app installs and upgrades its own copies:
13
+
14
+ | Peer | Minimum |
15
+ | --------------------------- | --------- |
16
+ | `hono` | `4.13.19` |
17
+ | `@hono/node-server` | `2.1.9` |
18
+ | `@modelcontextprotocol/sdk` | `1.29.0` |
19
+ | `@hono/mcp` | `0.3.5` |
20
+ | `zod` | `3.25.0` |
21
+
22
+ `@hono/mcp` declares `hono-rate-limiter` as a required peer, so install it too. The two minimums
23
+ shown for `hono` and `@hono/node-server` are the releases that carry the security fixes known when
24
+ this package was written.
25
+
26
+ ## Wiring
27
+
28
+ Mount the sub-app at your app's root. One call then serves both the document and the endpoint, and
29
+ no route below the endpoint's path escapes the guard.
30
+
31
+ ```ts
32
+ import { serve } from "@hono/node-server";
33
+ import { Hono } from "hono";
34
+ import { createMcpEndpoint } from "@bensandee/mcp-server";
35
+
36
+ interface User {
37
+ id: string;
38
+ }
39
+
40
+ const app = new Hono();
41
+
42
+ app.route(
43
+ "/",
44
+ createMcpEndpoint<User>({
45
+ publicUrl: "https://app.example.com",
46
+ path: "/mcp",
47
+ issuers: [
48
+ {
49
+ issuer: "https://id.example.com/application/o/household/",
50
+ audiences: ["<the connector application's client id>"],
51
+ jwksUrl: "https://id.example.com/application/o/household/jwks/",
52
+ },
53
+ ],
54
+ identify: (claims) => ({ ok: true, user: { id: claims.subject } }),
55
+ callerKey: (user) => user.id,
56
+ server: {
57
+ name: "household",
58
+ version: "1.0.0",
59
+ instructions: "Use these tools when the user asks about household chores or shopping.",
60
+ },
61
+ tools: [
62
+ {
63
+ name: "list_chores",
64
+ description: "List the chores that are due.",
65
+ inputSchema: { type: "object", properties: {} },
66
+ },
67
+ ],
68
+ callTool: async (call, user) => ({
69
+ content: [{ type: "text", text: `Chores for ${user.id}: none due.` }],
70
+ }),
71
+ }),
72
+ );
73
+
74
+ serve({ fetch: app.fetch, port: 3000 });
75
+ ```
76
+
77
+ `identify` turns checked claims into one of your users, or refuses the caller:
78
+
79
+ ```ts
80
+ identify: (claims) =>
81
+ claims.payload.email === "known@example.com"
82
+ ? { ok: true, user: { id: claims.subject } }
83
+ : { ok: false, status: 403, message: "No such user." },
84
+ ```
85
+
86
+ The refusal's `message` goes to your log hook only. The caller reads a fixed body, the same for
87
+ every reason.
88
+
89
+ ## What happens to a request, in order
90
+
91
+ 1. **The protected resource document** (RFC 9728) is served at
92
+ `/.well-known/oauth-protected-resource<path>`, public, with no guard. It names the endpoint's
93
+ URL as the resource, your issuers as authorization servers, `header` as the only bearer
94
+ method, and your scopes. With no scopes configured, `scopes_supported` is left out rather than
95
+ sent empty, because an empty list changes what a client asks for. The package serves only this
96
+ document. A site-wide `/.well-known/oauth-protected-resource` at your root stays your app's
97
+ business.
98
+ 2. **The challenge.** Every 401 from the sub-app, your own routes included, carries
99
+ `WWW-Authenticate: Bearer resource_metadata="<document URL>"`. When the request carried a token
100
+ that was refused, the header also carries `error="invalid_token"`.
101
+ 3. **The token key.** A request with an `Authorization` header gets a keyed hash of it for the
102
+ limits below. The raw token is never stored or logged, and the hash key lives only in process
103
+ memory.
104
+ 4. **The flood ceiling.** It counts refused requests (401 and 403) for the whole endpoint, with no
105
+ key and no client address. While it is tripped, a token the endpoint accepted recently still
106
+ gets through, so people already connected keep working and only new sign-ins wait. Every other
107
+ request gets 429 until the window passes.
108
+ 5. **The refusal limit.** It counts refused requests per token, keyed by the token key, and
109
+ answers 429 once a token's count is spent. A request with no `Authorization` header is never
110
+ counted, so a client's first request always gets the 401 that starts sign-in.
111
+ 6. **Bearer sign-in.** The package reads `Authorization: Bearer <token>` and nothing else, so a
112
+ request with only a cookie is refused. A token is checked in this order:
113
+ - its `iss` is one of your issuers, read before any key is fetched;
114
+ - its `alg` is `RS256` and it names a `kid`;
115
+ - its `aud` is one of the audiences you configured for that issuer;
116
+ - its signature checks out against that issuer's JWKS URL, cached, or against the key set you
117
+ supplied in place;
118
+ - its `typ` is `at+jwt` if you set `requireAccessTokenType`;
119
+ - its `exp` is in the future, with 30 seconds of clock skew allowed;
120
+ - its `sub` is a non-empty string.
121
+
122
+ A bad token is a refusal. A key set the endpoint could not fetch or read is a 503, so a caller
123
+ cannot make a 5xx on demand.
124
+
125
+ 7. **Your `identify`.** It receives the checked claims (issuer, subject, the whole payload) and the
126
+ request, and returns a user or a refusal with status 401 or 403.
127
+ 8. **The caller limit.** It counts requests per signed-in caller, keyed by `callerKey`, and answers
128
+ 429 past the limit. Every 429 from the package carries the standard `RateLimit` headers.
129
+ 9. **The body size limit.** A body larger than `maxBodyBytes` is refused with 413 before it is
130
+ parsed.
131
+ 10. **The endpoint.** POST to the path is served. Any other method gets 405 with `Allow: POST`, and
132
+ any path below the path gets 404. Each request gets a fresh MCP server and transport, answered
133
+ as one JSON body with no session id and no stream. A POST that holds only notifications gets
134
+ 202 with no body. A JSON-RPC batch is refused with a JSON-RPC error, because MCP dropped
135
+ batching and a batch would let one request count once here while running many calls. Your
136
+ server name, version and instructions go out when a client connects, and your tools are
137
+ listed and called with the signed-in user. A tool result, errors included, passes through
138
+ unchanged.
139
+
140
+ Anything that throws inside the sub-app (`identify`, `callTool`, `callerKey`, the key fetch) is
141
+ reported through your log hook as a fault. A throw in `callTool` becomes a tool error with a fixed
142
+ text. A throw anywhere earlier becomes a fixed 503. No error's own text, cause or stack reaches
143
+ the caller, and no throw reaches your app's error handler.
144
+
145
+ The fixed bodies are one per status. A request the MCP transport rejects, such as one with a wrong
146
+ `Accept` or `Content-Type`, or a body that is not a JSON-RPC message, gets 400 with its body.
147
+
148
+ ```json
149
+ {
150
+ "400": { "error": "bad_request" },
151
+ "401": { "error": "unauthorized" },
152
+ "403": { "error": "forbidden" },
153
+ "404": { "error": "not_found" },
154
+ "405": { "error": "method_not_allowed" },
155
+ "413": { "error": "payload_too_large" },
156
+ "429": { "error": "too_many_requests" },
157
+ "503": { "error": "unavailable" }
158
+ }
159
+ ```
160
+
161
+ ## Options
162
+
163
+ | Option | Default | Meaning |
164
+ | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
165
+ | `publicUrl` | required | The absolute public URL, origin only, with no path, query or hash. Both the document and the challenge are built from it, never from the request's `Host`. |
166
+ | `path` | `"/mcp"` | The route the endpoint serves. It must start with `/`, must not end with `/`, and must hold no `*` or `:`. |
167
+ | `issuers` | required | At least one issuer, each with the exact `iss` value, at least one audience, and either a `jwksUrl` or a `jwks` key set. |
168
+ | `scopes` | none | Scopes advertised in the document. They are never enforced. |
169
+ | `requireAccessTokenType` | `false` | Require the `typ` header to be `at+jwt` (RFC 9068). |
170
+ | `identify` | required | Turns checked claims and the request into a user, or a refusal with 401 or 403 and a message. |
171
+ | `callerKey` | required | A stable string per user, used by the caller limit. |
172
+ | `server` | required | The MCP server `name`, `version` and optional `instructions`. |
173
+ | `tools` | required | The tools to advertise and serve. |
174
+ | `callTool` | required | Runs one tool call for one user and returns a tool result. |
175
+ | `limits` | see below | `refusals`, `callers` and `flood`, each `{ limit, windowMs }`. |
176
+ | `maxBodyBytes` | `1048576` | Largest accepted request body, in bytes (1 MB). |
177
+ | `onEvent` | none | Receives every refusal, limit hit, tool error and fault. |
178
+
179
+ The three limits default to the numbers below, and each one can be changed on its own:
180
+
181
+ | Limit | Default | What it counts |
182
+ | ---------- | ------------------------ | ----------------------------------------- |
183
+ | `refusals` | 30 in 900000 ms (15 min) | 401 and 403 responses, per token |
184
+ | `callers` | 120 in 60000 ms (1 min) | Every request, per caller key |
185
+ | `flood` | 600 in 60000 ms (1 min) | Refused responses, for the whole endpoint |
186
+
187
+ Limits live in one process's memory, so they reset on restart and no two processes share them.
188
+ Each limit's store has a size cap, so a stream of distinct junk tokens cannot grow memory without
189
+ bound.
190
+
191
+ A bad option throws `McpEndpointConfigError` when you build the endpoint, not on the first request.
192
+
193
+ ## Events
194
+
195
+ `onEvent` receives one object per event. A hook that throws changes nothing about the answer.
196
+
197
+ | `type` | Fields |
198
+ | ------------ | ---------------------------------------------------------------------------- |
199
+ | `refusal` | `status` (401 or 403), `reason`, and `message` for `identify` refusals only |
200
+ | `limit` | `limit`: `"refusals"`, `"callers"` or `"flood"` |
201
+ | `tool_error` | `tool`, `error` |
202
+ | `fault` | `stage`: `"keys"`, `"identify"`, `"caller_key"` or `"endpoint"`, and `error` |
203
+
204
+ `reason` is one of `"no_token"`, `"not_jwt"`, `"algorithm"`, `"key_id"`, `"issuer"`, `"audience"`,
205
+ `"token_type"`, `"signature"`, `"expired"`, `"claims"`, `"invalid"` or `"identify"`. Log it: it
206
+ names the check that failed without telling the caller.
207
+
208
+ ## Testing your app
209
+
210
+ The `./testing` entry point gives you a local issuer and a probe. Neither touches the network.
211
+
212
+ ```ts
213
+ import { createTestIssuer, probeGuard } from "@bensandee/mcp-server/testing";
214
+ import { expect, test } from "vitest";
215
+ import app from "./app";
216
+
217
+ test("the guard covers every path variant", async () => {
218
+ const findings = await probeGuard(app.fetch);
219
+
220
+ expect(findings).toEqual([]);
221
+ });
222
+
223
+ test("a good token reaches the tool", async () => {
224
+ const issuer = await createTestIssuer();
225
+ const token = await issuer.mint({ subject: "user-1" });
226
+ // Pass issuer.config as one of the endpoint's issuers, then send `token` as a
227
+ // bearer token through app.fetch.
228
+ });
229
+ ```
230
+
231
+ - `createTestIssuer()` makes an RSA key pair and a local issuer. `issuer.config` is an issuer with
232
+ its key set in place, so the endpoint fetches no keys. `issuer.mint(options)` signs one token.
233
+ The options are `subject`, `audience`, `issuer`, `expiresIn`, `kid`, `typ` and `claims`; pass
234
+ `null` for `subject`, `expiresIn` or `kid` to leave that part out of the token.
235
+ - `LocalIssuer` is the issuer shape with a `jwks` key set. Use it directly when you supply your
236
+ own keys.
237
+ - `probeGuard(send, options)` sends requests with no credentials to the endpoint path and to the
238
+ variants a router or proxy might also route there: trailing slash, upper case, a doubled leading
239
+ slash, dot segments, encoded characters, a backslash and a trailing `;` or `?`. It reports every
240
+ answer its rule treats as unsafe. Run it against your whole built app's `fetch`, not the sub-app,
241
+ so a routing fault that skips the guard shows up. `defaultProbeIsSafe` accepts a refusal, a
242
+ missing route, a wrong method or a limit hit. An app with a page for unknown paths passes its own
243
+ `isSafe` rule that also accepts that page, since otherwise the probe reports a 200 it cannot
244
+ judge. `defaultProbeVariants(path)` gives the default list.
245
+
246
+ ## Provider setup, written for Authentik
247
+
248
+ The package trusts any provider that mints RS256 JWTs with a JWKS URL. The settings below are
249
+ Authentik's, with the general OAuth parts marked.
250
+
251
+ - **Sign the tokens with RS256.** The package accepts no other algorithm, and it refuses an HS256
252
+ token before it fetches a key. (General: the package accepts RS256 only.)
253
+ - **Keep the access token lifetime short.** A token cannot be revoked before it expires, so its
254
+ lifetime is the longest a removed user or a stolen token keeps working. Minutes, not hours.
255
+ - **Choose a subject mode users cannot edit.** Use the hashed user ID. Never use the username or
256
+ the email address: a user who can change either can take over another user's account in your app.
257
+ (General: `sub` must be stable and not user-controlled.)
258
+ - **Bind the application to a group.** Set the application's policy to the group of people who may
259
+ use the connector, so the provider issues a token only to them. Without a binding, every account
260
+ in the provider can get one.
261
+ - **Turn off self sign-up** on the provider, unless you mean to let strangers create accounts that
262
+ then pass the group check only by your leave.
263
+ - **Put the email in the access token only when you need it.** If your app links users by email,
264
+ add the email scope and the claim. That is safe only when users cannot change their own email in
265
+ the provider, or when your `identify` also requires `email_verified`. Otherwise a user can claim
266
+ another's address.
267
+ - **An Authentik ID token for the same client also passes, unless you set `requireAccessTokenType`.**
268
+ Authentik does not set `typ` to `at+jwt`, so the package cannot tell an ID token from an access
269
+ token for that client. That is acceptable because the MCP client is the only holder of either,
270
+ and both name the same user. Set `requireAccessTokenType: true` on a provider that does mark its
271
+ access tokens, and the ID token is refused.
272
+ - **A 403 tells the caller its token was valid but not allowed.** The package sends the same fixed
273
+ body for every reason, so a 403 reveals only that much. If your app must not reveal it, refuse
274
+ with 401 from `identify` instead, and the caller reads the same body as a bad token.
275
+
276
+ ## At the proxy
277
+
278
+ Two things belong at the proxy, because the package cannot do them from inside the app.
279
+
280
+ - **Limit `/mcp` and its document to the MCP client's ranges.** Allow
281
+ `/.well-known/oauth-protected-resource/mcp` and `/mcp` only from the addresses the MCP client
282
+ calls from, and answer everything else with 403 at the proxy. For Claude, take the current list
283
+ from Anthropic's published IP range page; do not copy a list from here, since Anthropic changes
284
+ it. This keeps the sign-in surface off the open internet.
285
+ - **Cap the body size.** The package refuses a body over `maxBodyBytes`, but only after the bytes
286
+ have arrived. A proxy cap stops them earlier.
287
+
288
+ A rate limit on `/mcp` is the extra layer for a flood too big for the app to absorb, since the
289
+ ceiling in the app runs after the network and TLS work is done.
290
+
291
+ Callers of one MCP client share addresses: every Claude call comes from Anthropic's ranges. A proxy
292
+ limit keyed by address is therefore a high shared ceiling that keeps the server up. It is not a
293
+ per-user limit, and it cannot be one. Count users in the app, through `callerKey`; count addresses
294
+ at the proxy.
295
+
296
+ This Caddy example uses the `caddy-ratelimit` module (not in the standard build, so add it with
297
+ `xcaddy`) and Caddy's own `request_body` handler:
298
+
299
+ ```text
300
+ app.example.com {
301
+ @mcp {
302
+ path /mcp /.well-known/oauth-protected-resource/mcp
303
+ }
304
+
305
+ request_body {
306
+ max_size 2MB
307
+ }
308
+
309
+ rate_limit {
310
+ zone mcp_flood {
311
+ match {
312
+ path /mcp
313
+ }
314
+ key {remote_host}
315
+ events 6000
316
+ window 1m
317
+ }
318
+ }
319
+
320
+ reverse_proxy localhost:3000
321
+ }
322
+ ```
323
+
324
+ The numbers are a starting point, not a rule: 6000 requests a minute from one address is far above
325
+ what real use needs, and it only slows a flood. Set it from your own traffic.
326
+
327
+ ## Public clients
328
+
329
+ The package never holds, asks for, or checks a client secret, and nothing in it depends on how the
330
+ client signed in. A later move from a confidential client to a public one (no secret, PKCE only)
331
+ needs no change here, but the provider setup gains four requirements:
332
+
333
+ - the application bound to a group becomes required, not advised, since PKCE alone does not say
334
+ who may use the client;
335
+ - the provider must enforce PKCE, not merely accept it;
336
+ - refresh tokens must rotate, or carry a bounded lifetime, because a public client cannot keep a
337
+ secret;
338
+ - the production application must have no localhost redirect, which anyone running a local server
339
+ could otherwise claim.
@@ -0,0 +1,18 @@
1
+ import { _ as ServerInfo, a as IdentifyResult, c as LimitOptions, d as McpEndpointEvent, f as McpEndpointOptions, g as RemoteIssuer, h as RefusalReason, i as IdentifyFailure, l as Limits, m as RefusalEvent, n as FaultEvent, o as IssuerConfig, p as McpEnv, r as IdentifiedUser, s as LimitEvent, t as CheckedClaims, u as LocalIssuer, v as ToolCall, y as ToolErrorEvent } from "./types-B7gttgCL.mjs";
2
+ import { Hono } from "hono";
3
+ /**
4
+ * Builds the sub-app that serves one MCP endpoint and its protected resource
5
+ * document.
6
+ *
7
+ * Mount it at the app's root (`app.route("/", createMcpEndpoint(...))`), so one
8
+ * call serves both routes and no route below the endpoint's path escapes the
9
+ * guard. Every request to the endpoint is answered in one fixed order: the
10
+ * challenge, the token key, the flood ceiling, the refusal limit, sign-in, the
11
+ * caller limit, the body limit, then the endpoint itself.
12
+ * An error thrown anywhere inside this app is reported through the log hook and
13
+ * answered with a fixed body; it never reaches the host app's error handler.
14
+ */
15
+ export declare function createMcpEndpoint<User>(options: McpEndpointOptions<User>): Hono<McpEnv<User>>;
16
+ /** Thrown when the endpoint options are invalid at construction time. */
17
+ export declare class McpEndpointConfigError extends Error {}
18
+ export type { CheckedClaims, FaultEvent, IdentifiedUser, IdentifyFailure, IdentifyResult, IssuerConfig, LimitEvent, LimitOptions, Limits, LocalIssuer, McpEndpointEvent, McpEndpointOptions, RefusalEvent, RefusalReason, RemoteIssuer, ServerInfo, ToolCall, ToolErrorEvent };