@casys/mcp-server 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -34
- package/mod.ts +46 -3
- package/package.json +1 -1
- package/src/auth/middleware.ts +36 -7
- package/src/client-auth/token-store/memory-store.ts +11 -6
- package/src/http/body.ts +72 -0
- package/src/http/request-guards.ts +137 -0
- package/src/http/wire.ts +41 -0
- package/src/mcp-app.ts +1946 -640
- package/src/middleware/types.ts +33 -0
- package/src/mrtr/capability-check.ts +303 -0
- package/src/mrtr/mod.ts +39 -0
- package/src/mrtr/request-state.ts +435 -0
- package/src/mrtr/types.ts +93 -0
- package/src/observability/metrics.ts +0 -42
- package/src/subscriptions/subscription-registry.ts +558 -0
- package/src/tasks/mod.ts +33 -0
- package/src/tasks/task-store.ts +1014 -0
- package/src/transport/request-headers.ts +661 -0
- package/src/types.ts +143 -24
- package/src/validation/schema-validator.ts +56 -0
- package/src/sampling/sampling-bridge.ts +0 -193
package/README.md
CHANGED
|
@@ -22,19 +22,18 @@ rate-limit → auth → custom middleware → scope-check → validation → bac
|
|
|
22
22
|
The official SDK gives you the protocol. This framework gives you the production
|
|
23
23
|
stack.
|
|
24
24
|
|
|
25
|
-
|
|
|
26
|
-
|
|
|
27
|
-
| MCP protocol compliance
|
|
28
|
-
| Concurrency control
|
|
29
|
-
| Middleware pipeline
|
|
30
|
-
| OAuth2 / JWT auth
|
|
31
|
-
| Rate limiting
|
|
32
|
-
| Schema validation
|
|
33
|
-
| Streamable HTTP
|
|
34
|
-
| OpenTelemetry tracing
|
|
35
|
-
| Prometheus metrics
|
|
36
|
-
| MCP Apps (UI resources)
|
|
37
|
-
| Sampling bridge | -- | Bidirectional LLM delegation |
|
|
25
|
+
| | Official SDK | @casys/mcp-server |
|
|
26
|
+
| --------------------------- | :----------: | :----------------------------: |
|
|
27
|
+
| MCP protocol compliance | Yes | Yes |
|
|
28
|
+
| Concurrency control | -- | 3 backpressure strategies |
|
|
29
|
+
| Middleware pipeline | -- | Composable onion model |
|
|
30
|
+
| OAuth2 / JWT auth | -- | Built-in + 4 OIDC presets |
|
|
31
|
+
| Rate limiting | -- | Sliding window, per-client |
|
|
32
|
+
| Schema validation | -- | JSON Schema (ajv) |
|
|
33
|
+
| Streamable HTTP (stateless) | Manual | `startHttp()` / handler |
|
|
34
|
+
| OpenTelemetry tracing | -- | Automatic spans per tool call |
|
|
35
|
+
| Prometheus metrics | -- | `/metrics` endpoint |
|
|
36
|
+
| MCP Apps (UI resources) | Manual | `registerResource()` + `ui://` |
|
|
38
37
|
|
|
39
38
|
---
|
|
40
39
|
|
|
@@ -134,7 +133,7 @@ await server.startHttp({ port: 3000 });
|
|
|
134
133
|
// GET /health → { status: "ok" }
|
|
135
134
|
// GET /metrics → Prometheus text format
|
|
136
135
|
// POST /mcp → JSON-RPC (tools/call, tools/list, ...)
|
|
137
|
-
// GET /mcp →
|
|
136
|
+
// GET /mcp → 405 Method Not Allowed (stateless transport)
|
|
138
137
|
```
|
|
139
138
|
|
|
140
139
|
**Secure-by-default HTTP options:**
|
|
@@ -248,13 +247,13 @@ When auth is configured, the framework automatically exposes
|
|
|
248
247
|
|
|
249
248
|
### DCR Discovery Proxy (RFC 8414 + RFC 7591)
|
|
250
249
|
|
|
251
|
-
IdPs without native Dynamic Client Registration (Zitadel, unconfigured
|
|
252
|
-
|
|
253
|
-
|
|
250
|
+
IdPs without native Dynamic Client Registration (Zitadel, unconfigured Keycloak,
|
|
251
|
+
Okta free tier) don't publish `registration_endpoint` in their AS metadata, so
|
|
252
|
+
MCP clients like Claude.ai or Cursor can't auto-register.
|
|
254
253
|
|
|
255
|
-
`createAsMetadataHandler` is a framework-agnostic Web Standard handler
|
|
256
|
-
|
|
257
|
-
|
|
254
|
+
`createAsMetadataHandler` is a framework-agnostic Web Standard handler that
|
|
255
|
+
proxies the upstream RFC 8414 metadata and injects a `registration_endpoint`
|
|
256
|
+
pointing to your own DCR proxy:
|
|
258
257
|
|
|
259
258
|
```typescript
|
|
260
259
|
// routes/.well-known/oauth-authorization-server.ts (Fresh example)
|
|
@@ -276,13 +275,12 @@ Then point the PRM at your own host so clients hit the enriched metadata:
|
|
|
276
275
|
authorizationServers: ["https://my-app.example.com"],
|
|
277
276
|
```
|
|
278
277
|
|
|
279
|
-
The DCR endpoint itself (RFC 7591 `/oauth/register`) is out of scope —
|
|
280
|
-
|
|
278
|
+
The DCR endpoint itself (RFC 7591 `/oauth/register`) is out of scope — mount it
|
|
279
|
+
in your framework and forward to the IdP's admin API.
|
|
281
280
|
|
|
282
|
-
**Path caveat**: if the MCP server lives at `/mcp`, clients may build
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
at the exact path your PRM advertises.
|
|
281
|
+
**Path caveat**: if the MCP server lives at `/mcp`, clients may build the
|
|
282
|
+
discovery URL as `<host>/.well-known/oauth-authorization-server/mcp`. Mount the
|
|
283
|
+
handler at the exact path your PRM advertises.
|
|
286
284
|
|
|
287
285
|
### Observability
|
|
288
286
|
|
|
@@ -314,8 +312,6 @@ mcp_server_tool_call_duration_ms_bucket{le="50"} 892
|
|
|
314
312
|
mcp_server_tool_call_duration_ms_bucket{le="100"} 987
|
|
315
313
|
mcp_server_tool_calls_by_name{tool="query",status="success"} 512
|
|
316
314
|
mcp_server_active_requests 3
|
|
317
|
-
mcp_server_active_sessions 42
|
|
318
|
-
mcp_server_sse_clients 7
|
|
319
315
|
mcp_server_uptime_seconds 86400
|
|
320
316
|
```
|
|
321
317
|
|
|
@@ -480,11 +476,6 @@ server.getToolCount();
|
|
|
480
476
|
server.getToolNames();
|
|
481
477
|
server.getResourceCount();
|
|
482
478
|
server.getResourceUris();
|
|
483
|
-
server.getSSEClientCount();
|
|
484
|
-
|
|
485
|
-
// SSE (Streamable HTTP)
|
|
486
|
-
server.sendToSession(sessionId, message);
|
|
487
|
-
server.broadcastNotification(method, params);
|
|
488
479
|
```
|
|
489
480
|
|
|
490
481
|
### Standalone Components
|
|
@@ -531,7 +522,6 @@ When running with `startHttp()`:
|
|
|
531
522
|
| Method | Path | Description |
|
|
532
523
|
| ------ | --------------------------------------- | ----------------------------------------------------------- |
|
|
533
524
|
| `POST` | `/mcp` or `/` | JSON-RPC endpoint (initialize, tools/call, tools/list, ...) |
|
|
534
|
-
| `GET` | `/mcp` or `/` | SSE stream (server→client notifications) |
|
|
535
525
|
| `GET` | `/health` | Health check |
|
|
536
526
|
| `GET` | `/metrics` | Prometheus metrics |
|
|
537
527
|
| `GET` | `/.well-known/oauth-protected-resource` | RFC 9728 metadata (when auth enabled) |
|
package/mod.ts
CHANGED
|
@@ -64,9 +64,6 @@ export type {
|
|
|
64
64
|
ValidationResult,
|
|
65
65
|
} from "./src/validation/schema-validator.js";
|
|
66
66
|
|
|
67
|
-
// Sampling support
|
|
68
|
-
export { SamplingBridge } from "./src/sampling/sampling-bridge.js";
|
|
69
|
-
|
|
70
67
|
// Type exports
|
|
71
68
|
export type {
|
|
72
69
|
HttpRateLimitContext,
|
|
@@ -252,3 +249,49 @@ export type {
|
|
|
252
249
|
// Inspector — launch the MCP Inspector for interactive debugging
|
|
253
250
|
export { launchInspector } from "./src/inspector/launcher.js";
|
|
254
251
|
export type { InspectorOptions } from "./src/inspector/launcher.js";
|
|
252
|
+
|
|
253
|
+
// ── Spec 2026-07-28 features ─────────────────────────────────────────────────
|
|
254
|
+
|
|
255
|
+
// Tasks extension (io.modelcontextprotocol/tasks, SEP-2663).
|
|
256
|
+
//
|
|
257
|
+
// `createTask` is what a tool handler returns to opt into async-task mode, so it
|
|
258
|
+
// has to be reachable from the package root — without it the extension is wired
|
|
259
|
+
// but unusable by any consumer.
|
|
260
|
+
export { createTask } from "./src/tasks/mod.js";
|
|
261
|
+
export type {
|
|
262
|
+
AsyncTaskDescriptor,
|
|
263
|
+
DetailedTask,
|
|
264
|
+
Task,
|
|
265
|
+
TaskController,
|
|
266
|
+
TaskStoreOptions,
|
|
267
|
+
} from "./src/tasks/mod.js";
|
|
268
|
+
|
|
269
|
+
// MRTR — Multi Round-Trip Requests (SEP-2322).
|
|
270
|
+
//
|
|
271
|
+
// `InputRequiredSignal` is the shape a handler returns to ask the client for
|
|
272
|
+
// input. The seal/verify primitives are exported for consumers implementing their
|
|
273
|
+
// own transport; the framework seals automatically on `tools/call`.
|
|
274
|
+
export type {
|
|
275
|
+
InputRequestEntry,
|
|
276
|
+
InputRequestMethod,
|
|
277
|
+
InputRequiredSignal,
|
|
278
|
+
MrtrOptions,
|
|
279
|
+
} from "./src/mrtr/mod.js";
|
|
280
|
+
export {
|
|
281
|
+
exportStateKey,
|
|
282
|
+
generateStateKey,
|
|
283
|
+
sealRequestState,
|
|
284
|
+
verifyRequestState,
|
|
285
|
+
} from "./src/mrtr/mod.js";
|
|
286
|
+
|
|
287
|
+
// subscriptions/listen (SEP-2575).
|
|
288
|
+
//
|
|
289
|
+
// The registry is owned by McpApp; these are exported for consumers driving their
|
|
290
|
+
// own streams, and for the filter type used when narrowing what a deployment
|
|
291
|
+
// delivers.
|
|
292
|
+
export { SubscriptionRegistry } from "./src/subscriptions/subscription-registry.js";
|
|
293
|
+
export type {
|
|
294
|
+
SubscriptionFilter,
|
|
295
|
+
SubscriptionRegistryOptions,
|
|
296
|
+
SubscriptionSink,
|
|
297
|
+
} from "./src/subscriptions/subscription-registry.js";
|
package/package.json
CHANGED
package/src/auth/middleware.ts
CHANGED
|
@@ -12,7 +12,31 @@ import type { AuthInfo } from "./types.js";
|
|
|
12
12
|
import type { Middleware } from "../middleware/types.js";
|
|
13
13
|
import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
// ── Auth error codes ────────────────────────────────────────────────────────
|
|
16
|
+
//
|
|
17
|
+
// Both codes moved OUT of the JSON-RPC reserved range (`-32768`..`-32000`) for
|
|
18
|
+
// spec 2026-07-28, which is stricter than earlier readings of it suggested:
|
|
19
|
+
//
|
|
20
|
+
// * `-32002` — "Implementations of this protocol version **MUST NOT** emit
|
|
21
|
+
// these codes", because 2025-11-25 and earlier used it for resource-not-found
|
|
22
|
+
// (now `-32602`). Keeping it for 403 was a conformance violation, not a
|
|
23
|
+
// grandfathered liberty. Two prior reviews, including one of this file, read
|
|
24
|
+
// the allocation policy as permitting it. It does not.
|
|
25
|
+
// * `-32001` — inside `-32000`..`-32019`, where "new implementations
|
|
26
|
+
// **SHOULD NOT** use codes from this sub-range at all" and receivers "**MUST
|
|
27
|
+
// NOT** assume any specific meaning".
|
|
28
|
+
//
|
|
29
|
+
// The spec's own guidance for codes it does not define: "**SHOULD** be allocated
|
|
30
|
+
// outside the JSON-RPC reserved range". Hence `-31401` / `-31403`, mnemonic for
|
|
31
|
+
// the HTTP statuses they accompany.
|
|
32
|
+
//
|
|
33
|
+
// BREAKING for anything matching on the old numbers — see the changelog.
|
|
34
|
+
|
|
35
|
+
/** 401 Unauthorized: no token, or an invalid one. */
|
|
36
|
+
export const JSONRPC_UNAUTHORIZED = -31401;
|
|
37
|
+
|
|
38
|
+
/** 403 Forbidden: authenticated, but missing a required scope. */
|
|
39
|
+
export const JSONRPC_FORBIDDEN = -31403;
|
|
16
40
|
|
|
17
41
|
function escapeAuthenticateParam(s: string): string {
|
|
18
42
|
return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
@@ -68,7 +92,9 @@ export function createUnauthorizedResponse(
|
|
|
68
92
|
errorDescription?: string,
|
|
69
93
|
): Response {
|
|
70
94
|
const parts = [
|
|
71
|
-
`Bearer resource_metadata="${
|
|
95
|
+
`Bearer resource_metadata="${
|
|
96
|
+
escapeAuthenticateParam(resourceMetadataUrl)
|
|
97
|
+
}"`,
|
|
72
98
|
];
|
|
73
99
|
if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
|
|
74
100
|
if (errorDescription) {
|
|
@@ -81,7 +107,10 @@ export function createUnauthorizedResponse(
|
|
|
81
107
|
JSON.stringify({
|
|
82
108
|
jsonrpc: "2.0",
|
|
83
109
|
id: null,
|
|
84
|
-
error: {
|
|
110
|
+
error: {
|
|
111
|
+
code: JSONRPC_UNAUTHORIZED,
|
|
112
|
+
message: errorDescription ?? "Unauthorized",
|
|
113
|
+
},
|
|
85
114
|
}),
|
|
86
115
|
{
|
|
87
116
|
status: 401,
|
|
@@ -105,11 +134,11 @@ export function createForbiddenResponse(
|
|
|
105
134
|
): Response {
|
|
106
135
|
const requiredScopesDescription = requiredScopes.join(", ");
|
|
107
136
|
const parts = [
|
|
108
|
-
`Bearer resource_metadata="${
|
|
109
|
-
|
|
110
|
-
`error_description="${
|
|
111
|
-
escapeAuthenticateParam(requiredScopesDescription)
|
|
137
|
+
`Bearer resource_metadata="${
|
|
138
|
+
escapeAuthenticateParam(resourceMetadataUrl)
|
|
112
139
|
}"`,
|
|
140
|
+
`error="insufficient_scope"`,
|
|
141
|
+
`error_description="${escapeAuthenticateParam(requiredScopesDescription)}"`,
|
|
113
142
|
];
|
|
114
143
|
|
|
115
144
|
return new Response(
|
|
@@ -9,19 +9,24 @@ import type { StoredCredentials, TokenStore } from "../types.js";
|
|
|
9
9
|
export class MemoryTokenStore implements TokenStore {
|
|
10
10
|
private store = new Map<string, StoredCredentials>();
|
|
11
11
|
|
|
12
|
-
async
|
|
13
|
-
|
|
12
|
+
// Not `async`: the Map operations are synchronous. The interface returns
|
|
13
|
+
// Promises so a real store can be I/O-backed; `Promise.resolve` satisfies it
|
|
14
|
+
// without claiming an await point that does not exist.
|
|
15
|
+
get(serverUrl: string): Promise<StoredCredentials | null> {
|
|
16
|
+
return Promise.resolve(this.store.get(serverUrl) ?? null);
|
|
14
17
|
}
|
|
15
18
|
|
|
16
|
-
|
|
19
|
+
set(serverUrl: string, credentials: StoredCredentials): Promise<void> {
|
|
17
20
|
this.store.set(serverUrl, credentials);
|
|
21
|
+
return Promise.resolve();
|
|
18
22
|
}
|
|
19
23
|
|
|
20
|
-
|
|
24
|
+
delete(serverUrl: string): Promise<void> {
|
|
21
25
|
this.store.delete(serverUrl);
|
|
26
|
+
return Promise.resolve();
|
|
22
27
|
}
|
|
23
28
|
|
|
24
|
-
|
|
25
|
-
return [...this.store.keys()];
|
|
29
|
+
list(): Promise<string[]> {
|
|
30
|
+
return Promise.resolve([...this.store.keys()]);
|
|
26
31
|
}
|
|
27
32
|
}
|
package/src/http/body.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP body reading, with a size ceiling.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `mcp-app.ts`: these are pure functions over Web APIs with no
|
|
5
|
+
* dependency on `McpApp` state, which is exactly what made them separable when
|
|
6
|
+
* the dispatch code was not. Keeping them here makes them unit-testable without
|
|
7
|
+
* standing up a server.
|
|
8
|
+
*
|
|
9
|
+
* Not re-exported from `mod.ts` — this is internal.
|
|
10
|
+
*
|
|
11
|
+
* @module lib/server/http/body
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** Default cap on a request body, in bytes. */
|
|
15
|
+
export const DEFAULT_MAX_BODY_BYTES = 1_000_000;
|
|
16
|
+
|
|
17
|
+
export class BodyTooLargeError extends Error {
|
|
18
|
+
constructor(maxBytes: number) {
|
|
19
|
+
super(`Payload too large. Max ${maxBytes} bytes.`);
|
|
20
|
+
this.name = "BodyTooLargeError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function getClientIpFromHeaders(headers: Headers): string {
|
|
25
|
+
const forwarded = headers.get("x-forwarded-for");
|
|
26
|
+
if (forwarded) {
|
|
27
|
+
return forwarded.split(",")[0]?.trim() || "unknown";
|
|
28
|
+
}
|
|
29
|
+
return headers.get("x-real-ip") ??
|
|
30
|
+
headers.get("cf-connecting-ip") ??
|
|
31
|
+
"unknown";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function readBodyWithLimit(
|
|
35
|
+
request: Request,
|
|
36
|
+
maxBytes: number | null,
|
|
37
|
+
): Promise<Uint8Array> {
|
|
38
|
+
const contentLength = request.headers.get("content-length");
|
|
39
|
+
if (maxBytes !== null && contentLength) {
|
|
40
|
+
const length = Number(contentLength);
|
|
41
|
+
if (!Number.isNaN(length) && length > maxBytes) {
|
|
42
|
+
throw new BodyTooLargeError(maxBytes);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (!request.body) {
|
|
47
|
+
return new Uint8Array();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const reader = request.body.getReader();
|
|
51
|
+
const chunks: Uint8Array[] = [];
|
|
52
|
+
let total = 0;
|
|
53
|
+
|
|
54
|
+
while (true) {
|
|
55
|
+
const { done, value } = await reader.read();
|
|
56
|
+
if (done) break;
|
|
57
|
+
if (!value) continue;
|
|
58
|
+
total += value.length;
|
|
59
|
+
if (maxBytes !== null && total > maxBytes) {
|
|
60
|
+
throw new BodyTooLargeError(maxBytes);
|
|
61
|
+
}
|
|
62
|
+
chunks.push(value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const body = new Uint8Array(total);
|
|
66
|
+
let offset = 0;
|
|
67
|
+
for (const chunk of chunks) {
|
|
68
|
+
body.set(chunk, offset);
|
|
69
|
+
offset += chunk.length;
|
|
70
|
+
}
|
|
71
|
+
return body;
|
|
72
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-scoped guards: who is calling, and may they touch this task.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `mcp-app.ts`. Like `body.ts`, these are pure over their
|
|
5
|
+
* arguments — they read no `McpApp` state — which is what let them move at all.
|
|
6
|
+
* `jsonRpcResponse` stays in `mcp-app.ts` and is passed in rather than imported,
|
|
7
|
+
* so this module has no edge back to the class.
|
|
8
|
+
*
|
|
9
|
+
* Not re-exported from `mod.ts` — internal.
|
|
10
|
+
*
|
|
11
|
+
* @module lib/server/http/request-guards
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
|
|
15
|
+
import type { AuthInfo } from "./../auth/types.js";
|
|
16
|
+
import type { McpAppOptions } from "./../types.js";
|
|
17
|
+
import { jsonRpcResponse, MRTR_NO_AUTH_PRINCIPAL } from "./wire.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Principal to bind a `requestState` to.
|
|
21
|
+
*
|
|
22
|
+
* Three cases, only two of which are acceptable:
|
|
23
|
+
*
|
|
24
|
+
* 1. **No auth configured** — every caller shares one authority by definition, so
|
|
25
|
+
* there is no boundary to enforce and the sentinel above is honest about it.
|
|
26
|
+
* The method and argument bindings still apply.
|
|
27
|
+
* 2. **Authenticated with a subject** — the binding separates callers, which is
|
|
28
|
+
* the case it exists for.
|
|
29
|
+
* 3. **Authenticated without a usable subject** — `AuthInfo.subject` falls back to
|
|
30
|
+
* `"unknown"` for a valid token carrying no `sub` claim. Sealing against that
|
|
31
|
+
* would put every such caller under one identity: a token minted for one could
|
|
32
|
+
* be spent by another, while the code reads as though the binding were
|
|
33
|
+
* enforced. That is worse than no auth, because it is invisible. Throws.
|
|
34
|
+
*/
|
|
35
|
+
export function callerPrincipal(authInfo: AuthInfo | undefined): string | null {
|
|
36
|
+
if (authInfo === undefined) return MRTR_NO_AUTH_PRINCIPAL;
|
|
37
|
+
const subject = authInfo.subject;
|
|
38
|
+
if (subject === undefined || subject === "" || subject === "unknown") {
|
|
39
|
+
// `null`, not a throw: the task handlers call this outside any try/catch, so
|
|
40
|
+
// a throw would surface through the POST-level catch as -32700 "Parse error"
|
|
41
|
+
// — a diagnosis pointing nowhere near a misconfigured auth provider. The
|
|
42
|
+
// caller turns this into an explicit error instead.
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return subject;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Authorization key for a task-related request.
|
|
50
|
+
*
|
|
51
|
+
* Defaults to the authenticated principal. A consumer whose authorization depends
|
|
52
|
+
* on more than identity — a tenant, an organisation, a workspace — supplies
|
|
53
|
+
* `taskOwnerKey` so that dimension becomes part of the key. Without it, binding to
|
|
54
|
+
* the subject alone leaves a task created under one tenant reachable from another
|
|
55
|
+
* by the same user.
|
|
56
|
+
*/
|
|
57
|
+
export async function taskOwnerKeyFor(
|
|
58
|
+
options: McpAppOptions,
|
|
59
|
+
authInfo: AuthInfo | undefined,
|
|
60
|
+
request: Request | undefined,
|
|
61
|
+
principal: string,
|
|
62
|
+
): Promise<string | null> {
|
|
63
|
+
if (options.taskOwnerKey === undefined || request === undefined) {
|
|
64
|
+
return principal;
|
|
65
|
+
}
|
|
66
|
+
let key: unknown;
|
|
67
|
+
try {
|
|
68
|
+
key = await options.taskOwnerKey(authInfo, request);
|
|
69
|
+
} catch {
|
|
70
|
+
// A throwing hook is a consumer bug, but it must fail closed and legibly —
|
|
71
|
+
// not escape to the POST-level catch and be reported as -32700 Parse error.
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
// An empty or non-string key would put every caller under one owner, undoing
|
|
75
|
+
// the isolation the hook exists to provide — and `""` is exactly what the
|
|
76
|
+
// obvious implementation yields when a header is missing. Refuse it rather
|
|
77
|
+
// than silently sharing tasks between callers.
|
|
78
|
+
if (typeof key !== "string" || key.length === 0) return null;
|
|
79
|
+
return key;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The error to return when `taskOwnerKey` produced an unusable value. */
|
|
83
|
+
export function noOwnerKeyError(id: unknown, version: string): Response {
|
|
84
|
+
return jsonRpcResponse(
|
|
85
|
+
{
|
|
86
|
+
jsonrpc: "2.0",
|
|
87
|
+
id,
|
|
88
|
+
error: {
|
|
89
|
+
code: ErrorCode.InternalError,
|
|
90
|
+
message:
|
|
91
|
+
"taskOwnerKey returned an empty or non-string value, which would place every caller under one owner.",
|
|
92
|
+
data: {
|
|
93
|
+
problem: "invalid_task_owner_key",
|
|
94
|
+
recovery:
|
|
95
|
+
'Return a non-empty string. If the value it derives from can be absent, decide explicitly what an anonymous caller\'s key is rather than letting it fall to "".',
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
500,
|
|
100
|
+
{ "MCP-Protocol-Version": version },
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The error to return when no caller boundary can be established. */
|
|
105
|
+
export function noPrincipalError(id: unknown, version: string): Response {
|
|
106
|
+
return jsonRpcResponse(
|
|
107
|
+
{
|
|
108
|
+
jsonrpc: "2.0",
|
|
109
|
+
id,
|
|
110
|
+
error: {
|
|
111
|
+
code: ErrorCode.InternalError,
|
|
112
|
+
message:
|
|
113
|
+
"Server cannot establish a caller identity: the auth provider returned no usable subject for an authenticated request.",
|
|
114
|
+
data: {
|
|
115
|
+
problem: "no_caller_principal",
|
|
116
|
+
recovery:
|
|
117
|
+
"Configure the auth provider to supply a subject claim, or disable auth if all callers genuinely share one authority.",
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
500,
|
|
122
|
+
{ "MCP-Protocol-Version": version },
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Lowercase hex encoding, for the requestState nonce. */
|
|
127
|
+
export function bytesToHexLocal(bytes: Uint8Array): string {
|
|
128
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Build a JSON-RPC response with an explicit HTTP status.
|
|
133
|
+
*
|
|
134
|
+
* Module-scoped rather than nested in `startHttp`: request-validation helpers on
|
|
135
|
+
* the class need it too, and duplicating the header defaults is how a response
|
|
136
|
+
* ends up missing its Content-Type.
|
|
137
|
+
*/
|
package/src/http/wire.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire-level primitives shared by the dispatch code and its extracted guards.
|
|
3
|
+
*
|
|
4
|
+
* This module exists to keep `http/request-guards.ts` from importing
|
|
5
|
+
* `mcp-app.ts`, which would be a cycle. It holds only what both need: no state,
|
|
6
|
+
* no `McpApp` reference.
|
|
7
|
+
*
|
|
8
|
+
* Not re-exported from `mod.ts` — internal.
|
|
9
|
+
*
|
|
10
|
+
* @module lib/server/http/wire
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Sentinel used when there is no authentication at all.
|
|
15
|
+
*
|
|
16
|
+
* Deliberately not a plausible subject value: the NUL prefix cannot appear in a
|
|
17
|
+
* JWT `sub`, so it can never collide with a real principal.
|
|
18
|
+
*/
|
|
19
|
+
export const MRTR_NO_AUTH_PRINCIPAL = "\u0000unauthenticated";
|
|
20
|
+
|
|
21
|
+
export function jsonRpcResponse(
|
|
22
|
+
payload: Record<string, unknown>,
|
|
23
|
+
status: number,
|
|
24
|
+
headers?: Record<string, string>,
|
|
25
|
+
): Response {
|
|
26
|
+
return new Response(JSON.stringify(payload), {
|
|
27
|
+
status,
|
|
28
|
+
headers: {
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
...(headers ?? {}),
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
|
|
37
|
+
* Used to safely extract fields from JSON-RPC `params` without unsafe casts.
|
|
38
|
+
*/
|
|
39
|
+
export function isRecord(v: unknown): v is Record<string, unknown> {
|
|
40
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
41
|
+
}
|