@casys/mcp-server 0.24.1 → 0.26.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.
@@ -12,6 +12,7 @@ export {
12
12
  endToolCallSpan,
13
13
  getServerTracer,
14
14
  isOtelEnabled,
15
+ parseTraceParent,
15
16
  recordAuthEvent,
16
17
  startToolCallSpan,
17
18
  type ToolCallSpanAttributes,
@@ -11,15 +11,225 @@
11
11
  */
12
12
 
13
13
  import {
14
+ type Context,
15
+ context as otelContext,
14
16
  type Span,
17
+ type SpanContext,
15
18
  SpanStatusCode,
16
19
  trace,
20
+ TraceFlags,
17
21
  type Tracer,
22
+ type TraceState,
18
23
  } from "@opentelemetry/api";
19
24
  import { env } from "../runtime/runtime.js";
20
25
 
21
26
  let serverTracer: Tracer | null = null;
22
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
+
23
233
  /**
24
234
  * Get or create the MCP server tracer
25
235
  */
@@ -46,13 +256,24 @@ export interface ToolCallSpanAttributes {
46
256
  /**
47
257
  * Start a span for a tool call.
48
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.
49
265
  */
50
266
  export function startToolCallSpan(
51
267
  toolName: string,
52
268
  attributes: ToolCallSpanAttributes,
269
+ remoteParent?: SpanContext,
53
270
  ): Span {
54
271
  const tracer = getServerTracer();
55
- return tracer.startSpan(`mcp.tool.call ${toolName}`, { attributes });
272
+ return tracer.startSpan(
273
+ `mcp.tool.call ${toolName}`,
274
+ { attributes },
275
+ parentContext(remoteParent),
276
+ );
56
277
  }
57
278
 
58
279
  /**
@@ -0,0 +1,110 @@
1
+ /**
2
+ * A real stdio server, started the way a consumer starts one.
3
+ *
4
+ * Spawned as a subprocess by `stdio-e2e_test.ts`. Kept as a fixture rather than
5
+ * written to a temp file at run time so the thing under test is readable and
6
+ * versioned: this is exactly the five lines from the README.
7
+ */
8
+
9
+ import { McpApp } from "../mcp-app.js";
10
+ import { MCP_APP_MIME_TYPE } from "../types.js";
11
+
12
+ const RESOURCE_URI = "ui://e2e-stdio/lifecycle";
13
+ const BATCH_RESOURCES = ["batch-a", "batch-b"].map((name) => ({
14
+ uri: `ui://e2e-stdio/${name}`,
15
+ name,
16
+ }));
17
+
18
+ function registerBatch(): string {
19
+ app.registerResources(
20
+ BATCH_RESOURCES,
21
+ new Map(BATCH_RESOURCES.map((resource) => [
22
+ resource.uri,
23
+ () => ({
24
+ uri: resource.uri,
25
+ mimeType: "text/plain",
26
+ text: resource.name,
27
+ }),
28
+ ])),
29
+ );
30
+ return "registered batch";
31
+ }
32
+
33
+ const app = new McpApp({
34
+ name: "e2e-stdio",
35
+ version: "9.9.9",
36
+ logger: () => {},
37
+ instructions: "fixture server",
38
+ });
39
+
40
+ app.registerTool(
41
+ {
42
+ name: "echo",
43
+ description: "Echo the input",
44
+ inputSchema: {
45
+ type: "object",
46
+ properties: { value: { type: "string" } },
47
+ },
48
+ },
49
+ (args) => args.value ?? "empty",
50
+ );
51
+
52
+ app.registerResource(
53
+ {
54
+ uri: RESOURCE_URI,
55
+ name: "Lifecycle resource",
56
+ mimeType: MCP_APP_MIME_TYPE,
57
+ size: 5,
58
+ },
59
+ () => ({
60
+ uri: RESOURCE_URI,
61
+ mimeType: MCP_APP_MIME_TYPE,
62
+ text: "hello",
63
+ _meta: { fixture: "stdio" },
64
+ }),
65
+ );
66
+
67
+ app.registerTool(
68
+ {
69
+ name: "unregister_lifecycle_resource",
70
+ description: "Remove the fixture resource after startup",
71
+ inputSchema: { type: "object" },
72
+ },
73
+ () => app.unregisterResource(RESOURCE_URI) ? "removed" : "absent",
74
+ );
75
+
76
+ app.registerTool(
77
+ {
78
+ name: "register_resource_batch",
79
+ description: "Register two resources in one post-start batch",
80
+ inputSchema: { type: "object" },
81
+ },
82
+ registerBatch,
83
+ );
84
+
85
+ app.registerTool(
86
+ {
87
+ name: "register_duplicate_resource_batch",
88
+ description: "Attempt to register the same batch again",
89
+ inputSchema: { type: "object" },
90
+ },
91
+ registerBatch,
92
+ );
93
+
94
+ app.registerTool(
95
+ {
96
+ name: "register_second_lifecycle_resource",
97
+ description: "Register one resource after the stdio transport starts",
98
+ inputSchema: { type: "object" },
99
+ },
100
+ () => {
101
+ const uri = "ui://e2e-stdio/second";
102
+ app.registerResource(
103
+ { uri, name: "Second lifecycle resource" },
104
+ () => ({ uri, mimeType: "text/plain", text: "second" }),
105
+ );
106
+ return "registered";
107
+ },
108
+ );
109
+
110
+ await app.start();
package/src/types.ts CHANGED
@@ -325,27 +325,84 @@ export interface MCPResource {
325
325
  /** Description of the resource */
326
326
  description?: string;
327
327
 
328
- /** MIME type. Defaults to MCP_APP_MIME_TYPE if not specified */
328
+ /** Optional display title, distinct from the protocol-required `name`. */
329
+ title?: string;
330
+
331
+ /** Optional visual hints advertised in `resources/list`. */
332
+ icons?: Array<{
333
+ src: string;
334
+ mimeType?: string;
335
+ sizes?: string[];
336
+ theme?: "light" | "dark";
337
+ }>;
338
+
339
+ /** Optional client-facing resource annotations. */
340
+ annotations?: {
341
+ audience?: Array<"user" | "assistant">;
342
+ priority?: number;
343
+ lastModified?: string;
344
+ };
345
+
346
+ /** Optional protocol/extension metadata advertised in `resources/list`. */
347
+ _meta?: Record<string, unknown>;
348
+
349
+ /** MIME type, when known before the resource is read. */
329
350
  mimeType?: string;
351
+
352
+ /**
353
+ * Byte size of the resource when it is known.
354
+ *
355
+ * This is an exact byte-size attestation: when supplied, every read must
356
+ * return exactly this many UTF-8 bytes for `text`, or decoded bytes for
357
+ * `blob`. It is surfaced in `resources/list` so clients can make loading
358
+ * decisions before reading. Must be a non-negative safe integer.
359
+ */
360
+ size?: number;
330
361
  }
331
362
 
332
363
  /**
333
- * Content returned by a resource handler
364
+ * Common fields of every resource response.
334
365
  */
335
- export interface ResourceContent {
336
- /** URI of the resource (should match request) */
366
+ interface ResourceContentBase {
367
+ /** URI of the resource. It must exactly match the URI that was requested. */
337
368
  uri: string;
338
- /** MIME type of the content */
369
+ /** Non-empty MIME type of the content. */
339
370
  mimeType: string;
340
- /** The actual content (HTML for MCP Apps) */
371
+ /** Optional MCP metadata passed through to the protocol response. */
372
+ _meta?: Record<string, unknown>;
373
+ }
374
+
375
+ /** A UTF-8/text resource response. */
376
+ export interface TextResourceContent extends ResourceContentBase {
377
+ /** Text payload, including HTML for MCP Apps. */
341
378
  text: string;
379
+ /** Text and blob payloads are mutually exclusive. */
380
+ blob?: never;
381
+ }
382
+
383
+ /** A binary resource response encoded as canonical standard base64. */
384
+ export interface BlobResourceContent extends ResourceContentBase {
385
+ /** Standard, padded base64 payload. */
386
+ blob: string;
387
+ /** Text and blob payloads are mutually exclusive. */
388
+ text?: never;
342
389
  }
343
390
 
391
+ /**
392
+ * Content returned by a resource handler.
393
+ *
394
+ * Exactly one payload form is allowed: `text` for text/HTML, or `blob` for
395
+ * binary content encoded as canonical standard base64. The framework validates
396
+ * the same XOR contract at runtime before writing the response, which keeps
397
+ * JavaScript consumers and unchecked handler results on the protocol-safe path.
398
+ */
399
+ export type ResourceContent = TextResourceContent | BlobResourceContent;
400
+
344
401
  /**
345
402
  * Resource handler callback
346
403
  *
347
404
  * @param uri - The requested resource URI as URL object
348
- * @returns ResourceContent with uri, mimeType, and text
405
+ * @returns A text or base64-blob ResourceContent whose URI matches `uri`
349
406
  *
350
407
  * @example
351
408
  * ```typescript
@@ -354,6 +411,9 @@ export interface ResourceContent {
354
411
  * mimeType: MCP_APP_MIME_TYPE,
355
412
  * text: "<html>...</html>"
356
413
  * });
414
+ *
415
+ * // For binary content, return `blob` instead of `text`:
416
+ * // { uri: uri.toString(), mimeType: "image/png", blob: "iVBORw0KGgo..." }
357
417
  * ```
358
418
  */
359
419
  export type ResourceHandler = (
@@ -8,7 +8,20 @@
8
8
  */
9
9
 
10
10
  // deno-lint-ignore-file no-explicit-any
11
- import AjvDefault from "ajv";
11
+ // Draft 2020-12, not ajv's default export (draft-07). Spec 2026-07-28
12
+ // (SEP-2106) allows any JSON Schema 2020-12 keyword in `inputSchema` /
13
+ // `outputSchema`, and the draft-07 build treats the keywords added in 2020-12 —
14
+ // `prefixItems`, `unevaluatedProperties`, `unevaluatedItems`, `$dynamicRef` —
15
+ // as unknown. Combined with `strict: false` that failure is silent: the schema
16
+ // compiles, the constraint is never applied, and a violating payload validates
17
+ // clean. A tool author's declared boundary has to actually hold.
18
+ //
19
+ // Spelled as the full `dist/` path, not `ajv/2020`: `build-node.sh` copies
20
+ // import specifiers verbatim into the npm distribution, and ajv 8 ships no
21
+ // `exports` map and no root-level `2020.js`, so `ajv/2020` resolves under
22
+ // Deno's import map and then fails at runtime in Node with ERR_MODULE_NOT_FOUND.
23
+ // This path resolves under both.
24
+ import AjvDefault from "ajv/dist/2020.js";
12
25
 
13
26
  // Get the Ajv constructor (handles ESM/CJS differences)
14
27
  const Ajv = (AjvDefault as any).default ?? AjvDefault;