@casys/mcp-server 0.20.0 → 0.21.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.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
@@ -12,6 +12,12 @@ import type { AuthInfo } from "./types.js";
12
12
  import type { Middleware } from "../middleware/types.js";
13
13
  import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
14
14
 
15
+ const JSONRPC_FORBIDDEN = -32002;
16
+
17
+ function escapeAuthenticateParam(s: string): string {
18
+ return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
19
+ }
20
+
15
21
  /**
16
22
  * Authentication error with structured information
17
23
  * for generating proper HTTP error responses.
@@ -61,11 +67,14 @@ export function createUnauthorizedResponse(
61
67
  error?: string,
62
68
  errorDescription?: string,
63
69
  ): Response {
64
- const escape = (s: string) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
65
- const parts = [`Bearer resource_metadata="${escape(resourceMetadataUrl)}"`];
66
- if (error) parts.push(`error="${escape(error)}"`);
70
+ const parts = [
71
+ `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
72
+ ];
73
+ if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
67
74
  if (errorDescription) {
68
- parts.push(`error_description="${escape(errorDescription)}"`);
75
+ parts.push(
76
+ `error_description="${escapeAuthenticateParam(errorDescription)}"`,
77
+ );
69
78
  }
70
79
 
71
80
  return new Response(
@@ -88,20 +97,36 @@ export function createUnauthorizedResponse(
88
97
  * Create a 403 Forbidden response for insufficient scopes.
89
98
  *
90
99
  * @param requiredScopes - Scopes that were required but missing
100
+ * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
91
101
  */
92
- export function createForbiddenResponse(requiredScopes: string[]): Response {
102
+ export function createForbiddenResponse(
103
+ requiredScopes: string[],
104
+ resourceMetadataUrl: string,
105
+ ): Response {
106
+ const requiredScopesDescription = requiredScopes.join(", ");
107
+ const parts = [
108
+ `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
109
+ `error="insufficient_scope"`,
110
+ `error_description="${
111
+ escapeAuthenticateParam(requiredScopesDescription)
112
+ }"`,
113
+ ];
114
+
93
115
  return new Response(
94
116
  JSON.stringify({
95
117
  jsonrpc: "2.0",
96
118
  id: null,
97
119
  error: {
98
- code: -32001,
120
+ code: JSONRPC_FORBIDDEN,
99
121
  message: `Forbidden: requires scopes ${requiredScopes.join(", ")}`,
100
122
  },
101
123
  }),
102
124
  {
103
125
  status: 403,
104
- headers: { "Content-Type": "application/json" },
126
+ headers: {
127
+ "Content-Type": "application/json",
128
+ "WWW-Authenticate": parts.join(", "),
129
+ },
105
130
  },
106
131
  );
107
132
  }
@@ -150,18 +175,19 @@ export function createAuthMiddleware(provider: AuthProvider): Middleware {
150
175
  return next();
151
176
  }
152
177
 
178
+ // 0.15.0+: provider's getResourceMetadata() always returns a valid
179
+ // absolute URL in resource_metadata_url (type system guarantees it).
180
+ // No derivation needed at the middleware level anymore.
181
+ const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
182
+
153
183
  // Already authenticated by the HTTP-level gate (verifyHttpAuth).
154
184
  // Skip the redundant verifyToken call to avoid JWKS race conditions
155
185
  // when concurrent requests arrive on a cold cache.
156
186
  if (ctx.authInfo) {
187
+ ctx.resourceMetadataUrl = metadataUrl;
157
188
  return next();
158
189
  }
159
190
 
160
- // 0.15.0+: provider's getResourceMetadata() always returns a valid
161
- // absolute URL in resource_metadata_url (type system guarantees it).
162
- // No derivation needed at the middleware level anymore.
163
- const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
164
-
165
191
  const token = extractBearerToken(ctx.request);
