@casys/mcp-server 0.19.0 → 0.20.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "dependencies": {
13
13
  "@modelcontextprotocol/sdk": "^1.29.0",
14
- "@modelcontextprotocol/ext-apps": "^1.7.1",
14
+ "@modelcontextprotocol/ext-apps": "^1.7.4",
15
15
  "hono": "^4.0.0",
16
16
  "ajv": "^8.17.1",
17
17
  "jose": "^6.0.0",
@@ -32,6 +32,8 @@ export interface ClientIdMetadataDocument {
32
32
  grant_types: ["authorization_code"];
33
33
  response_types: ["code"];
34
34
  token_endpoint_auth_method: "none";
35
+ /** RFC 7591 application type. Always "native" for loopback CLI/desktop clients. */
36
+ application_type: "native" | "web";
35
37
  scope?: string;
36
38
  client_uri?: string;
37
39
  logo_uri?: string;
@@ -121,6 +123,7 @@ export function buildClientIdMetadataDocument(
121
123
  grant_types: ["authorization_code"],
122
124
  response_types: ["code"],
123
125
  token_endpoint_auth_method: "none",
126
+ application_type: "native",
124
127
  } as ClientIdMetadataDocument;
125
128
 
126
129
  if (config.scopes?.length) {
@@ -230,6 +233,7 @@ const RESERVED_METADATA_KEYS = new Set([
230
233
  "grant_types",
231
234
  "response_types",
232
235
  "token_endpoint_auth_method",
236
+ "application_type",
233
237
  ]);
234
238
 
235
239
  function validateExtraMetadataKeys(metadata: unknown): void {
@@ -71,6 +71,7 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
71
71
  grant_types: ["authorization_code"],
72
72
  response_types: ["code"],
73
73
  token_endpoint_auth_method: "none", // public client, PKCE only
74
+ application_type: "native", // loopback CLI/desktop — prevents AS rejection of http://127.0.0.1 redirects
74
75
  };
75
76
  }
76
77
 
package/src/mcp-app.ts CHANGED
@@ -166,6 +166,31 @@ async function readBodyWithLimit(
166
166
  return body;
167
167
  }
168
168
 
169
+ // ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
170
+
171
+ /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
172
+ const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
173
+
174
+ /** Protocol versions accepted by this server in stateless mode */
175
+ const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
176
+ "2026-07-28",
177
+ "2025-06-18",
178
+ "2025-11-25",
179
+ ];
180
+
181
+ /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
182
+ const STATELESS_FALLBACK_VERSION = "2025-06-18";
183
+
184
+ /**
185
+ * Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
186
+ * Used to safely extract fields from JSON-RPC `params` without unsafe casts.
187
+ */
188
+ function isRecord(v: unknown): v is Record<string, unknown> {
189
+ return typeof v === "object" && v !== null && !Array.isArray(v);
190
+ }
191
+
192
+ // ─────────────────────────────────────────────────────────────────────────────
193
+
169
194
  /**
170
195
  * McpApp provides a high-performance MCP server
171
196
  *
@@ -282,6 +307,9 @@ export class McpApp {
282
307
 
283
308
  // Optional sampling support
284
309
  if (options.enableSampling && options.samplingClient) {
310
+ this.log(
311
+ "[DEPRECATED] Sampling is deprecated (MCP 2026-07-28) and will be removed after 2027-07-28.",
312
+ );
285
313
  this.samplingBridge = new SamplingBridge(options.samplingClient);
286
314
  }
287
315
 
@@ -1143,7 +1171,11 @@ export class McpApp {
1143
1171
  "mcp-protocol-version",
1144
1172
  "last-event-id",
1145
1173
  ],
1146
- exposeHeaders: ["Content-Length", "mcp-session-id"],
1174
+ exposeHeaders: [
1175
+ "Content-Length",
1176
+ "mcp-session-id",
1177
+ "mcp-protocol-version",
1178
+ ],
1147
1179
  maxAge: 600,
1148
1180
  }),
1149
1181
  );
@@ -1232,6 +1264,7 @@ export class McpApp {
1232
1264
  const checkHttpRateLimit = async (
1233
1265
  request: Request,
1234
1266
  sessionId?: string,
1267
+ overrideHeaders?: Headers, // Track A: sanitized headers for stateless mode (no mcp-session-id)
1235
1268
  ): Promise<{ allowed: boolean; retryAfterMs: number }> => {
1236
1269
  if (!httpRateLimiter || !httpRateLimit) {
1237
1270
  return { allowed: true, retryAfterMs: 0 };
@@ -1242,7 +1275,7 @@ export class McpApp {
1242
1275
  ip,
1243
1276
  method: request.method,
1244
1277
  path: new URL(request.url).pathname,
1245
- headers: request.headers,
1278
+ headers: overrideHeaders ?? request.headers,
1246
1279
  sessionId,
1247
1280
  };
1248
1281
  const key = httpRateLimit.keyExtractor?.(context) ?? ip;
@@ -1297,6 +1330,11 @@ export class McpApp {
1297
1330
  // MCP endpoint - GET opens SSE stream for server→client messages (Streamable HTTP spec)
1298
1331
  // deno-lint-ignore no-explicit-any
1299
1332
  const handleMcpGet = async (c: any) => {
1333
+ // Track A: stateless V2 — SSE channel not applicable (Track B replaces it)
1334
+ if (this.options.transport === "stateless") {
1335
+ return c.text("Method Not Allowed", 405);
1336
+ }
1337
+
1300
1338
  const accept = c.req.header("accept") ?? "";
1301
1339
  const sessionId = c.req.header("mcp-session-id");
1302
1340
  const lastEventId = c.req.header("last-event-id");
@@ -1398,12 +1436,31 @@ export class McpApp {
1398
1436
  header: (name: string) => string | undefined;
1399
1437
  };
1400
1438
  json: (data: unknown, status?: number) => Response;
1439
+ /** Accumulate a response header (Hono Context API — Track A: MCP-Protocol-Version) */
1440
+ header: (name: string, value: string) => void;
1401
1441
  },
