@casys/mcp-server 0.26.1 → 0.27.1

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +10 -627
  4. package/esm/mod.d.ts +1 -0
  5. package/esm/mod.js +1 -0
  6. package/package.json +28 -25
  7. package/mod.ts +0 -302
  8. package/src/auth/as-metadata-proxy.ts +0 -288
  9. package/src/auth/config.ts +0 -368
  10. package/src/auth/jwt-provider.ts +0 -327
  11. package/src/auth/middleware.ts +0 -257
  12. package/src/auth/mod.ts +0 -89
  13. package/src/auth/multi-tenant-middleware.ts +0 -236
  14. package/src/auth/presets.ts +0 -351
  15. package/src/auth/provider.ts +0 -49
  16. package/src/auth/scope-middleware.ts +0 -59
  17. package/src/auth/static-token-provider.ts +0 -197
  18. package/src/auth/types.ts +0 -207
  19. package/src/client-auth/callback-server.ts +0 -166
  20. package/src/client-auth/client-id-metadata.ts +0 -260
  21. package/src/client-auth/connect.ts +0 -72
  22. package/src/client-auth/mod.ts +0 -44
  23. package/src/client-auth/provider.ts +0 -300
  24. package/src/client-auth/token-store/file-store.ts +0 -73
  25. package/src/client-auth/token-store/memory-store.ts +0 -32
  26. package/src/client-auth/types.ts +0 -95
  27. package/src/concurrency/rate-limiter.ts +0 -190
  28. package/src/concurrency/request-queue.ts +0 -140
  29. package/src/http/body.ts +0 -72
  30. package/src/http/request-guards.ts +0 -137
  31. package/src/http/wire.ts +0 -41
  32. package/src/inspector/launcher.ts +0 -131
  33. package/src/mcp-app.ts +0 -4595
  34. package/src/middleware/backpressure.ts +0 -36
  35. package/src/middleware/mod.ts +0 -21
  36. package/src/middleware/rate-limit.ts +0 -45
  37. package/src/middleware/runner.ts +0 -63
  38. package/src/middleware/types.ts +0 -104
  39. package/src/middleware/validation.ts +0 -28
  40. package/src/mrtr/capability-check.ts +0 -303
  41. package/src/mrtr/mod.ts +0 -54
  42. package/src/mrtr/replay-store.ts +0 -103
  43. package/src/mrtr/request-state.ts +0 -435
  44. package/src/mrtr/retry-guard.ts +0 -110
  45. package/src/mrtr/types.ts +0 -107
  46. package/src/observability/metrics.ts +0 -336
  47. package/src/observability/mod.ts +0 -21
  48. package/src/observability/otel.ts +0 -330
  49. package/src/runtime/runtime.deno.ts +0 -149
  50. package/src/runtime/runtime.node.ts +0 -324
  51. package/src/runtime/runtime.ts +0 -50
  52. package/src/runtime/types.ts +0 -130
  53. package/src/security/channel-hmac.ts +0 -140
  54. package/src/security/csp.ts +0 -89
  55. package/src/security/message-signer.ts +0 -223
  56. package/src/subscriptions/subscription-registry.ts +0 -558
  57. package/src/tasks/mod.ts +0 -33
  58. package/src/tasks/task-store.ts +0 -1014
  59. package/src/transport/request-headers.ts +0 -661
  60. package/src/types.ts +0 -908
  61. package/src/ui/viewer-utils.ts +0 -117
  62. package/src/validation/schema-validator.ts +0 -307
