@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
package/src/mrtr/types.ts DELETED
@@ -1,107 +0,0 @@
1
- /**
2
- * Type definitions for Multi Round-Trip Requests (MRTR, spec 2026-07-28, SEP-2322).
3
- *
4
- * MRTR entirely replaces the old server-initiated request pattern. Instead of
5
- * the server pushing sampling/createMessage, elicitation/create or roots/list
6
- * over a side channel, the server returns an InputRequiredResult from any
7
- * tools/call, resources/read or prompts/get request. The client gathers the
8
- * data and retries the ORIGINAL method under a NEW JSON-RPC id, carrying
9
- * inputResponses (keyed by the server-assigned ids from the previous result)
10
- * and echoing requestState verbatim if one was included.
11
- *
12
- * @module lib/server/mrtr/types
13
- */
14
-
15
- /** The three request types a server may embed in an InputRequiredResult (spec 2026-07-28). */
16
- export type InputRequestMethod =
17
- | "elicitation/create"
18
- | "sampling/createMessage"
19
- | "roots/list";
20
-
21
- /** One slot in the inputRequests map. */
22
- export interface InputRequestEntry {
23
- readonly method: InputRequestMethod;
24
- readonly params: Record<string, unknown>;
25
- }
26
-
27
- /**
28
- * Return this from a tool/resource handler to trigger an MRTR round-trip.
29
- *
30
- * Spec rule 6 (MUST): at least one of inputRequests or requestState MUST
31
- * be present. The framework validates this and returns -32603 Internal Error
32
- * if both are absent -- that is a server-authoring error, not a client error.
33
- *
34
- * Security note: requestState passes through the client untouched and is
35
- * therefore ATTACKER-CONTROLLED on retry. Use sealRequestState() to bind it
36
- * cryptographically to the authenticated principal, the originating method, and
37
- * the request parameters. Do NOT use an unprotected requestState for
38
- * authorization or resource-access decisions.
39
- */
40
- export interface InputRequiredSignal {
41
- readonly resultType: "input_required";
42
- /**
43
- * Map of server-assigned string ids to sub-request objects.
44
- * Keys must be unique within the scope of the originating request (spec rule 2).
45
- */
46
- readonly inputRequests?: Record<string, InputRequestEntry>;
47
- /**
48
- * Opaque token the client must echo on retry (spec rule 2, client rule 2).
49
- *
50
- * When McpAppOptions.mrtr.signingKey is configured, produce this value
51
- * by calling sealRequestState(). The sealed token binds the principal,
52
- * method, params-digest, expiry and a random nonce under HMAC-SHA256 so the
53
- * server can reject a tampered or replayed token on retry.
54
- *
55
- * Without a signing key, the value is passed through to the client and back
56
- * as-is -- adequate only when requestState influences nothing that requires
57
- * integrity.
58
- */
59
- readonly requestState?: string;
60
- }
61
-
62
- /**
63
- * Configuration for the MRTR subsystem in McpAppOptions.
64
- *
65
- * Wire this in to McpAppOptions.mrtr before calling start() or startHttp().
66
- */
67
- export interface MrtrOptions {
68
- /**
69
- * 64-character lowercase hex string (32 bytes) used as the HMAC-SHA256 key
70
- * for sealing and verifying requestState tokens.
71
- *
72
- * Generate once per deployment with:
73
- * bytesToHex(crypto.getRandomValues(new Uint8Array(32)))
74
- *
75
- * In load-balanced deployments all instances MUST share the same key; rotating
76
- * the key immediately invalidates all in-flight requestState tokens.
77
- *
78
- * If absent, the framework emits a [WARN] at startup and passes requestState
79
- * through without integrity protection. Handlers MUST NOT use unprotected
80
- * requestState for authorization or resource-access decisions.
81
- */
82
- signingKey?: string;
83
-
84
- /**
85
- * Lifetime of a sealed requestState token in seconds.
86
- *
87
- * Default: 300 (5 minutes). The spec warns that these measures do NOT
88
- * guarantee single-use. Deployers who need at-most-once semantics MUST
89
- * enforce that invariant server-side (e.g., by consuming the nonce from a
90
- * shared store on the first use).
91
- */
92
- defaultTtlSecs?: number;
93
-
94
- /**
95
- * Atomic store used to reject a second use of the same signed requestState.
96
- *
97
- * With a signing key and no explicit store, McpApp uses a process-local
98
- * MemoryMrtrReplayStore. That protects one continuously running process only:
99
- * a restart loses its reservations. Every instance in a load-balanced
100
- * deployment MUST receive the same durable shared store implementation.
101
- *
102
- * The nonce is consumed before the handler runs. This provides at-most-once
103
- * admission, not exactly-once completion: if the handler commits a mutation
104
- * and its response is lost, the same token is still rejected on retry.
105
- */
106
- replayStore?: import("./replay-store.js").MrtrReplayStore;
107
- }
@@ -1,336 +0,0 @@
1
- /**
2
- * Server Metrics Collector for @casys/mcp-server
3
- *
4
- * In-memory counters, histograms, and gauges with Prometheus text format export.
5
- * Designed to be embedded in McpApp — no external dependencies.
6
- *
7
- * @module lib/server/observability/metrics
8
- */
9
-
10
- /**
11
- * Histogram bucket
12
- */
13
- interface HistogramBucket {
14
- le: number;
15
- count: number;
16
- }
17
-
18
- /**
19
- * Latency histogram with cumulative buckets
20
- */
21
- interface Histogram {
22
- buckets: HistogramBucket[];
23
- sum: number;
24
- count: number;
25
- }
26
-
27
- /**
28
- * Default histogram buckets (milliseconds)
29
- */
30
- const DEFAULT_BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
31
-
32
- function createHistogram(buckets: number[] = DEFAULT_BUCKETS): Histogram {
33
- return {
34
- buckets: buckets.map((le) => ({ le, count: 0 })),
35
- sum: 0,
36
- count: 0,
37
- };
38
- }
39
-
40
- function observeHistogram(histogram: Histogram, value: number): void {
41
- histogram.sum += value;
42
- histogram.count++;
43
- for (const bucket of histogram.buckets) {
44
- if (value <= bucket.le) {
45
- bucket.count++;
46
- }
47
- }
48
- }
49
-
50
- /**
51
- * Metrics snapshot returned by getMetrics()
52
- */
53
- export interface ServerMetricsSnapshot {
54
- counters: {
55
- tool_calls_total: number;
56
- tool_calls_success: number;
57
- tool_calls_failed: number;
58
- requests_rate_limited: number;
59
- requests_rejected_backpressure: number;
60
- auth_success: number;
61
- auth_failed: number;
62
- auth_cache_hits: number;
63
- };
64
- histograms: {
65
- tool_call_duration_ms: Histogram;
66
- };
67
- gauges: {
68
- active_requests: number;
69
- queued_requests: number;
70
- rate_limiter_keys: number;
71
- };
72
- collected_at: number;
73
- uptime_seconds: number;
74
- }
75
-
76
- /**
77
- * Tool call metrics by tool name
78
- */
79
- interface PerToolMetrics {
80
- calls: number;
81
- success: number;
82
- failed: number;
83
- totalDurationMs: number;
84
- }
85
-
86
- /**
87
- * Server metrics collector.
88
- *
89
- * @example
90
- * ```typescript
91
- * const metrics = new ServerMetrics();
92
- * metrics.recordToolCall("my_tool", true, 42);
93
- * console.log(metrics.toPrometheusFormat());
94
- * ```
95
- */
96
- export class ServerMetrics {
97
- private startTime = Date.now();
98
-
99
- // Counters
100
- private toolCallsTotal = 0;
101
- private toolCallsSuccess = 0;
102
- private toolCallsFailed = 0;
103
- private requestsRateLimited = 0;
104
- private requestsRejectedBackpressure = 0;
105
- private authSuccess = 0;
106
- private authFailed = 0;
107
- private authCacheHits = 0;
108
-
109
- // Histogram
110
- private toolCallDuration = createHistogram();
111
-
112
- // Per-tool breakdown
113
- private perTool = new Map<string, PerToolMetrics>();
114
-
115
- // Gauges (set externally via setGauge)
116
- private activeRequests = 0;
117
- private queuedRequests = 0;
118
- private rateLimiterKeys = 0;
119
-
120
- /**
121
- * Record a completed tool call
122
- */
123
- recordToolCall(toolName: string, success: boolean, durationMs: number): void {
124
- this.toolCallsTotal++;
125
- if (success) {
126
- this.toolCallsSuccess++;
127
- } else {
128
- this.toolCallsFailed++;
129
- }
130
- observeHistogram(this.toolCallDuration, durationMs);
131
-
132
- // Per-tool
133
- let pt = this.perTool.get(toolName);
134
- if (!pt) {
135
- pt = { calls: 0, success: 0, failed: 0, totalDurationMs: 0 };
136
- this.perTool.set(toolName, pt);
137
- }
138
- pt.calls++;
139
- if (success) pt.success++;
140
- else pt.failed++;
141
- pt.totalDurationMs += durationMs;
142
- }
143
-
144
- recordRateLimited(): void {
145
- this.requestsRateLimited++;
146
- }
147
-
148
- recordBackpressureRejected(): void {
149
- this.requestsRejectedBackpressure++;
150
- }
151
-
152
- recordAuth(success: boolean): void {
153
- if (success) this.authSuccess++;
154
- else this.authFailed++;
155
- }
156
-
157
- recordAuthCacheHit(): void {
158
- this.authCacheHits++;
159
- }
160
-
161
- /**
162
- * Update gauge values (called periodically or on-demand)
163
- */
164
- setGauges(gauges: {
165
- activeRequests?: number;
166
- queuedRequests?: number;
167
- rateLimiterKeys?: number;
168
- }): void {
169
- if (gauges.activeRequests !== undefined) {
170
- this.activeRequests = gauges.activeRequests;
171
- }
172
- if (gauges.queuedRequests !== undefined) {
173
- this.queuedRequests = gauges.queuedRequests;
174
- }
175
- if (gauges.rateLimiterKeys !== undefined) {
176
- this.rateLimiterKeys = gauges.rateLimiterKeys;
177
- }
178
- }
179
-
180
- /**
181
- * Get current metrics snapshot
182
- */
183
- getSnapshot(): ServerMetricsSnapshot {
184
- return {
185
- counters: {
186
- tool_calls_total: this.toolCallsTotal,
187
- tool_calls_success: this.toolCallsSuccess,
188
- tool_calls_failed: this.toolCallsFailed,
189
- requests_rate_limited: this.requestsRateLimited,
190
- requests_rejected_backpressure: this.requestsRejectedBackpressure,
191
- auth_success: this.authSuccess,
192
- auth_failed: this.authFailed,
193
- auth_cache_hits: this.authCacheHits,
194
- },
195
- histograms: {
196
- tool_call_duration_ms: { ...this.toolCallDuration },
197
- },
198
- gauges: {
199
- active_requests: this.activeRequests,
200
- queued_requests: this.queuedRequests,
201
- rate_limiter_keys: this.rateLimiterKeys,
202
- },
203
- collected_at: Date.now(),
204
- uptime_seconds: Math.floor((Date.now() - this.startTime) / 1000),
205
- };
206
- }
207
-
208
- /**
209
- * Prometheus text format export
210
- */
211
- toPrometheusFormat(prefix = "mcp_server"): string {
212
- const m = this.getSnapshot();
213
- const lines: string[] = [];
214
-
215
- // --- Counters ---
216
- const counter = (name: string, help: string, value: number) => {
217
- lines.push(`# HELP ${prefix}_${name} ${help}`);
218
- lines.push(`# TYPE ${prefix}_${name} counter`);
219
- lines.push(`${prefix}_${name} ${value}`);
220
- };
221
-
222
- counter(
223
- "tool_calls_total",
224
- "Total tool calls",
225
- m.counters.tool_calls_total,
226
- );
227
- counter(
228
- "tool_calls_success_total",
229
- "Successful tool calls",
230
- m.counters.tool_calls_success,
231
- );
232
- counter(
233
- "tool_calls_failed_total",
234
- "Failed tool calls",
235
- m.counters.tool_calls_failed,
236
- );
237
- counter(
238
- "requests_rate_limited_total",
239
- "Requests rejected by rate limiter",
240
- m.counters.requests_rate_limited,
241
- );
242
- counter(
243
- "requests_backpressure_total",
244
- "Requests rejected by backpressure",
245
- m.counters.requests_rejected_backpressure,
246
- );
247
- counter(
248
- "auth_success_total",
249
- "Successful auth verifications",
250
- m.counters.auth_success,
251
- );
252
- counter(
253
- "auth_failed_total",
254
- "Failed auth verifications",
255
- m.counters.auth_failed,
256
- );
257
- counter(
258
- "auth_cache_hits_total",
259
- "Auth token cache hits",
260
- m.counters.auth_cache_hits,
261
- );
262
-
263
- // --- Per-tool counters ---
264
- lines.push(`# HELP ${prefix}_tool_calls_by_name Tool calls by tool name`);
265
- lines.push(`# TYPE ${prefix}_tool_calls_by_name counter`);
266
- for (const [name, pt] of this.perTool) {
267
- lines.push(
268
- `${prefix}_tool_calls_by_name{tool="${name}",status="success"} ${pt.success}`,
269
- );
270
- lines.push(
271
- `${prefix}_tool_calls_by_name{tool="${name}",status="failed"} ${pt.failed}`,
272
- );
273
- }
274
-
275
- // --- Histogram ---
276
- const h = m.histograms.tool_call_duration_ms;
277
- lines.push(
278
- `# HELP ${prefix}_tool_call_duration_ms Tool call duration in milliseconds`,
279
- );
280
- lines.push(`# TYPE ${prefix}_tool_call_duration_ms histogram`);
281
- for (const bucket of h.buckets) {
282
- lines.push(
283
- `${prefix}_tool_call_duration_ms_bucket{le="${bucket.le}"} ${bucket.count}`,
284
- );
285
- }
286
- lines.push(`${prefix}_tool_call_duration_ms_bucket{le="+Inf"} ${h.count}`);
287
- lines.push(`${prefix}_tool_call_duration_ms_sum ${h.sum}`);
288
- lines.push(`${prefix}_tool_call_duration_ms_count ${h.count}`);
289
-
290
- // --- Gauges ---
291
- const gauge = (name: string, help: string, value: number) => {
292
- lines.push(`# HELP ${prefix}_${name} ${help}`);
293
- lines.push(`# TYPE ${prefix}_${name} gauge`);
294
- lines.push(`${prefix}_${name} ${value}`);
295
- };
296
-
297
- gauge(
298
- "active_requests",
299
- "Currently executing requests",
300
- m.gauges.active_requests,
301
- );
302
- gauge(
303
- "queued_requests",
304
- "Requests waiting in queue",
305
- m.gauges.queued_requests,
306
- );
307
- gauge(
308
- "rate_limiter_keys",
309
- "Tracked rate limiter keys",
310
- m.gauges.rate_limiter_keys,
311
- );
312
- gauge("uptime_seconds", "Server uptime in seconds", m.uptime_seconds);
313
-
314
- return lines.join("\n") + "\n";
315
- }
316
-
317
- /**
318
- * Reset all metrics
319
- */
320
- reset(): void {
321
- this.toolCallsTotal = 0;
322
- this.toolCallsSuccess = 0;
323
- this.toolCallsFailed = 0;
324
- this.requestsRateLimited = 0;
325
- this.requestsRejectedBackpressure = 0;
326
- this.authSuccess = 0;
327
- this.authFailed = 0;
328
- this.authCacheHits = 0;
329
- this.toolCallDuration = createHistogram();
330
- this.perTool.clear();
331
- this.activeRequests = 0;
332
- this.queuedRequests = 0;
333
- this.rateLimiterKeys = 0;
334
- this.startTime = Date.now();
335
- }
336
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Observability module for @casys/mcp-server
3
- *
4
- * - OTel tracing (spans on tool calls, auth events)
5
- * - Metrics collection (counters, histograms, gauges)
6
- * - Prometheus text format export
7
- *
8
- * @module lib/server/observability
9
- */
10
-
11
- export {
12
- endToolCallSpan,
13
- getServerTracer,
14
- isOtelEnabled,
15
- parseTraceParent,
16
- recordAuthEvent,
17
- startToolCallSpan,
18
- type ToolCallSpanAttributes,
19
- } from "./otel.js";
20
-
21
- export { ServerMetrics, type ServerMetricsSnapshot } from "./metrics.js";