@casys/mcp-server 0.17.0 → 0.17.2
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/mod.ts +4 -0
- package/package.json +1 -1
- package/src/auth/as-metadata-proxy.ts +272 -0
- package/src/auth/mod.ts +4 -0
- package/src/mcp-app.ts +16 -7
package/mod.ts
CHANGED
|
@@ -182,6 +182,10 @@ export {
|
|
|
182
182
|
} from "./src/auth/mod.js";
|
|
183
183
|
export type { PresetOptions } from "./src/auth/mod.js";
|
|
184
184
|
|
|
185
|
+
// Auth - AS Metadata Proxy (DCR discovery for IdPs without native RFC 7591)
|
|
186
|
+
export { createAsMetadataHandler } from "./src/auth/mod.js";
|
|
187
|
+
export type { AsMetadataProxyOptions } from "./src/auth/mod.js";
|
|
188
|
+
|
|
185
189
|
// Auth - Config (YAML + env)
|
|
186
190
|
export {
|
|
187
191
|
createAuthProviderFromConfig,
|
package/package.json
CHANGED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AS Metadata Proxy for DCR Discovery.
|
|
3
|
+
*
|
|
4
|
+
* Creates a Web Standard request handler that serves an RFC 8414
|
|
5
|
+
* Authorization Server Metadata document enriched with
|
|
6
|
+
* `registration_endpoint` (RFC 7591). Enables MCP servers behind IdPs
|
|
7
|
+
* without native Dynamic Client Registration (e.g., Zitadel,
|
|
8
|
+
* unconfigured Keycloak, Okta free tier) to advertise a DCR endpoint
|
|
9
|
+
* so clients like Claude.ai / Cursor can auto-register.
|
|
10
|
+
*
|
|
11
|
+
* **Issuer field note (RFC 8414 §3.2)**:
|
|
12
|
+
* The `issuer` field in the served metadata will be the upstream IdP's
|
|
13
|
+
* issuer, not the URL where this handler is served. This intentionally
|
|
14
|
+
* violates RFC 8414 §3.2 (`issuer` MUST match the AS URL) because
|
|
15
|
+
* overriding `issuer` would cause JWT `iss` claim mismatches — the IdP
|
|
16
|
+
* still issues tokens with its own `iss`, and clients verify
|
|
17
|
+
* `token.iss === metadata.issuer`. The metadata-URL mismatch is the
|
|
18
|
+
* lesser evil and disappears once the IdP ships native DCR.
|
|
19
|
+
*
|
|
20
|
+
* @module lib/server/auth/as-metadata-proxy
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
// ─── Types ───────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Options for {@link createAsMetadataHandler}.
|
|
27
|
+
*
|
|
28
|
+
* Provide exactly one of:
|
|
29
|
+
* - `upstreamMetadataUrl` — full URL of the upstream metadata document
|
|
30
|
+
* - `upstreamIssuer` — OIDC issuer (derives `/.well-known/openid-configuration`)
|
|
31
|
+
*
|
|
32
|
+
* Providing both or neither throws at construction time.
|
|
33
|
+
*/
|
|
34
|
+
export interface AsMetadataProxyOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Full URL of the upstream AS metadata document to proxy.
|
|
37
|
+
*
|
|
38
|
+
* IdP-agnostic — pass the appropriate discovery endpoint:
|
|
39
|
+
* - OIDC providers: `https://idp.example.com/.well-known/openid-configuration`
|
|
40
|
+
* - RFC 8414 AS: `https://as.example.com/.well-known/oauth-authorization-server`
|
|
41
|
+
* - Custom paths: any URL that returns a JSON metadata document
|
|
42
|
+
*
|
|
43
|
+
* Mutually exclusive with `upstreamIssuer`.
|
|
44
|
+
*/
|
|
45
|
+
upstreamMetadataUrl?: string;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* OIDC issuer URL (e.g., `https://my-tenant.zitadel.cloud`).
|
|
49
|
+
* Convenience shorthand — derives `{upstreamIssuer}/.well-known/openid-configuration`.
|
|
50
|
+
*
|
|
51
|
+
* Mutually exclusive with `upstreamMetadataUrl`.
|
|
52
|
+
*/
|
|
53
|
+
upstreamIssuer?: string;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Absolute HTTPS URL of the RFC 7591 DCR endpoint that the MCP server
|
|
57
|
+
* exposes (implemented separately by the consumer — outside lib scope).
|
|
58
|
+
* Injected as `registration_endpoint` in the enriched metadata.
|
|
59
|
+
*
|
|
60
|
+
* Must be a valid absolute HTTP(S) URL (validated at construction time).
|
|
61
|
+
*/
|
|
62
|
+
registrationEndpoint: string;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* TTL for the upstream metadata cache in milliseconds.
|
|
66
|
+
* @default 86_400_000 (24 hours)
|
|
67
|
+
*
|
|
68
|
+
* Uses stale-while-revalidate: serves cached metadata even after
|
|
69
|
+
* expiry while refreshing in the background.
|
|
70
|
+
*/
|
|
71
|
+
cacheTtlMs?: number;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Additional RFC 8414 fields to inject or override in the metadata
|
|
75
|
+
* (beyond `registration_endpoint`). Useful for overriding
|
|
76
|
+
* `scopes_supported`, adding `code_challenge_methods_supported`, etc.
|
|
77
|
+
*
|
|
78
|
+
* **Warning**: avoid overriding `issuer` — see module-level JSDoc
|
|
79
|
+
* for why this causes JWT validation failures.
|
|
80
|
+
*/
|
|
81
|
+
extraFields?: Record<string, unknown>;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Custom `fetch` implementation. Defaults to `globalThis.fetch`.
|
|
85
|
+
*
|
|
86
|
+
* Use for dependency injection in tests, or for advanced scenarios
|
|
87
|
+
* like mTLS, custom headers, or retry wrappers.
|
|
88
|
+
*/
|
|
89
|
+
fetch?: typeof globalThis.fetch;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ─── Implementation ──────────────────────────────────────────────────
|
|
93
|
+
|
|
94
|
+
function stripTrailingSlash(url: string): string {
|
|
95
|
+
return url.endsWith("/") ? url.slice(0, -1) : url;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Validates that a string is a parseable absolute HTTP(S) URL.
|
|
100
|
+
* Throws at construction time for fast failure.
|
|
101
|
+
*/
|
|
102
|
+
function validateUrl(value: string, label: string): void {
|
|
103
|
+
try {
|
|
104
|
+
const parsed = new URL(value);
|
|
105
|
+
if (!parsed.protocol.startsWith("http")) {
|
|
106
|
+
throw new Error(`expected http(s) scheme`);
|
|
107
|
+
}
|
|
108
|
+
} catch (cause) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`AsMetadataProxyOptions.${label} is not a valid HTTP(S) URL: "${value}"`,
|
|
111
|
+
{ cause },
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Resolves the upstream metadata URL from the flat options.
|
|
118
|
+
* Enforces mutual exclusivity: exactly one of upstreamMetadataUrl
|
|
119
|
+
* or upstreamIssuer must be provided.
|
|
120
|
+
*/
|
|
121
|
+
function resolveMetadataUrl(options: AsMetadataProxyOptions): string {
|
|
122
|
+
const { upstreamMetadataUrl, upstreamIssuer } = options;
|
|
123
|
+
const hasUrl = upstreamMetadataUrl !== undefined;
|
|
124
|
+
const hasIssuer = upstreamIssuer !== undefined;
|
|
125
|
+
|
|
126
|
+
if (hasUrl && hasIssuer) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
"AsMetadataProxyOptions: provide either upstreamMetadataUrl or upstreamIssuer, not both",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
if (!hasUrl && !hasIssuer) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
"AsMetadataProxyOptions: one of upstreamMetadataUrl or upstreamIssuer is required",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (hasUrl) {
|
|
138
|
+
validateUrl(upstreamMetadataUrl!, "upstreamMetadataUrl");
|
|
139
|
+
return upstreamMetadataUrl!;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
validateUrl(upstreamIssuer!, "upstreamIssuer");
|
|
143
|
+
return `${stripTrailingSlash(upstreamIssuer!)}/.well-known/openid-configuration`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Creates a Web Standard request handler that serves an RFC 8414
|
|
148
|
+
* Authorization Server Metadata document enriched with
|
|
149
|
+
* `registration_endpoint`.
|
|
150
|
+
*
|
|
151
|
+
* The handler is framework-agnostic — mount it in Fresh, Hono, Express
|
|
152
|
+
* (via adapter), or any framework that accepts `(Request) => Response`.
|
|
153
|
+
*
|
|
154
|
+
* @example Explicit metadata URL (any AS)
|
|
155
|
+
* ```typescript
|
|
156
|
+
* const handler = createAsMetadataHandler({
|
|
157
|
+
* upstreamMetadataUrl: "https://as.example.com/.well-known/oauth-authorization-server",
|
|
158
|
+
* registrationEndpoint: "https://my-app.example.com/oauth/register",
|
|
159
|
+
* });
|
|
160
|
+
* ```
|
|
161
|
+
*
|
|
162
|
+
* @example OIDC issuer shorthand
|
|
163
|
+
* ```typescript
|
|
164
|
+
* const handler = createAsMetadataHandler({
|
|
165
|
+
* upstreamIssuer: "https://my-tenant.zitadel.cloud",
|
|
166
|
+
* registrationEndpoint: "https://my-app.example.com/oauth/register",
|
|
167
|
+
* });
|
|
168
|
+
* ```
|
|
169
|
+
*/
|
|
170
|
+
export function createAsMetadataHandler(
|
|
171
|
+
options: AsMetadataProxyOptions,
|
|
172
|
+
): (req: Request) => Promise<Response> {
|
|
173
|
+
// ── Fail-fast validation at construction time ──
|
|
174
|
+
const metadataUrl = resolveMetadataUrl(options);
|
|
175
|
+
validateUrl(options.registrationEndpoint, "registrationEndpoint");
|
|
176
|
+
if (options.cacheTtlMs !== undefined && (options.cacheTtlMs < 0 || !Number.isFinite(options.cacheTtlMs))) {
|
|
177
|
+
throw new Error("AsMetadataProxyOptions.cacheTtlMs must be a non-negative finite number");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const {
|
|
181
|
+
registrationEndpoint,
|
|
182
|
+
cacheTtlMs = 24 * 60 * 60 * 1000,
|
|
183
|
+
extraFields,
|
|
184
|
+
fetch: fetchFn = globalThis.fetch,
|
|
185
|
+
} = options;
|
|
186
|
+
|
|
187
|
+
let cached: { metadata: Record<string, unknown>; fetchedAt: number } | null =
|
|
188
|
+
null;
|
|
189
|
+
let refreshing = false;
|
|
190
|
+
|
|
191
|
+
async function fetchUpstream(): Promise<Record<string, unknown>> {
|
|
192
|
+
const res = await fetchFn(metadataUrl, {
|
|
193
|
+
signal: AbortSignal.timeout(10_000),
|
|
194
|
+
});
|
|
195
|
+
if (!res.ok) {
|
|
196
|
+
throw new Error(
|
|
197
|
+
`AS metadata fetch failed: ${res.status} from ${metadataUrl}`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const body = await res.json();
|
|
201
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
202
|
+
throw new Error(
|
|
203
|
+
`AS metadata from ${metadataUrl} is not a JSON object (got ${Array.isArray(body) ? "array" : typeof body})`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (typeof body.issuer !== "string") {
|
|
207
|
+
throw new Error(
|
|
208
|
+
`AS metadata from ${metadataUrl} is missing required 'issuer' field`,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
return body as Record<string, unknown>;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function getMetadata(): Promise<Record<string, unknown>> {
|
|
215
|
+
const now = Date.now();
|
|
216
|
+
|
|
217
|
+
// Fresh cache hit
|
|
218
|
+
if (cached && now - cached.fetchedAt < cacheTtlMs) {
|
|
219
|
+
return cached.metadata;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Stale-while-revalidate: serve stale, refresh in background
|
|
223
|
+
if (cached) {
|
|
224
|
+
if (!refreshing) {
|
|
225
|
+
refreshing = true;
|
|
226
|
+
fetchUpstream()
|
|
227
|
+
.then((m) => {
|
|
228
|
+
cached = { metadata: m, fetchedAt: Date.now() };
|
|
229
|
+
})
|
|
230
|
+
.catch((e) =>
|
|
231
|
+
console.error("[as-metadata-proxy] background refresh failed:", e)
|
|
232
|
+
)
|
|
233
|
+
.finally(() => {
|
|
234
|
+
refreshing = false;
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
return cached.metadata;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Cold start: must await
|
|
241
|
+
const metadata = await fetchUpstream();
|
|
242
|
+
cached = { metadata, fetchedAt: now };
|
|
243
|
+
return metadata;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return async (req: Request): Promise<Response> => {
|
|
247
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
248
|
+
return new Response(null, { status: 405, headers: { "Allow": "GET, HEAD" } });
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
const upstream = await getMetadata();
|
|
252
|
+
const enriched = {
|
|
253
|
+
...upstream,
|
|
254
|
+
...extraFields,
|
|
255
|
+
registration_endpoint: registrationEndpoint,
|
|
256
|
+
};
|
|
257
|
+
return new Response(JSON.stringify(enriched), {
|
|
258
|
+
headers: {
|
|
259
|
+
"Content-Type": "application/json",
|
|
260
|
+
"Cache-Control": "public, max-age=3600",
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
} catch (err) {
|
|
264
|
+
console.error("[as-metadata-proxy] upstream fetch failed:", err);
|
|
265
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
266
|
+
return new Response(
|
|
267
|
+
JSON.stringify({ error: "as_metadata_unavailable", message: msg }),
|
|
268
|
+
{ status: 502, headers: { "Content-Type": "application/json" } },
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
package/src/auth/mod.ts
CHANGED
|
@@ -64,6 +64,10 @@ export type {
|
|
|
64
64
|
PresetOptions,
|
|
65
65
|
} from "./presets.js";
|
|
66
66
|
|
|
67
|
+
// AS Metadata Proxy (DCR discovery for IdPs without native RFC 7591)
|
|
68
|
+
export { createAsMetadataHandler } from "./as-metadata-proxy.js";
|
|
69
|
+
export type { AsMetadataProxyOptions } from "./as-metadata-proxy.js";
|
|
70
|
+
|
|
67
71
|
// Config loader (YAML + env)
|
|
68
72
|
export { createAuthProviderFromConfig, loadAuthConfig } from "./config.js";
|
|
69
73
|
// `AuthConfig` is a discriminated union in 0.17.0 — each variant is also
|
package/src/mcp-app.ts
CHANGED
|
@@ -1433,8 +1433,17 @@ export class McpApp {
|
|
|
1433
1433
|
const { id, method, params } = body;
|
|
1434
1434
|
requestId = id ?? null;
|
|
1435
1435
|
|
|
1436
|
-
//
|
|
1437
|
-
//
|
|
1436
|
+
// Auth gate: when requireAuth is configured, ALL requests (including
|
|
1437
|
+
// initialize) must be authenticated per MCP spec 2025-06-18. The 401
|
|
1438
|
+
// response with WWW-Authenticate triggers OAuth discovery in MCP
|
|
1439
|
+
// clients (Claude.ai, Cursor). Without this, clients receive a 200 on
|
|
1440
|
+
// initialize and never attempt the OAuth/DCR flow.
|
|
1441
|
+
if (this.authProvider) {
|
|
1442
|
+
const authDenied = await verifyHttpAuth(c.req.raw);
|
|
1443
|
+
if (authDenied) return authDenied;
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// Initialize - create session and return session ID (now auth-verified)
|
|
1438
1447
|
if (method === "initialize") {
|
|
1439
1448
|
// Per-IP rate limit on initialize to prevent session exhaustion attacks
|
|
1440
1449
|
const clientIp = getClientIpFromHeaders(c.req.raw.headers);
|
|
@@ -1472,7 +1481,7 @@ export class McpApp {
|
|
|
1472
1481
|
jsonrpc: "2.0",
|
|
1473
1482
|
id,
|
|
1474
1483
|
result: {
|
|
1475
|
-
protocolVersion: "2025-
|
|
1484
|
+
protocolVersion: "2025-06-18",
|
|
1476
1485
|
capabilities: {
|
|
1477
1486
|
tools: {},
|
|
1478
1487
|
resources: this.resources.size > 0 ? {} : undefined,
|
|
@@ -1576,10 +1585,10 @@ export class McpApp {
|
|
|
1576
1585
|
}
|
|
1577
1586
|
}
|
|
1578
1587
|
|
|
1579
|
-
// Auth gate
|
|
1580
|
-
//
|
|
1581
|
-
|
|
1582
|
-
|
|
1588
|
+
// Auth gate already applied above (covers all methods including tools/call, tools/list, etc.)
|
|
1589
|
+
// Note: tools/call also runs auth again in the middleware pipeline (createAuthMiddleware),
|
|
1590
|
+
// which provides per-tool scope enforcement. The top-level check above is the gate
|
|
1591
|
+
// that triggers OAuth discovery (401 with WWW-Authenticate).
|
|
1583
1592
|
|
|
1584
1593
|
// Tools list
|
|
1585
1594
|
if (method === "tools/list") {
|