@@ -1,190 +0,0 @@
1
- /**
2
- * Rate Limiter
3
- *
4
- * Sliding window rate limiter for per-client request throttling.
5
- * Prevents server overload by limiting requests per time window.
6
- *
7
- * @module lib/server/rate-limiter
8
- */
9
-
10
- /**
11
- * Sliding window rate limiter
12
- *
13
- * Features:
14
- * - Per-key rate limiting (client ID, IP, etc.)
15
- * - Sliding window for smooth rate enforcement
16
- * - Automatic cleanup of old timestamps
17
- * - Backoff waiting when limit exceeded
18
- *
19
- * @example
20
- * ```typescript
21
- * const limiter = new RateLimiter({ maxRequests: 100, windowMs: 60000 });
22
- *
23
- * if (await limiter.checkLimit("client-123")) {
24
- * // Execute request
25
- * } else {
26
- * // Rate limited
27
- * }
28
- * ```
29
- */
30
- export class RateLimiter {
31
- private requestCounts = new Map<string, number[]>();
32
- private readonly windowMs: number;
33
- private readonly maxRequests: number;
34
- private operationsSinceLastPurge = 0;
35
- private static readonly PURGE_EVERY_N_OPS = 1000;
36
-
37
- constructor(options: { maxRequests: number; windowMs: number }) {
38
- this.maxRequests = options.maxRequests;
39
- this.windowMs = options.windowMs;
40
- }
41
-
42
- /**
43
- * Check if request is allowed for the given key
44
- *
45
- * @param key - Identifier (client ID, IP, etc.)
46
- * @returns true if allowed, false if rate limited
47
- */
48
- checkLimit(key: string): boolean {
49
- const now = Date.now();
50
- const requests = this.requestCounts.get(key) || [];
51
-
52
- // Remove old requests outside the sliding window
53
- const validRequests = requests.filter((time) => now - time < this.windowMs);
54
-
55
- if (validRequests.length === 0) {
56
- // No active requests for this key — remove from map to prevent unbounded growth
57
- this.requestCounts.delete(key);
58
- }
59
-
60
- if (validRequests.length >= this.maxRequests) {
61
- // Update with cleaned list
62
- this.requestCounts.set(key, validRequests);
63
- return false;
64
- }
65
-
66
- // Add current request timestamp
67
- validRequests.push(now);
68
- this.requestCounts.set(key, validRequests);
69
-
70
- // Periodic full purge to catch keys that haven't been checked recently
71
- this.operationsSinceLastPurge++;
72
- if (this.operationsSinceLastPurge >= RateLimiter.PURGE_EVERY_N_OPS) {
73
- this.purgeExpiredKeys();
74
- }
75
-
76
- return true;
77
- }
78
-
79
- /**
80
- * Remove all keys with no active requests in the current window.
81
- * Called automatically every PURGE_EVERY_N_OPS operations.
82
- */
83
- purgeExpiredKeys(): number {
84
- const now = Date.now();
85
- let purged = 0;
86
- for (const [key, requests] of this.requestCounts) {
87
- const active = requests.filter((time) => now - time < this.windowMs);
88
- if (active.length === 0) {
89
- this.requestCounts.delete(key);
90
- purged++;
91
- } else {
92
- this.requestCounts.set(key, active);
93
- }
94
- }
95
- this.operationsSinceLastPurge = 0;
96
- return purged;
97
- }
98
-
99
- /**
100
- * Wait until request slot is available (with exponential backoff)
101
- *
102
- * @param key - Identifier (client ID, IP, etc.)
103
- * @throws Error if max wait time exceeded (defaults to windowMs)
104
- */
105
- async waitForSlot(key: string): Promise<void> {
106
- let retries = 0;
107
- const baseDelay = 100;
108
- const maxWaitMs = this.windowMs;
109
- const startTime = Date.now();
110
-
111
- while (!this.checkLimit(key)) {
112
- if (Date.now() - startTime >= maxWaitMs) {
113
- throw new Error(
114
- `Rate limit wait timeout: waited ${maxWaitMs}ms for key "${key}"`,
115
- );
116
- }
117
- // Exponential backoff: 100ms, 200ms, 400ms, 800ms, cap at 1000ms
118
- const delay = Math.min(baseDelay * Math.pow(2, retries), 1000);
119
- await new Promise((resolve) => setTimeout(resolve, delay));
120
- retries++;
121
- }
122
- }
123
-
124
- /**
125
- * Get current request count for a key
126
- */
127
- getCurrentCount(key: string): number {
128
- const now = Date.now();
129
- const requests = this.requestCounts.get(key) || [];
130
- return requests.filter((time) => now - time < this.windowMs).length;
131
- }
132
-
133
- /**
134
- * Get remaining requests for a key
135
- */
136
- getRemainingRequests(key: string): number {
137
- return Math.max(0, this.maxRequests - this.getCurrentCount(key));
138
- }
139
-
140
- /**
141
- * Get time until next slot is available (in ms)
142
- * Returns 0 if a slot is available now
143
- */
144
- getTimeUntilSlot(key: string): number {
145
- const now = Date.now();
146
- const requests = this.requestCounts.get(key) || [];
147
- const validRequests = requests.filter((time) => now - time < this.windowMs);
148
-
149
- if (validRequests.length < this.maxRequests) {
150
- return 0;
151
- }
152
-
153
- // Find oldest request in window - when it expires, a slot opens
154
- const oldest = Math.min(...validRequests);
155
- return Math.max(0, oldest + this.windowMs - now);
156
- }
157
-
158
- /**
159
- * Clear rate limit history for a key
160
- */
161
- clear(key: string): void {
162
- this.requestCounts.delete(key);
163
- }
164
-
165
- /**
166
- * Clear all rate limit history
167
- */
168
- clearAll(): void {
169
- this.requestCounts.clear();
170
- }
171
-
172
- /**
173
- * Get metrics for monitoring
174
- */
175
- getMetrics(): { keys: number; totalRequests: number } {
176
- let totalRequests = 0;
177
- const now = Date.now();
178
-
179
- for (const requests of this.requestCounts.values()) {
180
- totalRequests += requests.filter((time) =>
181
- now - time < this.windowMs
182
- ).length;
183
- }
184
-
185
- return {
186
- keys: this.requestCounts.size,
187
- totalRequests,
188
- };
189
- }
190
- }
@@ -1,140 +0,0 @@
1
- /**
2
- * Request Queue with Concurrency Control and Backpressure
3
- *
4
- * Limits the number of concurrent requests to prevent resource exhaustion
5
- * and implements backpressure strategies when at capacity.
6
- *
7
- * @module lib/server/request-queue
8
- */
9
-
10
- import type { QueueMetrics, QueueOptions } from "../types.js";
11
-
12
- /**
13
- * RequestQueue manages concurrent request execution with backpressure
14
- *
15
- * Features:
16
- * - Limits max concurrent requests (default: 10)
17
- * - Multiple backpressure strategies: sleep, queue, reject
18
- * - Metrics for monitoring (inFlight, queued)
19
- * - Graceful degradation under load
20
- *
21
- * @example
22
- * ```typescript
23
- * const queue = new RequestQueue({
24
- * maxConcurrent: 5,
25
- * strategy: 'queue',
26
- * sleepMs: 10
27
- * });
28
- *
29
- * await queue.acquire();
30
- * try {
31
- * // Execute request
32
- * } finally {
33
- * queue.release();
34
- * }
35
- * ```
36
- */
37
- export class RequestQueue {
38
- private inFlight = 0;
39
- private maxConcurrent: number;
40
- private strategy: "sleep" | "queue" | "reject";
41
- private sleepMs: number;
42
- private waitQueue: Array<() => void> = [];
43
-
44
- constructor(options: QueueOptions) {
45
- this.maxConcurrent = options.maxConcurrent;
46
- this.strategy = options.strategy;
47
- this.sleepMs = options.sleepMs;
48
- }
49
-
50
- /**
51
- * Acquire a slot for request execution
52
- * Blocks until a slot is available based on backpressure strategy
53
- *
54
- * @throws {Error} If strategy is 'reject' and queue is at capacity
55
- */
56
- async acquire(): Promise<void> {
57
- if (this.strategy === "reject") {
58
- // Fail fast - reject immediately if at capacity
59
- if (this.inFlight >= this.maxConcurrent) {
60
- throw new Error(
61
- `Server at capacity (${this.maxConcurrent} concurrent requests)`,
62
- );
63
- }
64
- this.inFlight++;
65
- return;
66
- }
67
-
68
- if (this.strategy === "queue") {
69
- // Queue-based backpressure - wait in FIFO queue.
70
- // Claim the slot BEFORE awaiting to prevent TOCTOU race:
71
- // without this, two waiters woken back-to-back could both see
72
- // inFlight < maxConcurrent and both increment past the limit.
73
- if (this.inFlight >= this.maxConcurrent) {
74
- await new Promise<void>((resolve) => {
75
- this.waitQueue.push(resolve);
76
- });
77
- // Slot was pre-claimed by release() before waking us
78
- } else {
79
- this.inFlight++;
80
- }
81
- return;
82
- }
83
-
84
- // Sleep-based backpressure (default) - busy-wait with sleep.
85
- // The check + increment is safe here because JS is single-threaded
86
- // for synchronous code: after the while loop exits, no other code
87
- // runs before inFlight++ (no await between check and increment).
88
- while (this.inFlight >= this.maxConcurrent) {
89
- await new Promise((resolve) => setTimeout(resolve, this.sleepMs));
90
- }
91
- this.inFlight++;
92
- }
93
-
94
- /**
95
- * Release a slot after request completion
96
- * Notifies next waiting request if using queue strategy
97
- */
98
- release(): void {
99
- if (this.strategy === "queue" && this.waitQueue.length > 0) {
100
- // Transfer the slot directly to the next waiter without decrementing.
101
- // This prevents the TOCTOU race: the waiter wakes up with
102
- // the slot already claimed (inFlight unchanged).
103
- const next = this.waitQueue.shift()!;
104
- next();
105
- } else {
106
- this.inFlight--;
107
- }
108
- }
109
-
110
- /**
111
- * Get current queue metrics for monitoring
112
- */
113
- getMetrics(): QueueMetrics {
114
- return {
115
- inFlight: this.inFlight,
116
- queued: this.waitQueue.length,
117
- };
118
- }
119
-
120
- /**
121
- * Check if queue is at capacity
122
- */
123
- isAtCapacity(): boolean {
124
- return this.inFlight >= this.maxConcurrent;
125
- }
126
-
127
- /**
128
- * Get current in-flight request count
129
- */
130
- getInFlight(): number {
131
- return this.inFlight;
132
- }
133
-
134
- /**
135
- * Get current queued request count
136
- */
137
- getQueued(): number {
138
- return this.waitQueue.length;
139
- }
140
- }
package/src/http/body.ts DELETED
@@ -1,72 +0,0 @@
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
- }
@@ -1,137 +0,0 @@
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 DELETED
@@ -1,41 +0,0 @@
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
- }