@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,330 +0,0 @@
1
- /**
2
- * OpenTelemetry Integration for @casys/mcp-server
3
- *
4
- * Provides tracing for tool calls, auth, and middleware pipeline.
5
- *
6
- * Enable with:
7
- * - Deno: OTEL_DENO=true deno run --unstable-otel ...
8
- * - Node.js: OTEL_ENABLED=true node ...
9
- *
10
- * @module lib/server/observability/otel
11
- */
12
-
13
- import {
14
- type Context,
15
- context as otelContext,
16
- type Span,
17
- type SpanContext,
18
- SpanStatusCode,
19
- trace,
20
- TraceFlags,
21
- type Tracer,
22
- type TraceState,
23
- } from "@opentelemetry/api";
24
- import { env } from "../runtime/runtime.js";
25
-
26
- let serverTracer: Tracer | null = null;
27
-
28
- /**
29
- * W3C `traceparent`: `<2 hex version>-<32 hex trace-id>-<16 hex parent-id>-<2 hex flags>`.
30
- *
31
- * Matches the 55-character prefix only — the trailing-content rule depends on
32
- * the version and is applied separately, see {@link parseTraceParent}.
33
- *
34
- * Case-sensitive on purpose. The spec mandates lowercase hex, and accepting
35
- * uppercase produces a trace id that will not match the same trace elsewhere in
36
- * the pipeline: a silently broken join is worse than a dropped header.
37
- */
38
- const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})/;
39
-
40
- /** `00-` + 32 + `-` + 16 + `-` + 2 = 55. */
41
- const TRACEPARENT_PREFIX_LENGTH = 55;
42
-
43
- /** All-zero ids are explicitly invalid in the W3C spec. */
44
- const INVALID_TRACE_ID = "0".repeat(32);
45
- const INVALID_SPAN_ID = "0".repeat(16);
46
-
47
- /** W3C caps `tracestate` at 32 list members; the rest are dropped. */
48
- const TRACESTATE_MAX_MEMBERS = 32;
49
-
50
- /**
51
- * W3C `tracestate` key, both forms of the ABNF:
52
- * - simple: `lcalpha 0*255(lcalpha / DIGIT / "_" / "-" / "*" / "/")`
53
- * - multi-tenant: `tenant-id "@" system-id`
54
- */
55
- const TRACESTATE_KEY =
56
- /^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/;
57
-
58
- /**
59
- * W3C `tracestate` value — the ABNF is `0*255(chr) nblk-chr`:
60
- *
61
- * - `chr` is printable ASCII except comma and equals. `=` inside a value is
62
- * forbidden, so a member carrying one is malformed, not a value to preserve.
63
- * - the final character is `nblk-chr`, which additionally excludes SP. That
64
- * makes the value **non-empty** and forbids a trailing space, so `vendor=`
65
- * is not a valid member.
66
- */
67
- const TRACESTATE_VALUE =
68
- /^[\x20-\x2B\x2D-\x3C\x3E-\x7E]{0,255}[\x21-\x2B\x2D-\x3C\x3E-\x7E]$/;
69
-
70
- /**
71
- * The grammar's optional whitespace around a list member is SP and HTAB only.
72
- * `String.trim()` also eats CR, LF, FF, VT and Unicode spaces — none of which
73
- * are legal separators here, so trimming with it would silently accept a
74
- * malformed list.
75
- */
76
- function trimOws(member: string): string {
77
- return member.replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
78
- }
79
-
80
- /**
81
- * `tracestate` carried to the next hop.
82
- *
83
- * `@opentelemetry/api` declares the interface but ships no implementation —
84
- * that lives in `@opentelemetry/core`. Pulling in the SDK package for one
85
- * key/value list would put a second OTel dependency in the public API, so this
86
- * is the minimum that satisfies the interface.
87
- *
88
- * Members are validated against the W3C ABNF rather than passed through: the
89
- * spec permits discarding invalid entries, and this list is re-serialised onto
90
- * the next hop — accepting a malformed member here means emitting a malformed
91
- * `tracestate` downstream, turning one peer's bug into ours.
92
- */
93
- class ListTraceState implements TraceState {
94
- readonly #entries: ReadonlyArray<readonly [string, string]>;
95
-
96
- constructor(entries: ReadonlyArray<readonly [string, string]>) {
97
- this.#entries = entries;
98
- }
99
-
100
- static #isValid(key: string, value: string): boolean {
101
- return TRACESTATE_KEY.test(key) && TRACESTATE_VALUE.test(value);
102
- }
103
-
104
- static parse(raw: string): ListTraceState | undefined {
105
- const seen = new Set<string>();
106
- const entries: Array<readonly [string, string]> = [];
107
-
108
- for (const member of raw.split(",")) {
109
- // Optional whitespace around a list member is part of the grammar; the
110
- // key and value themselves are matched exactly.
111
- const trimmed = trimOws(member);
112
- if (trimmed.length === 0) continue;
113
-
114
- const at = trimmed.indexOf("=");
115
- if (at <= 0) continue;
116
-
117
- const key = trimmed.slice(0, at);
118
- const value = trimmed.slice(at + 1);
119
- // Duplicate keys are invalid; the first occurrence is the live one.
120
- if (seen.has(key)) continue;
121
- if (!ListTraceState.#isValid(key, value)) continue;
122
-
123
- seen.add(key);
124
- entries.push([key, value]);
125
- if (entries.length === TRACESTATE_MAX_MEMBERS) break;
126
- }
127
-
128
- return entries.length > 0 ? new ListTraceState(entries) : undefined;
129
- }
130
-
131
- get(key: string): string | undefined {
132
- return this.#entries.find(([k]) => k === key)?.[1];
133
- }
134
-
135
- set(key: string, value: string): TraceState {
136
- // Returns the state unchanged rather than throwing. The OpenTelemetry
137
- // specification is explicit that "API methods MUST NOT throw unhandled
138
- // exceptions when used incorrectly by end users" — telemetry is not worth
139
- // taking an application down for. Rejecting the mutation still keeps the
140
- // invalid member off the wire, which is the property that matters.
141
- if (!ListTraceState.#isValid(key, value)) return this;
142
- // W3C: a mutated key moves to the front of the list.
143
- return new ListTraceState([
144
- [key, value] as const,
145
- ...this.#entries.filter(([k]) => k !== key),
146
- ].slice(0, TRACESTATE_MAX_MEMBERS));
147
- }
148
-
149
- unset(key: string): TraceState {
150
- return new ListTraceState(this.#entries.filter(([k]) => k !== key));
151
- }
152
-
153
- serialize(): string {
154
- return this.#entries.map(([k, v]) => `${k}=${v}`).join(",");
155
- }
156
- }
157
-
158
- /**
159
- * Parse a W3C trace context into an OTel `SpanContext` (spec 2026-07-28).
160
- *
161
- * The revision documents `traceparent` / `tracestate` / `baggage` as `_meta`
162
- * keys so a tool call joins the caller's trace instead of starting a detached
163
- * one. Returns `undefined` for anything malformed — a bad header leaves the span
164
- * unparented, it never fails the call.
165
- *
166
- * Version handling follows the W3C forward-compatibility rule, which is not
167
- * "reject anything unfamiliar":
168
- *
169
- * - `ff` is forbidden outright.
170
- * - `00` is a fixed 55-character format; anything longer is malformed.
171
- * - a higher version MAY carry fields this implementation does not know. The
172
- * receiver parses the first 55 characters and ignores the rest, provided the
173
- * next character is a `-`. Rejecting those would make this server drop trace
174
- * context the day a new version ships — the exact breakage the rule exists to
175
- * prevent.
176
- */
177
- export function parseTraceParent(
178
- traceparent: unknown,
179
- tracestate?: unknown,
180
- ): SpanContext | undefined {
181
- if (typeof traceparent !== "string") return undefined;
182
- if (traceparent.length < TRACEPARENT_PREFIX_LENGTH) return undefined;
183
-
184
- const match = TRACEPARENT.exec(traceparent);
185
- if (!match) return undefined;
186
-
187
- const [, version, traceId, spanId, flags] = match;
188
- if (version === "ff") return undefined;
189
-
190
- if (version === "00") {
191
- if (traceparent.length !== TRACEPARENT_PREFIX_LENGTH) return undefined;
192
- } else if (
193
- traceparent.length > TRACEPARENT_PREFIX_LENGTH &&
194
- traceparent[TRACEPARENT_PREFIX_LENGTH] !== "-"
195
- ) {
196
- // Longer, but not a well-formed continuation: the extra characters are not
197
- // a new field, so the whole header is suspect.
198
- return undefined;
199
- }
200
-
201
- if (traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
202
- return undefined;
203
- }
204
-
205
- const traceState = typeof tracestate === "string"
206
- ? ListTraceState.parse(tracestate)
207
- : undefined;
208
-
209
- return {
210
- traceId,
211
- spanId,
212
- // Only the sampled bit is defined; the rest of the byte is reserved.
213
- traceFlags: (parseInt(flags, 16) & TraceFlags.SAMPLED) as TraceFlags,
214
- isRemote: true,
215
- ...(traceState ? { traceState } : {}),
216
- };
217
- }
218
-
219
- /**
220
- * The OTel context a remote `SpanContext` should parent, or the active one.
221
- *
222
- * Note the fallback is the *active* context, not `ROOT_CONTEXT`: with no
223
- * caller-supplied trace context the span attaches to whatever span is active in
224
- * this process, and only becomes a root when there is none. That is the right
225
- * default — it preserves in-process nesting — but it means "no traceparent" and
226
- * "root span" are not synonyms.
227
- */
228
- function parentContext(remote?: SpanContext): Context {
229
- const active = otelContext.active();
230
- return remote ? trace.setSpanContext(active, remote) : active;
231
- }
232
-
233
- /**
234
- * Get or create the MCP server tracer
235
- */
236
- export function getServerTracer(): Tracer {
237
- if (!serverTracer) {
238
- serverTracer = trace.getTracer("mcp.server", "0.8.0");
239
- }
240
- return serverTracer;
241
- }
242
-
243
- /**
244
- * Span attributes for MCP tool calls
245
- */
246
- export interface ToolCallSpanAttributes {
247
- "mcp.tool.name": string;
248
- "mcp.server.name"?: string;
249
- "mcp.transport"?: string;
250
- "mcp.session.id"?: string;
251
- "mcp.auth.subject"?: string;
252
- "mcp.auth.client_id"?: string;
253
- [key: string]: string | number | boolean | undefined;
254
- }
255
-
256
- /**
257
- * Start a span for a tool call.
258
- * Caller MUST call span.end() when done.
259
- *
260
- * `remoteParent` is the caller's trace context, read from the request's `_meta`
261
- * (spec 2026-07-28). With it the span joins the caller's trace; without it the
262
- * span falls back to the active context, which is what every call produced
263
- * before the `_meta` keys were wired in — a server-side trace nobody could
264
- * correlate to the client that caused it.
265
- */
266
- export function startToolCallSpan(
267
- toolName: string,
268
- attributes: ToolCallSpanAttributes,
269
- remoteParent?: SpanContext,
270
- ): Span {
271
- const tracer = getServerTracer();
272
- return tracer.startSpan(
273
- `mcp.tool.call ${toolName}`,
274
- { attributes },
275
- parentContext(remoteParent),
276
- );
277
- }
278
-
279
- /**
280
- * Record a tool call result on a span and end it.
281
- */
282
- export function endToolCallSpan(
283
- span: Span,
284
- success: boolean,
285
- durationMs: number,
286
- error?: string,
287
- ): void {
288
- span.setAttribute("mcp.tool.duration_ms", durationMs);
289
- span.setAttribute("mcp.tool.success", success);
290
-
291
- if (error) {
292
- span.setAttribute("mcp.tool.error", error);
293
- span.recordException(new Error(error));
294
- }
295
-
296
- span.setStatus({
297
- code: success ? SpanStatusCode.OK : SpanStatusCode.ERROR,
298
- message: error,
299
- });
300
- span.end();
301
- }
302
-
303
- /**
304
- * Record an auth event as a fire-and-forget span.
305
- */
306
- export function recordAuthEvent(
307
- event: "verify" | "reject" | "cache_hit",
308
- attributes: Record<string, string | number | boolean | undefined>,
309
- ): void {
310
- const tracer = getServerTracer();
311
- tracer.startActiveSpan(`mcp.auth.${event}`, { attributes }, (span) => {
312
- span.setStatus({
313
- code: event === "reject" ? SpanStatusCode.ERROR : SpanStatusCode.OK,
314
- });
315
- span.end();
316
- });
317
- }
318
-
319
- /**
320
- * Check if OTEL is enabled.
321
- * Deno: OTEL_DENO=true | Node.js: OTEL_ENABLED=true
322
- */
323
- export function isOtelEnabled(): boolean {
324
- try {
325
- return env("OTEL_DENO") === "true" || env("OTEL_ENABLED") === "true";
326
- } catch {
327
- // Deno without --allow-env throws NotCapable
328
- return false;
329
- }
330
- }
@@ -1,149 +0,0 @@
1
- /**
2
- * Runtime adapter — Deno implementation
3
- *
4
- * Implements the RuntimePort contract for Deno.
5
- * Selected automatically by runtime.ts (the selector) when running under Deno.
6
- *
7
- * @see types.ts for the port contract
8
- * @module lib/server/runtime.deno
9
- */
10
-
11
- import type {
12
- FetchHandler,
13
- RuntimePort,
14
- ServeHandle,
15
- ServeOptions,
16
- } from "./types.js";
17
-
18
- // Re-export types so consumers import from a single module
19
- export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
20
-
21
- /**
22
- * Get an environment variable.
23
- */
24
- export function env(key: string): string | undefined {
25
- return Deno.env.get(key);
26
- }
27
-
28
- /**
29
- * Read a UTF-8 text file.
30
- * Returns null if the file does not exist.
31
- */
32
- export async function readTextFile(path: string): Promise<string | null> {
33
- try {
34
- return await Deno.readTextFile(path);
35
- } catch (err) {
36
- if (err instanceof Deno.errors.NotFound) {
37
- return null;
38
- }
39
- throw err;
40
- }
41
- }
42
-
43
- /**
44
- * Write a UTF-8 text file.
45
- */
46
- export async function writeTextFile(
47
- path: string,
48
- content: string,
49
- opts?: { mode?: number },
50
- ): Promise<void> {
51
- await Deno.writeTextFile(path, content, opts);
52
- }
53
-
54
- /**
55
- * Create a directory.
56
- */
57
- export async function mkdir(
58
- path: string,
59
- opts?: { recursive?: boolean; mode?: number },
60
- ): Promise<void> {
61
- await Deno.mkdir(path, opts);
62
- }
63
-
64
- /**
65
- * Remove a file or empty directory. No-op if absent.
66
- */
67
- export async function remove(path: string): Promise<void> {
68
- try {
69
- await Deno.remove(path);
70
- } catch (err) {
71
- if (err instanceof Deno.errors.NotFound) {
72
- return;
73
- }
74
- throw err;
75
- }
76
- }
77
-
78
- /**
79
- * Read directory entry names. Returns [] if absent.
80
- */
81
- export async function readDir(path: string): Promise<string[]> {
82
- try {
83
- const names: string[] = [];
84
- for await (const entry of Deno.readDir(path)) {
85
- names.push(entry.name);
86
- }
87
- return names;
88
- } catch (err) {
89
- if (err instanceof Deno.errors.NotFound) {
90
- return [];
91
- }
92
- throw err;
93
- }
94
- }
95
-
96
- /**
97
- * Start an HTTP server with a fetch-style handler.
98
- */
99
- export function serve(
100
- options: ServeOptions,
101
- handler: FetchHandler,
102
- ): ServeHandle {
103
- let server: Deno.HttpServer | null = null;
104
- try {
105
- server = Deno.serve(
106
- {
107
- port: options.port,
108
- hostname: options.hostname,
109
- onListen: options.onListen,
110
- },
111
- handler,
112
- );
113
- } catch (err) {
114
- const error = toError(err);
115
- if (options.onError) {
116
- options.onError(error);
117
- return {
118
- shutdown: () => Promise.resolve(),
119
- };
120
- }
121
- throw error;
122
- }
123
- return {
124
- shutdown: () => server.shutdown(),
125
- };
126
- }
127
-
128
- /**
129
- * Unref a timer so it doesn't block process exit.
130
- */
131
- export function unrefTimer(id: number): void {
132
- Deno.unrefTimer(id);
133
- }
134
-
135
- /** Compile-time contract check — ensures this module satisfies RuntimePort */
136
- void ({
137
- env,
138
- readTextFile,
139
- writeTextFile,
140
- mkdir,
141
- remove,
142
- readDir,
143
- serve,
144
- unrefTimer,
145
- } satisfies RuntimePort);
146
-
147
- function toError(err: unknown): Error {
148
- return err instanceof Error ? err : new Error(String(err));
149
- }