@casys/mcp-server 0.21.1 → 0.23.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/README.md CHANGED
@@ -248,13 +248,13 @@ When auth is configured, the framework automatically exposes
248
248
 
249
249
  ### DCR Discovery Proxy (RFC 8414 + RFC 7591)
250
250
 
251
- IdPs without native Dynamic Client Registration (Zitadel, unconfigured
252
- Keycloak, Okta free tier) don't publish `registration_endpoint` in their
253
- AS metadata, so MCP clients like Claude.ai or Cursor can't auto-register.
251
+ IdPs without native Dynamic Client Registration (Zitadel, unconfigured Keycloak,
252
+ Okta free tier) don't publish `registration_endpoint` in their AS metadata, so
253
+ MCP clients like Claude.ai or Cursor can't auto-register.
254
254
 
255
- `createAsMetadataHandler` is a framework-agnostic Web Standard handler
256
- that proxies the upstream RFC 8414 metadata and injects a
257
- `registration_endpoint` pointing to your own DCR proxy:
255
+ `createAsMetadataHandler` is a framework-agnostic Web Standard handler that
256
+ proxies the upstream RFC 8414 metadata and injects a `registration_endpoint`
257
+ pointing to your own DCR proxy:
258
258
 
259
259
  ```typescript
260
260
  // routes/.well-known/oauth-authorization-server.ts (Fresh example)
@@ -276,13 +276,12 @@ Then point the PRM at your own host so clients hit the enriched metadata:
276
276
  authorizationServers: ["https://my-app.example.com"],
277
277
  ```
278
278
 
279
- The DCR endpoint itself (RFC 7591 `/oauth/register`) is out of scope —
280
- mount it in your framework and forward to the IdP's admin API.
279
+ The DCR endpoint itself (RFC 7591 `/oauth/register`) is out of scope — mount it
280
+ in your framework and forward to the IdP's admin API.
281
281
 
282
- **Path caveat**: if the MCP server lives at `/mcp`, clients may build
283
- the discovery URL as
284
- `<host>/.well-known/oauth-authorization-server/mcp`. Mount the handler
285
- at the exact path your PRM advertises.
282
+ **Path caveat**: if the MCP server lives at `/mcp`, clients may build the
283
+ discovery URL as `<host>/.well-known/oauth-authorization-server/mcp`. Mount the
284
+ handler at the exact path your PRM advertises.
286
285
 
287
286
  ### Observability
288
287
 
package/mod.ts CHANGED
@@ -183,8 +183,16 @@ export {
183
183
  createAuthProviderFromConfig,
184
184
  loadAuthConfig,
185
185
  } from "./src/auth/mod.js";
186
+
186
187
  export type { AuthConfig, AuthProviderName } from "./src/auth/mod.js";
187
188
 
189
+ // Auth - Static Token Provider (opaque pre-shared bearer tokens)
190
+ export {
191
+ createStaticTokenAuthProvider,
192
+ StaticTokenAuthProvider,
193
+ } from "./src/auth/mod.js";
194
+ export type { StaticTokenAuthProviderOptions } from "./src/auth/mod.js";
195
+
188
196
  // Client Auth — OAuth client flow + CIMD