166
192
  if (!token) {
167
193
  if (isOtelEnabled()) {
@@ -48,8 +48,8 @@ export function createScopeMiddleware(
48
48
  const missingScopes = requiredScopes.filter((s) =>
49
49
  !authInfo.scopes.includes(s)
50
50
  );
51
- // resourceMetadataUrl is not critical for 403 responses (only used in 401),
52
- // but we populate it from context if available for consistency
51
+ // Used by 403 responses to advertise protected resource metadata in
52
+ // WWW-Authenticate; auth middleware populates it for HTTP requests.
53
53
  const metadataUrl = (ctx.resourceMetadataUrl as string | undefined) ?? "";
54
54
  throw new AuthError("insufficient_scope", metadataUrl, missingScopes);
55
55
  }
@@ -29,7 +29,7 @@ export interface ClientIdMetadataDocument {
29
29
  client_id: string;
30
30
  client_name: string;
31
31
  redirect_uris: string[];
32
- grant_types: ["authorization_code"];
32
+ grant_types: ["authorization_code", "refresh_token"];
33
33
  response_types: ["code"];
34
34
  token_endpoint_auth_method: "none";
35
35
  /** RFC 7591 application type. Always "native" for loopback CLI/desktop clients. */
@@ -120,7 +120,7 @@ export function buildClientIdMetadataDocument(
120
120
  client_id: clientRegistration.clientIdMetadataUrl,
121
121
  client_name: config.clientName!,
122
122
  redirect_uris: [clientRegistration.redirectUri],
123
- grant_types: ["authorization_code"],
123
+ grant_types: ["authorization_code", "refresh_token"],
124
124
  response_types: ["code"],
125
125
  token_endpoint_auth_method: "none",
126
126
  application_type: "native",
@@ -68,7 +68,7 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
68
68
  return {
69
69
  client_name: this.config.clientName ?? "PML Client",
70
70
  redirect_uris: [String(this.redirectUrl)],
71
- grant_types: ["authorization_code"],
71
+ grant_types: ["authorization_code", "refresh_token"],
72
72
  response_types: ["code"],
73
73
  token_endpoint_auth_method: "none", // public client, PKCE only
74
74
  application_type: "native", // loopback CLI/desktop — prevents AS rejection of http://127.0.0.1 redirects
@@ -101,9 +101,18 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
101
101
  }
102
102
 
103
103
  async saveTokens(tokens: OAuthTokens): Promise<void> {
104
+ // Sequential guard only: keep an existing refresh_token when a later save omits it.
105
+ // This get/set is not atomic; concurrent saves for one serverUrl are unsupported
106
+ // because refresh is serialized by the caller.
107
+ const stored = await this.config.tokenStore.get(this.serverUrl);
108
+ const tokensToStore = tokens.refresh_token === undefined &&
109
+ stored?.tokens.refresh_token !== undefined
110
+ ? { ...tokens, refresh_token: stored.tokens.refresh_token }
111
+ : tokens;
112
+
104
113
  await this.config.tokenStore.set(this.serverUrl, {
105
114
  serverUrl: this.serverUrl,
106
- tokens,
115
+ tokens: tokensToStore,
107
116
  obtainedAt: Date.now(),
108
117
  });
109
118
  }
package/src/mcp-app.ts CHANGED
@@ -15,6 +15,9 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
15
15
  import {
16
16
  type CallToolRequest,
17
17
  CallToolRequestSchema,
18
+ type ClientCapabilities,
19
+ ErrorCode,
20
+ type Implementation,
18
21
  ListResourcesRequestSchema,
19
22
  ListToolsRequestSchema,
20
23
  type ReadResourceRequest,
@@ -171,6 +174,13 @@ async function readBodyWithLimit(
171
174
  /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
172
175
  const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
173
176
 
177
+ /** Namespaced clientInfo key in params._meta (SEP-2575 stateless transport) */
178
+ const STATELESS_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo";
179
+
180
+ /** Namespaced clientCapabilities key in params._meta (SEP-2575 stateless transport) */
181
+ const STATELESS_CLIENT_CAPABILITIES_KEY =
182
+ "io.modelcontextprotocol/clientCapabilities";
183
+
174
184
  /** Protocol versions accepted by this server in stateless mode */
175
185
  const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
176
186
  "2026-07-28",
@@ -181,6 +191,14 @@ const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
181
191
  /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
182
192
  const STATELESS_FALLBACK_VERSION = "2025-06-18";
183
193
 
194
+ const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
195
+ const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32004;
196
+
197
+ interface StatelessClientMeta {
198
+ readonly clientInfo?: Implementation;
199
+ readonly clientCapabilities?: ClientCapabilities;
200
+ }
201
+
184
202
  /**
185
203
  * Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
186
204
  * Used to safely extract fields from JSON-RPC `params` without unsafe casts.
@@ -636,6 +654,10 @@ export class McpApp {
636
654
  ? { sessionId: ctx.sessionId }
637
655
  : {}),
638
656
  ...(ctx.authInfo ? { authInfo: ctx.authInfo as AuthInfo } : {}),
657
+ ...(ctx.clientInfo !== undefined ? { clientInfo: ctx.clientInfo } : {}),
658
+ ...(ctx.clientCapabilities !== undefined
659
+ ? { clientCapabilities: ctx.clientCapabilities }
660
+ : {}),
639
661
  }));
640
662
  });
641
663
  }
@@ -656,6 +678,7 @@ export class McpApp {
656
678
  request?: Request,
657
679
  sessionId?: string,
658
680
  preVerifiedAuthInfo?: AuthInfo,
681
+ clientMeta?: StatelessClientMeta,
659
682
  ): Promise<MiddlewareResult> {
660
683
  if (!this.middlewareRunner) {
661
684
  throw new Error(
@@ -672,6 +695,12 @@ export class McpApp {
672
695
  // middleware skips the redundant verifyToken call (avoids JWKS
673
696
  // race conditions on concurrent cold-cache requests).
674
697
  authInfo: preVerifiedAuthInfo,
698
+ ...(clientMeta?.clientInfo !== undefined
699
+ ? { clientInfo: clientMeta.clientInfo }
700
+ : {}),
701
+ ...(clientMeta?.clientCapabilities !== undefined
702
+ ? { clientCapabilities: clientMeta.clientCapabilities }
703
+ : {}),
675
704
  };
676
705
 
677
706
  // OTel span + metrics
@@ -1527,9 +1556,9 @@ export class McpApp {
1527
1556
  // Must run BEFORE any method dispatch so every call (not just initialize)
1528
1557
  // is validated. Sets MCP-Protocol-Version header on all subsequent responses
1529
1558
  // 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.
1559
+ // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
1560
+ // Tolerant mode: MCP-Protocol-Version may be absent for backward compatibility;
1561
+ // when present it must match the _meta version.
1533
1562
  let statelessVersion: string | undefined;
1534
1563
  if (this.options.transport === "stateless") {
1535
1564
  const clientVersion = isRecord(params) && isRecord(params["_meta"])
@@ -1543,7 +1572,7 @@ export class McpApp {
1543
1572
  jsonrpc: "2.0",
1544
1573
  id,
1545
1574
  error: {
1546
- code: -32020,
1575
+ code: JSONRPC_INVALID_PARAMS,
1547
1576
  message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1548
1577
  },
1549
1578
  },
@@ -1559,7 +1588,7 @@ export class McpApp {
1559
1588
  jsonrpc: "2.0",
1560
1589
  id,
1561
1590
  error: {
1562
- code: -32022,
1591
+ code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
1563
1592
  message: `Unsupported protocolVersion: "${clientVersion}"`,
1564
1593
  data: {
1565
1594
  supported: [...STATELESS_SUPPORTED_VERSIONS],
@@ -1572,12 +1601,56 @@ export class McpApp {
1572
1601
  );
1573
1602
  }
1574
1603
 
1604
+ const headerVersion = c.req.header("MCP-Protocol-Version");
1605
+ if (
1606
+ headerVersion !== undefined &&
1607
+ headerVersion !== clientVersion
1608
+ ) {
1609
+ return jsonRpcResponse(
1610
+ {
1611
+ jsonrpc: "2.0",
1612
+ id,
1613
+ error: {
1614
+ code: JSONRPC_INVALID_PARAMS,
1615
+ message:
1616
+ `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
1617
+ },
1618
+ },
1619
+ 400,
1620
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1621
+ );
1622
+ }
1623
+
1575
1624
  statelessVersion = clientVersion;
1576
1625
  // Spec 2026-07-28: echo negotiated version in every response header.
1577
1626
  // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1578
1627
  c.header("MCP-Protocol-Version", statelessVersion);
1579
1628
  }
1580
1629
 
1630
+ if (
1631
+ method === "server/discover" &&
1632
+ this.options.transport === "stateless"
1633
+ ) {
1634
+ return c.json({
1635
+ jsonrpc: "2.0",
1636
+ id,
1637
+ result: {
1638
+ supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1639
+ capabilities: {
1640
+ tools: {},
1641
+ resources: this.resources.size > 0 ? {} : undefined,
1642
+ },
1643
+ serverInfo: {
1644
+ name: this.options.name,
1645
+ version: this.options.version,
1646
+ },
1647
+ ...(this.options.instructions
1648
+ ? { instructions: this.options.instructions }
1649
+ : {}),
1650
+ },
1651
+ });
1652
+ }
1653
+
1581
1654
  // Initialize - create session and return session ID (now auth-verified)
1582
1655
  if (method === "initialize") {
1583
1656
  // Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
@@ -1683,6 +1756,20 @@ export class McpApp {
1683
1756
  if (method === "tools/call" && params?.name) {
1684
1757
  const toolName = params.name as string;
1685
1758
  const args = (params.arguments as Record<string, unknown>) || {};
1759
+ const statelessClientMeta:
1760
+ | StatelessClientMeta
1761
+ | undefined = this.options.transport === "stateless" &&
1762
+ isRecord(params) &&
1763
+ isRecord(params["_meta"])
1764
+ ? {
1765
+ clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
1766
+ | Implementation
1767
+ | undefined,
1768
+ clientCapabilities: params["_meta"][
1769
+ STATELESS_CLIENT_CAPABILITIES_KEY
1770
+ ] as ClientCapabilities | undefined,
1771
+ }
1772
+ : undefined;
1686
1773
 
1687
1774
  try {
1688
1775
  const result = await this.executeToolCall(
@@ -1691,6 +1778,7 @@ export class McpApp {
1691
1778
  c.req.raw,
1692
1779
  reqSessionId,
1693
1780
  httpAuthInfo,
1781
+ statelessClientMeta,
1694
1782
  );
1695
1783
  return c.json({
1696
1784
  jsonrpc: "2.0",
@@ -1710,7 +1798,10 @@ export class McpApp {
1710
1798
  );
1711
1799
  }
1712
1800
  if (error.code === "insufficient_scope") {
1713
- return createForbiddenResponse(error.requiredScopes ?? []);
1801
+ return createForbiddenResponse(
1802
+ error.requiredScopes ?? [],
1803
+ error.resourceMetadataUrl,
1804
+ );
1714
1805
  }
1715
1806
  }
1716
1807
 
@@ -1818,6 +1909,10 @@ export class McpApp {
1818
1909
  }
1819
1910
 
1820
1911
  // MCP protocol methods we don't implement — return empty results
1912
+ // ping: SEP-2575 removes ping in stateless mode, but we deliberately keep
1913
+ // answering it for backward compatibility. A SEP-conformant client won't send
1914
+ // it, and a stale client using ping for liveness keeps working. (Decision:
1915
+ // tolerant over strict, consistent with the rest of the stateless conformance work.)
1821
1916
  if (method === "ping") {
1822
1917
  return c.json({ jsonrpc: "2.0", id, result: {} });
1823
1918
  }
@@ -7,6 +7,11 @@
7
7
  * @module lib/server/middleware/types
8
8
  */
9
9
 
10
+ import type {
11
+ ClientCapabilities,
12
+ Implementation,
13
+ } from "@modelcontextprotocol/sdk/types.js";
14
+
10
15
  /**
11
16
  * Context passed through the middleware pipeline.
12
17
  * Each middleware can read and enrich the context.
@@ -24,6 +29,12 @@ export interface MiddlewareContext {
24
29
  /** Session ID (only present for HTTP transport) */
25
30
  sessionId?: string;
26
31
 
32
+ /** Client implementation metadata (stateless HTTP transport, when provided) */
33
+ clientInfo?: Implementation;
34
+
35
+ /** Client capabilities metadata (stateless HTTP transport, when provided) */
36
+ clientCapabilities?: ClientCapabilities;
37
+
27
38
  /** Extensible by middlewares (e.g., authInfo added by auth middleware) */
28
39
  [key: string]: unknown;
29
40
  }
package/src/types.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  */
9
9
 
10
10
  import type { McpUiToolMeta as McpUiToolMetaBase } from "@modelcontextprotocol/ext-apps";
11
+ import type {
12
+ ClientCapabilities,
13
+ Implementation,
14
+ } from "@modelcontextprotocol/sdk/types.js";
11
15
 
12
16
  /**
13
17
  * Rate limit configuration
@@ -467,6 +471,8 @@ export interface ToolHandlerContext {
467
471
  readonly request?: Request;
468
472
  readonly sessionId?: string;
469
473
  readonly authInfo?: import("./auth/types.js").AuthInfo;
474
+ readonly clientInfo?: Implementation;
475
+ readonly clientCapabilities?: ClientCapabilities;
470
476
  }
471
477
 
472
478
  export type ToolHandler = (