@casys/mcp-server 0.23.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 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
- | | 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 + SSE | Manual | Built-in session management |
34
- | OpenTelemetry tracing | -- | Automatic spans per tool call |
35
- | Prometheus metrics | -- | `/metrics` endpoint |
36
- | MCP Apps (UI resources) | Manual | `registerResource()` + `ui://` |
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 → SSE stream (server→client notifications)
136
+ // GET /mcp → 405 Method Not Allowed (stateless transport)
138
137
  ```
139
138
 
140
139
  **Secure-by-default HTTP options:**
@@ -313,8 +312,6 @@ mcp_server_tool_call_duration_ms_bucket{le="50"} 892
313
312
  mcp_server_tool_call_duration_ms_bucket{le="100"} 987
314
313
  mcp_server_tool_calls_by_name{tool="query",status="success"} 512
315
314
  mcp_server_active_requests 3
316
- mcp_server_active_sessions 42
317
- mcp_server_sse_clients 7
318
315
  mcp_server_uptime_seconds 86400
319
316
  ```
320
317
 
@@ -479,11 +476,6 @@ server.getToolCount();
479
476
  server.getToolNames();
480
477
  server.getResourceCount();
481
478
  server.getResourceUris();
482
- server.getSSEClientCount();
483
-
484
- // SSE (Streamable HTTP)
485
- server.sendToSession(sessionId, message);
486
- server.broadcastNotification(method, params);
487
479
  ```
488
480
 
489
481
  ### Standalone Components
@@ -530,7 +522,6 @@ When running with `startHttp()`:
530
522
  | Method | Path | Description |
531
523
  | ------ | --------------------------------------- | ----------------------------------------------------------- |
532
524
  | `POST` | `/mcp` or `/` | JSON-RPC endpoint (initialize, tools/call, tools/list, ...) |
533
- | `GET` | `/mcp` or `/` | SSE stream (server→client notifications) |
534
525
  | `GET` | `/health` | Health check |
535
526
  | `GET` | `/metrics` | Prometheus metrics |
536
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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
@@ -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
+ */
@@ -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
+ }