189
197
  export {
190
198
  buildClientIdMetadataDocument,
@@ -244,3 +252,49 @@ export type {
244
252
  // Inspector — launch the MCP Inspector for interactive debugging
245
253
  export { launchInspector } from "./src/inspector/launcher.js";
246
254
  export type { InspectorOptions } from "./src/inspector/launcher.js";
255
+
256
+ // ── Spec 2026-07-28 features ─────────────────────────────────────────────────
257
+
258
+ // Tasks extension (io.modelcontextprotocol/tasks, SEP-2663).
259
+ //
260
+ // `createTask` is what a tool handler returns to opt into async-task mode, so it
261
+ // has to be reachable from the package root — without it the extension is wired
262
+ // but unusable by any consumer.
263
+ export { createTask } from "./src/tasks/mod.js";
264
+ export type {
265
+ AsyncTaskDescriptor,
266
+ DetailedTask,
267
+ Task,
268
+ TaskController,
269
+ TaskStoreOptions,
270
+ } from "./src/tasks/mod.js";
271
+
272
+ // MRTR — Multi Round-Trip Requests (SEP-2322).
273
+ //
274
+ // `InputRequiredSignal` is the shape a handler returns to ask the client for
275
+ // input. The seal/verify primitives are exported for consumers implementing their
276
+ // own transport; the framework seals automatically on `tools/call`.
277
+ export type {
278
+ InputRequestEntry,
279
+ InputRequestMethod,
280
+ InputRequiredSignal,
281
+ MrtrOptions,
282
+ } from "./src/mrtr/mod.js";
283
+ export {
284
+ exportStateKey,
285
+ generateStateKey,
286
+ sealRequestState,
287
+ verifyRequestState,
288
+ } from "./src/mrtr/mod.js";
289
+
290
+ // subscriptions/listen (SEP-2575).
291
+ //
292
+ // The registry is owned by McpApp; these are exported for consumers driving their
293
+ // own streams, and for the filter type used when narrowing what a deployment
294
+ // delivers.
295
+ export { SubscriptionRegistry } from "./src/subscriptions/subscription-registry.js";
296
+ export type {
297
+ SubscriptionFilter,
298
+ SubscriptionRegistryOptions,
299
+ SubscriptionSink,
300
+ } from "./src/subscriptions/subscription-registry.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.21.1",
3
+ "version": "0.23.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,7 +12,31 @@ 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;
15
+ // ── Auth error codes ────────────────────────────────────────────────────────
16
+ //
17
+ // Both codes moved OUT of the JSON-RPC reserved range (`-32768`..`-32000`) for
18
+ // spec 2026-07-28, which is stricter than earlier readings of it suggested:
19
+ //
20
+ // * `-32002` — "Implementations of this protocol version **MUST NOT** emit
21
+ // these codes", because 2025-11-25 and earlier used it for resource-not-found
22
+ // (now `-32602`). Keeping it for 403 was a conformance violation, not a
23
+ // grandfathered liberty. Two prior reviews, including one of this file, read
24
+ // the allocation policy as permitting it. It does not.
25
+ // * `-32001` — inside `-32000`..`-32019`, where "new implementations
26
+ // **SHOULD NOT** use codes from this sub-range at all" and receivers "**MUST
27
+ // NOT** assume any specific meaning".
28
+ //
29
+ // The spec's own guidance for codes it does not define: "**SHOULD** be allocated
30
+ // outside the JSON-RPC reserved range". Hence `-31401` / `-31403`, mnemonic for
31
+ // the HTTP statuses they accompany.
32
+ //
33
+ // BREAKING for anything matching on the old numbers — see the changelog.
34
+
35
+ /** 401 Unauthorized: no token, or an invalid one. */
36
+ export const JSONRPC_UNAUTHORIZED = -31401;
37
+
38
+ /** 403 Forbidden: authenticated, but missing a required scope. */
39
+ export const JSONRPC_FORBIDDEN = -31403;
16
40
 
17
41
  function escapeAuthenticateParam(s: string): string {
18
42
  return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
@@ -68,7 +92,9 @@ export function createUnauthorizedResponse(
68
92
  errorDescription?: string,
69
93
  ): Response {
70
94
  const parts = [
71
- `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
95
+ `Bearer resource_metadata="${
96
+ escapeAuthenticateParam(resourceMetadataUrl)
97
+ }"`,
72
98
  ];
73
99
  if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
74
100
  if (errorDescription) {
@@ -81,7 +107,10 @@ export function createUnauthorizedResponse(
81
107
  JSON.stringify({
82
108
  jsonrpc: "2.0",
83
109
  id: null,
84
- error: { code: -32001, message: errorDescription ?? "Unauthorized" },
110
+ error: {
111
+ code: JSONRPC_UNAUTHORIZED,
112
+ message: errorDescription ?? "Unauthorized",
113
+ },
85
114
  }),
86
115
  {
87
116
  status: 401,
@@ -105,11 +134,11 @@ export function createForbiddenResponse(
105
134
  ): Response {
106
135
  const requiredScopesDescription = requiredScopes.join(", ");
107
136
  const parts = [
108
- `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
109
- `error="insufficient_scope"`,
110
- `error_description="${
111
- escapeAuthenticateParam(requiredScopesDescription)
137
+ `Bearer resource_metadata="${
138
+ escapeAuthenticateParam(resourceMetadataUrl)
112
139
  }"`,
140
+ `error="insufficient_scope"`,
141
+ `error_description="${escapeAuthenticateParam(requiredScopesDescription)}"`,
113
142
  ];
114
143
 
115
144
  return new Response(
package/src/auth/mod.ts CHANGED
@@ -80,3 +80,10 @@ export type {
80
80
  GoogleAuthConfig,
81
81
  OIDCAuthConfig,
82
82
  } from "./config.js";
83
+
84
+ // Static Token Provider (opaque pre-shared bearer tokens; no OIDC/JWT infra)
85
+ export {
86
+ createStaticTokenAuthProvider,
87
+ StaticTokenAuthProvider,
88
+ } from "./static-token-provider.js";
89
+ export type { StaticTokenAuthProviderOptions } from "./static-token-provider.js";
@@ -0,0 +1,197 @@
1
+ // deno-lint-ignore-file require-await
2
+ /**
3
+ * Static (opaque) bearer-token auth provider.
4
+ *
5
+ * Validates a fixed set of pre-shared bearer tokens with no OIDC/JWT
6
+ * infrastructure — no issuer, no JWKS endpoint, no key management. Suited to
7
+ * same-network deployments (Docker, VPN, LAN), server-to-server integrations,
8
+ * and CI pipelines where a full OAuth flow is disproportionate.
9
+ *
10
+ * All valid tokens map to the same {@link AuthInfo}: this is authentication
11
+ * ("is this an allowed caller?"), not per-user identity. For per-user identity,
12
+ * expiry, or scopes issued by an IdP, use {@link JwtAuthProvider} / the OIDC
13
+ * presets instead.
14
+ *
15
+ * Per RFC 9728 the emitted {@link ProtectedResourceMetadata} carries an empty
16
+ * `authorization_servers` array: there is no authorization server in a static
17
+ * token scheme — tokens are provisioned out of band — which is the correct
18
+ * signal for clients not to attempt AS discovery.
19
+ *
20
+ * @module lib/server/auth/static-token-provider
21
+ */
22
+
23
+ import { AuthProvider } from "./provider.js";
24
+ import {
25
+ type AuthInfo,
26
+ type HttpsUrl,
27
+ httpsUrl,
28
+ type ProtectedResourceMetadata,
29
+ } from "./types.js";
30
+
31
+ /**
32
+ * Options for {@link createStaticTokenAuthProvider} /
33
+ * {@link StaticTokenAuthProvider}.
34
+ */
35
+ export interface StaticTokenAuthProviderOptions {
36
+ /**
37
+ * RFC 9728 § 2 resource identifier — an absolute HTTP(S) URL identifying
38
+ * this server, validated via {@link httpsUrl} at construction. Required: the
39
+ * {@link AuthProvider} contract must emit Protected Resource Metadata, which
40
+ * needs a resource URL.
41
+ */
42
+ resource: string;
43
+ /**
44
+ * `subject` reported in {@link AuthInfo} for every valid token.
45
+ * Default `"static-token-user"`.
46
+ */
47
+ subject?: string;
48
+ /**
49
+ * `scopes` granted to every valid token. Default `[]` — a pure gate with no
50
+ * scopes, which is the common same-network case.
51
+ */
52
+ scopes?: string[];
53
+ /**
54
+ * `scopes_supported` advertised in the metadata document (what the resource
55
+ * accepts). Defaults to `scopes` when omitted.
56
+ */
57
+ scopesSupported?: string[];
58
+ /**
59
+ * Explicit Protected Resource Metadata URL. When omitted it is auto-derived
60
+ * from `resource` per RFC 9728 § 3.1, identically to {@link JwtAuthProvider}.
61
+ * Empty / whitespace-only values are treated as absent.
62
+ */
63
+ resourceMetadataUrl?: string;
64
+ }
65
+
66
+ /**
67
+ * {@link AuthProvider} that accepts a fixed set of opaque bearer tokens.
68
+ *
69
+ * Token lookup is O(1) via a pre-built `Set`; the shared {@link AuthInfo} (and
70
+ * its `scopes` array) is frozen at construction. Tokens are stored trimmed to
71
+ * match the bearer value the HTTP middleware extracts. Note that `Set.has()` is
72
+ * not constant-time — prefer long, high-entropy tokens (>= 32 random bytes) and
73
+ * rotate them regularly.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const provider = new StaticTokenAuthProvider(
78
+ * [Deno.env.get("MCP_AUTH_TOKEN")!],
79
+ * { resource: "https://my-mcp.example.com", scopes: ["tools:invoke"] },
80
+ * );
81
+ * ```
82
+ */
83
+ export class StaticTokenAuthProvider extends AuthProvider {
84
+ private readonly tokens: Set<string>;
85
+ private readonly authInfo: AuthInfo;
86
+ private readonly resource: string;
87
+ private readonly resourceMetadataUrl: HttpsUrl;
88
+ private readonly scopesSupported: string[] | undefined;
89
+
90
+ constructor(tokens: string[], options: StaticTokenAuthProviderOptions) {
91
+ super();
92
+
93
+ if (tokens.length === 0) {
94
+ throw new Error(
95
+ "[StaticTokenAuthProvider] `tokens` must contain at least one token",
96
+ );
97
+ }
98
+ if (tokens.some((t) => t.trim().length === 0)) {
99
+ throw new Error(
100
+ "[StaticTokenAuthProvider] `tokens` must not contain empty entries",
101
+ );
102
+ }
103
+ if (!options.resource?.trim()) {
104
+ throw new Error("[StaticTokenAuthProvider] `resource` is required");
105
+ }
106
+
107
+ // Validate `resource` as an absolute HTTP(S) URL unconditionally, so the
108
+ // documented guarantee holds even when `resourceMetadataUrl` is supplied.
109
+ const resourceUrl = httpsUrl(options.resource);
110
+
111
+ // Store tokens trimmed: the HTTP middleware trims the extracted bearer
112
+ // value (`extractBearerToken`), so a padded entry would otherwise be stored
113
+ // in a form that can never match an incoming request.
114
+ this.tokens = new Set(tokens.map((t) => t.trim()));
115
+
116
+ // Clone + freeze the scopes array: verifyToken returns this same AuthInfo
117
+ // reference for every valid token, so a shared mutable array would let one
118
+ // caller escalate scopes for all callers.
119
+ const scopes = Object.freeze([...(options.scopes ?? [])]) as string[];
120
+ this.authInfo = Object.freeze({
121
+ subject: options.subject ?? "static-token-user",
122
+ scopes,
123
+ }) as AuthInfo;
124
+
125
+ // Store the caller's raw resource string (RFC 9728 allows opaque URIs, and
126
+ // JwtAuthProvider does the same); `resourceUrl` above is used only for
127
+ // validation and metadata-URL derivation.
128
+ this.resource = options.resource;
129
+ this.scopesSupported = options.scopesSupported
130
+ ? (Object.freeze([...options.scopesSupported]) as string[])
131
+ : (scopes.length > 0 ? scopes : undefined);
132
+
133
+ // RFC 9728 § 3.1: when `resourceMetadataUrl` is omitted, insert the
134
+ // well-known suffix between the resource's origin and its path/query
135
+ // (identical derivation to JwtAuthProvider).
136
+ if (options.resourceMetadataUrl?.trim()) {
137
+ this.resourceMetadataUrl = httpsUrl(options.resourceMetadataUrl);
138
+ } else {
139
+ const parsed = new URL(resourceUrl);
140
+ const pathPart = parsed.pathname === "/" ? "" : parsed.pathname;
141
+ this.resourceMetadataUrl = httpsUrl(
142
+ `${parsed.origin}/.well-known/oauth-protected-resource${pathPart}${parsed.search}`,
143
+ );
144
+ }
145
+ }
146
+
147
+ async verifyToken(token: string): Promise<AuthInfo | null> {
148
+ // Trim to match how tokens are stored (and how the HTTP middleware extracts
149
+ // the bearer), so direct callers and the middleware path behave identically.
150
+ return this.tokens.has(token.trim()) ? this.authInfo : null;
151
+ }
152
+
153
+ getResourceMetadata(): ProtectedResourceMetadata {
154
+ // Fresh object per call (matching JwtAuthProvider) so a caller cannot
155
+ // mutate shared metadata — e.g. the `authorization_servers` array.
156
+ return {
157
+ resource: this.resource,
158
+ resource_metadata_url: this.resourceMetadataUrl,
159
+ // No authorization server: static tokens are provisioned out of band.
160
+ authorization_servers: [],
161
+ scopes_supported: this.scopesSupported,
162
+ bearer_methods_supported: ["header"],
163
+ };
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Create a static (opaque) bearer-token {@link AuthProvider}.
169
+ *
170
+ * @param tokens Non-empty list of valid bearer tokens (deduplicated, stored
171
+ * trimmed). Load them from env / a secrets manager — never hard-code tokens
172
+ * in source.
173
+ * @param options Provider configuration; `options.resource` is required.
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * import { createStaticTokenAuthProvider, McpApp } from "@casys/mcp-server";
178
+ *
179
+ * const app = new McpApp({
180
+ * name: "my-server",
181
+ * version: "1.0.0",
182
+ * auth: {
183
+ * provider: createStaticTokenAuthProvider(
184
+ * (Deno.env.get("MCP_AUTH_TOKENS") ?? "").split(",").filter(Boolean),
185
+ * { resource: "https://my-mcp.example.com" },
186
+ * ),
187
+ * },
188
+ * });
189
+ * await app.startHttp({ port: 7654, requireAuth: true });
190
+ * ```
191
+ */
192
+ export function createStaticTokenAuthProvider(
193
+ tokens: string[],
194
+ options: StaticTokenAuthProviderOptions,
195
+ ): StaticTokenAuthProvider {
196
+ return new StaticTokenAuthProvider(tokens, options);
197
+ }
@@ -9,19 +9,24 @@ import type { StoredCredentials, TokenStore } from "../types.js";
9
9
  export class MemoryTokenStore implements TokenStore {
10
10
  private store = new Map<string, StoredCredentials>();
11
11
 
12
- async get(serverUrl: string): Promise<StoredCredentials | null> {
13
- return this.store.get(serverUrl) ?? null;
12
+ // Not `async`: the Map operations are synchronous. The interface returns
13
+ // Promises so a real store can be I/O-backed; `Promise.resolve` satisfies it
14
+ // without claiming an await point that does not exist.
15
+ get(serverUrl: string): Promise<StoredCredentials | null> {
16
+ return Promise.resolve(this.store.get(serverUrl) ?? null);
14
17
  }
15
18
 
16
- async set(serverUrl: string, credentials: StoredCredentials): Promise<void> {
19
+ set(serverUrl: string, credentials: StoredCredentials): Promise<void> {
17
20
  this.store.set(serverUrl, credentials);
21
+ return Promise.resolve();
18
22
  }
19
23
 
20
- async delete(serverUrl: string): Promise<void> {
24
+ delete(serverUrl: string): Promise<void> {
21
25
  this.store.delete(serverUrl);
26
+ return Promise.resolve();
22
27
  }
23
28
 
24
- async list(): Promise<string[]> {
25
- return [...this.store.keys()];
29
+ list(): Promise<string[]> {
30
+ return Promise.resolve([...this.store.keys()]);
26
31
  }
27
32
  }