@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.
@@ -0,0 +1,101 @@
1
+ import { u as LocalIssuer } from "./types-B7gttgCL.mjs";
2
+ /**
3
+ * A value that may be left out by passing `null` instead of one.
4
+ *
5
+ * `null` means "no default", which is how a test asks for a token with no `exp`
6
+ * or no `kid` at all.
7
+ */
8
+ type Omittable<T> = T | null;
9
+ /** The options `createTestIssuer` takes; each has a default. */
10
+ export interface TestIssuerOptions {
11
+ /** The `iss` every minted token carries; default `https://issuer.test/`. */
12
+ issuer?: string;
13
+ /** The `aud` every minted token carries; default `test-client`. */
14
+ audience?: string;
15
+ /** The `kid` of the signing key; default `test-key`. */
16
+ kid?: string;
17
+ }
18
+ /** How to shape one minted token; each field falls back to the issuer's default. */
19
+ export interface MintOptions {
20
+ /** The `sub` claim; default `user-1`. `null` leaves `sub` out. */
21
+ subject?: Omittable<string>;
22
+ /** Overrides the issuer's audience. */
23
+ audience?: string;
24
+ /** Overrides the issuer's `iss`. */
25
+ issuer?: string;
26
+ /** Token lifetime as jose reads it; default `5m`. `null` leaves `exp` out. */
27
+ expiresIn?: Omittable<string>;
28
+ /** The signing key's `kid`; `null` leaves `kid` out. */
29
+ kid?: Omittable<string>;
30
+ /** The `typ` header; left out when not given. */
31
+ typ?: string;
32
+ /** Extra claims; a field the options above set wins over the same claim. */
33
+ claims?: Record<string, unknown>;
34
+ }
35
+ /** A local issuer with a private key, so a test can mint real tokens. */
36
+ export interface TestIssuer {
37
+ /** The issuer to hand the endpoint under test. */
38
+ config: LocalIssuer;
39
+ /** Mints one signed access token. */
40
+ mint(options?: MintOptions): Promise<string>;
41
+ }
42
+ /**
43
+ * Makes an issuer with an RSA key pair and a JWK set holding its public key.
44
+ *
45
+ * The issuer is local, so a test fetches nothing. Its key set is a plain object,
46
+ * which a test may also serve over HTTP to stand in for a remote issuer.
47
+ */
48
+ export declare function createTestIssuer(options?: TestIssuerOptions): Promise<TestIssuer>;
49
+ /** A function that answers one request, such as a Hono app's `fetch`. */
50
+ export type ProbeFetch = (request: Request) => Response | Promise<Response>;
51
+ /** The method one probe request uses. */
52
+ export type ProbeMethod = "GET" | "POST";
53
+ /** One probe request whose answer the probe's rule refused. */
54
+ export interface ProbeFinding {
55
+ /** The path variant the request was sent to. */
56
+ variant: string;
57
+ /** The method the request used. */
58
+ method: ProbeMethod;
59
+ /** The answer's status; 0 means the request threw before an answer came. */
60
+ status: number;
61
+ }
62
+ /** The options `probeGuard` takes; each has a default. */
63
+ export interface ProbeOptions {
64
+ /** The origin requests go to; default `http://localhost`. */
65
+ origin?: string;
66
+ /** The endpoint's path, which the default variants vary; default `/mcp`. */
67
+ path?: string;
68
+ /** The full paths to probe, in place of the default variants for `path`. */
69
+ variants?: readonly string[];
70
+ /** Reads one answer as safe; `defaultProbeIsSafe` when unset. */
71
+ isSafe?: (response: Response, variant: string) => boolean | Promise<boolean>;
72
+ }
73
+ /**
74
+ * Sends requests with no credentials to an endpoint and to the variants a
75
+ * router or proxy may also send there, and reports every answer the rule
76
+ * refuses.
77
+ *
78
+ * Send them through the whole built app's `fetch`, so a router or framework
79
+ * fault that skips the guard shows up here. A request that throws is reported
80
+ * with status 0, which no rule treats as safe by default, so one broken variant
81
+ * still leaves every other answer in the list.
82
+ */
83
+ export declare function probeGuard(send: ProbeFetch, options?: ProbeOptions): Promise<ProbeFinding[]>;
84
+ /**
85
+ * The paths a probe sends, the endpoint's own path first.
86
+ *
87
+ * Each of the rest is a path a router or proxy may treat as the endpoint's
88
+ * while the guard's exact path does not match it: a trailing slash, a change of
89
+ * case, a doubled leading slash, dot segments, an encoded first letter, an
90
+ * encoded slash before and after, a backslash, and a trailing `;` or `?`.
91
+ */
92
+ export declare function defaultProbeVariants(path: string): string[];
93
+ /**
94
+ * Reads an answer as safe for a guarded endpoint: a refusal, a missing route, a
95
+ * wrong method or a limit hit.
96
+ *
97
+ * An app with a page for unknown paths passes a rule of its own that also
98
+ * accepts that page.
99
+ */
100
+ export declare function defaultProbeIsSafe(response: Response): boolean;
101
+ export type { LocalIssuer };
@@ -0,0 +1,172 @@
1
+ import { SignJWT, exportJWK, generateKeyPair } from "jose";
2
+ // src/testing.ts
3
+ /**
4
+ * Makes an issuer with an RSA key pair and a JWK set holding its public key.
5
+ *
6
+ * The issuer is local, so a test fetches nothing. Its key set is a plain object,
7
+ * which a test may also serve over HTTP to stand in for a remote issuer.
8
+ */
9
+ async function createTestIssuer(options = {}) {
10
+ const defaults = {
11
+ issuer: options.issuer ?? "https://issuer.test/",
12
+ audience: options.audience ?? "test-client",
13
+ kid: options.kid ?? "test-key"
14
+ };
15
+ const { privateKey, publicKey } = await generateKeyPair("RS256");
16
+ const jwks = { keys: [{
17
+ ...await exportJWK(publicKey),
18
+ kid: defaults.kid,
19
+ alg: "RS256",
20
+ use: "sig"
21
+ }] };
22
+ return {
23
+ config: {
24
+ issuer: defaults.issuer,
25
+ audiences: [defaults.audience],
26
+ jwks
27
+ },
28
+ mint: (mintOptions = {}) => mintToken(privateKey, defaults, mintOptions)
29
+ };
30
+ }
31
+ async function mintToken(privateKey, defaults, options) {
32
+ const kid = options.kid === null ? void 0 : options.kid ?? defaults.kid;
33
+ const header = kid === void 0 ? { alg: "RS256" } : {
34
+ alg: "RS256",
35
+ kid
36
+ };
37
+ const subject = options.subject === null ? void 0 : options.subject ?? "user-1";
38
+ const token = new SignJWT({ ...options.claims }).setProtectedHeader(options.typ === void 0 ? header : {
39
+ ...header,
40
+ typ: options.typ
41
+ }).setIssuer(options.issuer ?? defaults.issuer).setAudience(options.audience ?? defaults.audience);
42
+ if (subject !== void 0) token.setSubject(subject);
43
+ if (options.expiresIn !== null) token.setExpirationTime(options.expiresIn ?? "5m");
44
+ return token.sign(privateKey);
45
+ }
46
+ /** The origin a probe sends to when the options name none. */
47
+ const DEFAULT_PROBE_ORIGIN = "http://localhost";
48
+ /** The path a probe varies when the options name none. */
49
+ const DEFAULT_PROBE_PATH = "/mcp";
50
+ /** The statuses a probe treats as safe when the options give no rule. */
51
+ const DEFAULT_SAFE_STATUSES = /* @__PURE__ */ new Set([
52
+ 401,
53
+ 403,
54
+ 404,
55
+ 405,
56
+ 429
57
+ ]);
58
+ /** The two methods a probe sends to every variant. */
59
+ const PROBE_METHODS = ["GET", "POST"];
60
+ /** The headers a probe POST carries, as an MCP client sends them. */
61
+ const PROBE_POST_HEADERS = {
62
+ "content-type": "application/json",
63
+ accept: "application/json, text/event-stream"
64
+ };
65
+ /**
66
+ * The body a probe POST carries.
67
+ *
68
+ * It is built here rather than read from the test helpers, so the `./testing`
69
+ * entry loads no app code.
70
+ */
71
+ const PROBE_POST_BODY = JSON.stringify({
72
+ jsonrpc: "2.0",
73
+ id: 1,
74
+ method: "initialize",
75
+ params: {
76
+ protocolVersion: "2025-06-18",
77
+ capabilities: {},
78
+ clientInfo: {
79
+ name: "probe",
80
+ version: "1.0.0"
81
+ }
82
+ }
83
+ });
84
+ /**
85
+ * Sends requests with no credentials to an endpoint and to the variants a
86
+ * router or proxy may also send there, and reports every answer the rule
87
+ * refuses.
88
+ *
89
+ * Send them through the whole built app's `fetch`, so a router or framework
90
+ * fault that skips the guard shows up here. A request that throws is reported
91
+ * with status 0, which no rule treats as safe by default, so one broken variant
92
+ * still leaves every other answer in the list.
93
+ */
94
+ async function probeGuard(send, options = {}) {
95
+ const origin = (options.origin ?? DEFAULT_PROBE_ORIGIN).replace(/\/+$/, "");
96
+ const path = options.path ?? DEFAULT_PROBE_PATH;
97
+ const variants = options.variants ?? defaultProbeVariants(path);
98
+ const isSafe = options.isSafe ?? defaultProbeIsSafe;
99
+ const findings = [];
100
+ for (const variant of variants) for (const method of PROBE_METHODS) {
101
+ const response = await sendProbe(send, `${origin}${variant}`, method);
102
+ if (response === void 0) {
103
+ findings.push({
104
+ variant,
105
+ method,
106
+ status: 0
107
+ });
108
+ continue;
109
+ }
110
+ if (!await isSafe(response, variant)) findings.push({
111
+ variant,
112
+ method,
113
+ status: response.status
114
+ });
115
+ }
116
+ return findings;
117
+ }
118
+ /**
119
+ * The paths a probe sends, the endpoint's own path first.
120
+ *
121
+ * Each of the rest is a path a router or proxy may treat as the endpoint's
122
+ * while the guard's exact path does not match it: a trailing slash, a change of
123
+ * case, a doubled leading slash, dot segments, an encoded first letter, an
124
+ * encoded slash before and after, a backslash, and a trailing `;` or `?`.
125
+ */
126
+ function defaultProbeVariants(path) {
127
+ const first = path.slice(1, 2);
128
+ const tail = path.slice(2);
129
+ return [
130
+ path,
131
+ `${path}/`,
132
+ path.toUpperCase(),
133
+ `/${first.toUpperCase()}${tail}`,
134
+ `/${path}`,
135
+ `/.${path}`,
136
+ `/x/..${path}`,
137
+ `/%${first.charCodeAt(0).toString(16)}${tail}`,
138
+ `/%2F${path.slice(1)}`,
139
+ `${path}%2F`,
140
+ `${path}\\`,
141
+ `${path};`,
142
+ `${path}?`
143
+ ];
144
+ }
145
+ /**
146
+ * Reads an answer as safe for a guarded endpoint: a refusal, a missing route, a
147
+ * wrong method or a limit hit.
148
+ *
149
+ * An app with a page for unknown paths passes a rule of its own that also
150
+ * accepts that page.
151
+ */
152
+ function defaultProbeIsSafe(response) {
153
+ return DEFAULT_SAFE_STATUSES.has(response.status);
154
+ }
155
+ /** Sends one probe request; `undefined` means it threw instead of answering. */
156
+ async function sendProbe(send, url, method) {
157
+ try {
158
+ return await send(new Request(url, probeRequestInit(method)));
159
+ } catch {
160
+ return;
161
+ }
162
+ }
163
+ /** What one probe request carries: the MCP headers and body on a POST only. */
164
+ function probeRequestInit(method) {
165
+ if (method === "GET") return { method };
166
+ return {
167
+ method,
168
+ headers: PROBE_POST_HEADERS,
169
+ body: PROBE_POST_BODY
170
+ };
171
+ }
172
+ export { createTestIssuer, defaultProbeIsSafe, defaultProbeVariants, probeGuard };
@@ -0,0 +1,140 @@
1
+ import { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
2
+ import { JSONWebKeySet, JWTPayload } from "jose";
3
+ /** An issuer whose signing keys are fetched from a JWKS URL. */
4
+ interface RemoteIssuer {
5
+ /** The exact `iss` value accepted for this issuer. */
6
+ issuer: string;
7
+ /** Accepted `aud` values; a token must name at least one. */
8
+ audiences: readonly string[];
9
+ /** The JWKS document URL the keys are fetched from. */
10
+ jwksUrl: string;
11
+ }
12
+ /** An issuer whose signing keys are supplied in place, so no fetch happens. */
13
+ interface LocalIssuer {
14
+ /** The exact `iss` value accepted for this issuer. */
15
+ issuer: string;
16
+ /** Accepted `aud` values; a token must name at least one. */
17
+ audiences: readonly string[];
18
+ /** The key set to check signatures against. */
19
+ jwks: JSONWebKeySet;
20
+ }
21
+ /** One trusted token issuer, remote or local. Narrow with `"jwks" in issuer`. */
22
+ type IssuerConfig = RemoteIssuer | LocalIssuer;
23
+ /** The claims a token was checked against, passed to `identify`. */
24
+ interface CheckedClaims {
25
+ /** The `iss` value the token matched. */
26
+ issuer: string;
27
+ /** The token's `sub`, required and non-empty. */
28
+ subject: string;
29
+ /** The full verified claim set. */
30
+ payload: JWTPayload;
31
+ }
32
+ /** `identify` accepted the caller. */
33
+ interface IdentifiedUser<User> {
34
+ ok: true;
35
+ user: User;
36
+ }
37
+ /** `identify` refused the caller, with the status and message to send. */
38
+ interface IdentifyFailure {
39
+ ok: false;
40
+ status: 401 | 403;
41
+ message: string;
42
+ }
43
+ /** What `identify` returns. */
44
+ type IdentifyResult<User> = IdentifiedUser<User> | IdentifyFailure;
45
+ /** The MCP server name, version and optional instructions. */
46
+ interface ServerInfo {
47
+ name: string;
48
+ version: string;
49
+ instructions?: string;
50
+ }
51
+ /** The values the endpoint's routes and handlers read from the Hono context. */
52
+ interface McpVariables<User> {
53
+ /** The user `identify` returned for the request's token. */
54
+ mcpUser: User;
55
+ /** A keyed hash of the request's `Authorization` header, set when it had one. */
56
+ tokenKey: string;
57
+ }
58
+ /** The Hono environment the endpoint's routes and handlers are typed with. */
59
+ interface McpEnv<User> {
60
+ /** The context values they read. */
61
+ Variables: McpVariables<User>;
62
+ }
63
+ /** One tool call: the tool name and its arguments. */
64
+ interface ToolCall {
65
+ name: string;
66
+ arguments: Readonly<Record<string, unknown>>;
67
+ }
68
+ /** A rate limit: how many events per `windowMs`. */
69
+ interface LimitOptions {
70
+ limit: number;
71
+ windowMs: number;
72
+ }
73
+ /** The endpoint's rate limits; each one uses its default when unset. */
74
+ interface Limits {
75
+ /** 401 and 403 responses, counted per token rather than per address. */
76
+ refusals?: LimitOptions;
77
+ /** Requests per signed-in caller, keyed by `callerKey`. */
78
+ callers?: LimitOptions;
79
+ /** Refused requests across the whole endpoint before new tokens are turned away. */
80
+ flood?: LimitOptions;
81
+ }
82
+ /** Why a token or caller was refused. */
83
+ type RefusalReason = "no_token" | "not_jwt" | "algorithm" | "key_id" | "issuer" | "audience" | "token_type" | "signature" | "expired" | "claims" | "invalid" | "identify";
84
+ /** The endpoint refused a token or caller. */
85
+ interface RefusalEvent {
86
+ type: "refusal";
87
+ status: 401 | 403;
88
+ reason: RefusalReason;
89
+ /** Set only for the `"identify"` reason. */
90
+ message?: string;
91
+ }
92
+ /** A rate limit tripped. */
93
+ interface LimitEvent {
94
+ type: "limit";
95
+ limit: "refusals" | "callers" | "flood";
96
+ }
97
+ /** A tool call threw. */
98
+ interface ToolErrorEvent {
99
+ type: "tool_error";
100
+ tool: string;
101
+ error: unknown;
102
+ }
103
+ /** A stage the endpoint could not complete. */
104
+ interface FaultEvent {
105
+ type: "fault";
106
+ stage: "keys" | "identify" | "caller_key" | "endpoint";
107
+ error: unknown;
108
+ }
109
+ /** Anything the endpoint reports through `onEvent`. */
110
+ type McpEndpointEvent = RefusalEvent | LimitEvent | ToolErrorEvent | FaultEvent;
111
+ /** Every option the endpoint takes. */
112
+ interface McpEndpointOptions<User> {
113
+ /** The absolute public URL of the endpoint. */
114
+ publicUrl: string;
115
+ /** The route the endpoint serves; defaults to `/mcp`. */
116
+ path?: string;
117
+ /** The issuers whose tokens are accepted. */
118
+ issuers: readonly IssuerConfig[];
119
+ /** Scopes advertised in the protected resource document; never enforced. */
120
+ scopes?: readonly string[];
121
+ /** Require `typ` to be `at+jwt`; defaults to `false`. */
122
+ requireAccessTokenType?: boolean;
123
+ /** Turn checked claims into a user, or refuse the caller. */
124
+ identify: (claims: CheckedClaims, request: Request) => IdentifyResult<User> | Promise<IdentifyResult<User>>;
125
+ /** A stable key for rate limiting one caller. */
126
+ callerKey: (user: User) => string;
127
+ /** The server name, version and instructions to advertise. */
128
+ server: ServerInfo;
129
+ /** The tools to advertise and serve. */
130
+ tools: readonly Tool[];
131
+ /** Run one tool call for one user. */
132
+ callTool: (call: ToolCall, user: User) => CallToolResult | Promise<CallToolResult>;
133
+ /** Rate limits; see `Limits`. */
134
+ limits?: Limits;
135
+ /** Largest accepted request body in bytes. */
136
+ maxBodyBytes?: number;
137
+ /** Receives every refusal, limit, tool error and fault. */
138
+ onEvent?: (event: McpEndpointEvent) => void;
139
+ }
140
+ export { ServerInfo as _, IdentifyResult as a, LimitOptions as c, McpEndpointEvent as d, McpEndpointOptions as f, RemoteIssuer as g, RefusalReason as h, IdentifyFailure as i, Limits as l, RefusalEvent as m, FaultEvent as n, IssuerConfig as o, McpEnv as p, IdentifiedUser as r, LimitEvent as s, CheckedClaims as t, LocalIssuer as u, ToolCall as v, ToolErrorEvent as y };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@bensandee/mcp-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "One guarded MCP endpoint for Hono apps",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://codeberg.org/bensandee/common.git",
9
+ "directory": "packages/mcp-server"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "./testing": {
21
+ "types": "./dist/testing.d.mts",
22
+ "default": "./dist/testing.mjs"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org"
29
+ },
30
+ "dependencies": {
31
+ "hono-rate-limiter": "^0.5.4",
32
+ "jose": "^6.2.18",
33
+ "lru-cache": "^11.5.3"
34
+ },
35
+ "devDependencies": {
36
+ "@hono/mcp": "0.3.5",
37
+ "@modelcontextprotocol/sdk": "1.29.0",
38
+ "@types/node": "24.19.2",
39
+ "hono": "4.13.21",
40
+ "tsdown": "0.23.7"
41
+ },
42
+ "peerDependencies": {
43
+ "@hono/mcp": "^0.3.5",
44
+ "@hono/node-server": "^2.1.9",
45
+ "@modelcontextprotocol/sdk": "^1.29.0",
46
+ "hono": "^4.13.19",
47
+ "zod": "^3.25.0 || ^4.0.0"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown",
51
+ "dev": "tsdown --watch",
52
+ "typecheck": "tsc -p tsconfig.json",
53
+ "clean": "rm -rf dist"
54
+ }
6
55
  }