1402
1442
  ) => {
1403
1443
  let requestId: string | number | null = null;
1404
1444
  try {
1405
- const reqSessionId = c.req.header("mcp-session-id");
1406
- const rateLimit = await checkHttpRateLimit(c.req.raw, reqSessionId);
1445
+ // Track A: in stateless mode, ignore Mcp-Session-Id so it cannot be used
1446
+ // as a rate-limit key (session bypass attack surface removed).
1447
+ const reqSessionId = this.options.transport === "stateless"
1448
+ ? undefined
1449
+ : c.req.header("mcp-session-id");
1450
+ // Track A: strip mcp-session-id from headers passed to rate-limit context
1451
+ // so a keyExtractor cannot use rotating session IDs to bypass IP-level limits.
1452
+ const rlHeaders = this.options.transport === "stateless"
1453
+ ? (() => {
1454
+ const h = new Headers(c.req.raw.headers);
1455
+ h.delete("mcp-session-id");
1456
+ return h;
1457
+ })()
1458
+ : undefined;
1459
+ const rateLimit = await checkHttpRateLimit(
1460
+ c.req.raw,
1461
+ reqSessionId,
1462
+ rlHeaders,
1463
+ );
1407
1464
  if (!rateLimit.allowed) {
1408
1465
  const retryAfter = Math.max(
1409
1466
  1,
@@ -1466,8 +1523,88 @@ export class McpApp {
1466
1523
  httpAuthInfo = authResult.authInfo;
1467
1524
  }
1468
1525
 
1526
+ // Track A: per-request protocolVersion validation in stateless mode.
1527
+ // Must run BEFORE any method dispatch so every call (not just initialize)
1528
+ // is validated. Sets MCP-Protocol-Version header on all subsequent responses
1529
+ // via Hono's c.header() accumulation.
1530
+ // Key location: params._meta[STATELESS_PROTO_KEY] (spec 2026-07-28, confirmed).
1531
+ // TODO(spec-2026-07-28, valider en interop MCP Inspector): MCP-Protocol-Version
1532
+ // request header comparison to body version not enforced until spec text is final.
1533
+ let statelessVersion: string | undefined;
1534
+ if (this.options.transport === "stateless") {
1535
+ const clientVersion = isRecord(params) && isRecord(params["_meta"])
1536
+ ? params["_meta"][STATELESS_PROTO_KEY]
1537
+ : undefined;
1538
+
1539
+ if (typeof clientVersion !== "string") {
1540
+ // Header uses fallback version — no negotiated version available yet
1541
+ return jsonRpcResponse(
1542
+ {
1543
+ jsonrpc: "2.0",
1544
+ id,
1545
+ error: {
1546
+ code: -32020,
1547
+ message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1548
+ },
1549
+ },
1550
+ 400,
1551
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1552
+ );
1553
+ }
1554
+
1555
+ if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
1556
+ // AX: data carries machine-readable supported/requested for agent recovery
1557
+ return jsonRpcResponse(
1558
+ {
1559
+ jsonrpc: "2.0",
1560
+ id,
1561
+ error: {
1562
+ code: -32022,
1563
+ message: `Unsupported protocolVersion: "${clientVersion}"`,
1564
+ data: {
1565
+ supported: [...STATELESS_SUPPORTED_VERSIONS],
1566
+ requested: clientVersion,
1567
+ },
1568
+ },
1569
+ },
1570
+ 400,
1571
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1572
+ );
1573
+ }
1574
+
1575
+ statelessVersion = clientVersion;
1576
+ // Spec 2026-07-28: echo negotiated version in every response header.
1577
+ // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1578
+ c.header("MCP-Protocol-Version", statelessVersion);
1579
+ }
1580
+
1469
1581
  // Initialize - create session and return session ID (now auth-verified)
1470
1582
  if (method === "initialize") {
1583
+ // Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
1584
+ // statelessVersion is guaranteed defined here (per-request block above returned early otherwise).
1585
+ if (this.options.transport === "stateless") {
1586
+ return c.json({
1587
+ jsonrpc: "2.0",
1588
+ id,
1589
+ result: {
1590
+ protocolVersion: statelessVersion as string,
1591
+ capabilities: {
1592
+ tools: {},
1593
+ resources: this.resources.size > 0 ? {} : undefined,
1594
+ },
1595
+ serverInfo: {
1596
+ name: this.options.name,
1597
+ version: this.options.version,
1598
+ },
1599
+ ...(this.options.instructions
1600
+ ? { instructions: this.options.instructions }
1601
+ : {}),
1602
+ },
1603
+ });
1604
+ // Note: c.json() inherits MCP-Protocol-Version header set above.
1605
+ // No Mcp-Session-Id header emitted — stateless by design.
1606
+ }
1607
+
1471
1608
  // Per-IP rate limit on initialize to prevent session exhaustion attacks
1472
1609
  const clientIp = getClientIpFromHeaders(c.req.raw.headers);
1473
1610
  if (!this.initRateLimiter.checkLimit(clientIp)) {
@@ -1527,8 +1664,9 @@ export class McpApp {
1527
1664
  );
1528
1665
  }
1529
1666
 
1530
- // Session validation: all methods after initialize must provide a valid session
1531
- if (reqSessionId) {
1667
+ // Session validation: all methods after initialize must provide a valid session.
1668
+ // Skipped in stateless V2 mode (Track A) — no session concept.
1669
+ if (this.options.transport !== "stateless" && reqSessionId) {
1532
1670
  const session = this.sessions.get(reqSessionId);
1533
1671
  if (!session) {
1534
1672
  return c.json({
@@ -1686,6 +1824,7 @@ export class McpApp {
1686
1824
  if (method === "prompts/list") {
1687
1825
  return c.json({ jsonrpc: "2.0", id, result: { prompts: [] } });
1688
1826
  }
1827
+ // @deprecated (MCP 2026-07-28)
1689
1828
  if (method === "logging/setLevel") {
1690
1829
  return c.json({ jsonrpc: "2.0", id, result: {} });
1691
1830
  }
@@ -1752,11 +1891,14 @@ export class McpApp {
1752
1891
  // deno-lint-ignore no-explicit-any
1753
1892
  options.embeddedHandlerCallback(app.fetch as any);
1754
1893
  this.started = true;
1755
- this.sessionCleanupTimer = setInterval(
1756
- () => this.cleanupSessions(),
1757
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
1758
- );
1759
- unrefTimer(this.sessionCleanupTimer as unknown as number);
1894
+ // Track A: no sessions in stateless mode — skip cleanup timer
1895
+ if (this.options.transport !== "stateless") {
1896
+ this.sessionCleanupTimer = setInterval(
1897
+ () => this.cleanupSessions(),
1898
+ McpApp.SESSION_CLEANUP_INTERVAL_MS,
1899
+ );
1900
+ unrefTimer(this.sessionCleanupTimer as unknown as number);
1901
+ }
1760
1902
  this.log(
1761
1903
  `HTTP handler ready (embedded mode — no port bound, max concurrent: ${
1762
1904
  this.options.maxConcurrent ?? 10
@@ -1787,13 +1929,16 @@ export class McpApp {
1787
1929
 
1788
1930
  this.started = true;
1789
1931
 
1790
- // Start session cleanup timer (prevents unbounded memory growth)
1791
- this.sessionCleanupTimer = setInterval(
1792
- () => this.cleanupSessions(),
1793
- McpApp.SESSION_CLEANUP_INTERVAL_MS,
1794
- );
1795
- // Don't block Deno from exiting because of cleanup timer
1796
- unrefTimer(this.sessionCleanupTimer as unknown as number);
1932
+ // Start session cleanup timer (prevents unbounded memory growth).
1933
+ // Track A: no sessions in stateless mode — skip timer to keep contract clean.
1934
+ if (this.options.transport !== "stateless") {
1935
+ this.sessionCleanupTimer = setInterval(
1936
+ () => this.cleanupSessions(),
1937
+ McpApp.SESSION_CLEANUP_INTERVAL_MS,
1938
+ );
1939
+ // Don't block Deno from exiting because of cleanup timer
1940
+ unrefTimer(this.sessionCleanupTimer as unknown as number);
1941
+ }
1797
1942
 
1798
1943
  const rateLimitInfo = this.options.rateLimit
1799
1944
  ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
@@ -1962,6 +2107,8 @@ export class McpApp {
1962
2107
 
1963
2108
  /**
1964
2109
  * Get sampling bridge (if enabled)
2110
+ *
2111
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
1965
2112
  */
1966
2113
  getSamplingBridge(): SamplingBridge | null {
1967
2114
  return this.samplingBridge;
@@ -24,6 +24,8 @@ import type {
24
24
  * - Promise-based async/await API
25
25
  * - Support for both Anthropic and OpenAI sampling
26
26
  *
27
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
28
+ *
27
29
  * @example
28
30
  * ```typescript
29
31
  * const bridge = new SamplingBridge(samplingClient);
package/src/types.ts CHANGED
@@ -75,7 +75,10 @@ export interface McpAppOptions {
75
75
  */
76
76
  validateSchema?: boolean;
77
77
 
78
- /** Enable sampling support for agentic tools (default: false) */
78
+ /**
79
+ * Enable sampling support for agentic tools (default: false)
80
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
81
+ */
79
82
  enableSampling?: boolean;
80
83
 
81
84
  /**
@@ -84,7 +87,10 @@ export interface McpAppOptions {
84
87
  */
85
88
  instructions?: string;
86
89
 
87
- /** Sampling client implementation (required if enableSampling is true) */
90
+ /**
91
+ * Sampling client implementation (required if enableSampling is true)
92
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
93
+ */
88
94
  samplingClient?: SamplingClient;
89
95
 
90
96
  /** Custom logger function (default: console.error) */
@@ -132,6 +138,22 @@ export interface McpAppOptions {
132
138
  * that discovers child servers after the stdio handshake).
133
139
  */
134
140
  expectResources?: boolean;
141
+
142
+ /**
143
+ * HTTP transport mode (Track A — spec 2026-07-28).
144
+ *
145
+ * - `"stateful"` (DEFAULT): legacy session-based transport, retro-compatible
146
+ * with spec 2025-06-18. Requires an `initialize` handshake before any
147
+ * other method; emits and validates `Mcp-Session-Id` headers.
148
+ * - `"stateless"`: per-request transport, spec 2026-07-28. No handshake, no
149
+ * `Mcp-Session-Id`. `protocolVersion` is read from
150
+ * `params._meta["io.modelcontextprotocol/protocolVersion"]` on every
151
+ * request. `GET /mcp` returns 405 (Track B will replace the SSE channel).
152
+ *
153
+ * Default: `"stateful"`.
154
+ */
155
+ // Track A — transport mode, défaut "stateful"
156
+ transport?: "stateful" | "stateless";
135
157
  }
136
158
 
137
159
  // ============================================
@@ -481,6 +503,8 @@ export type ToolErrorMapper = (
481
503
  /**
482
504
  * Sampling client interface for bidirectional LLM delegation
483
505
  * Compatible with the agentic sampling protocol (SEP-1577)
506
+ *
507
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
484
508
  */
485
509
  export interface SamplingClient {
486
510
  /**
@@ -494,6 +518,8 @@ export interface SamplingClient {
494
518
  /**
495
519
  * Parameters for sampling request
496
520
  * Compatible with MCP sampling protocol
521
+ *
522
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
497
523
  */
498
524
  export interface SamplingParams {
499
525
  messages: Array<{ role: "user" | "assistant"; content: string }>;
@@ -515,6 +541,8 @@ export interface SamplingParams {
515
541
  /**
516
542
  * Result from sampling request
517
543
  * Compatible with MCP sampling protocol
544
+ *
545
+ * @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
518
546
  */
519
547
  export interface SamplingResult {
520
548
  content: Array<{