@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
package/src/mcp-app.ts DELETED
@@ -1,4595 +0,0 @@
1
- /**
2
- * McpApp — Hono-style framework for MCP servers
3
- *
4
- * High-performance MCP server with built-in concurrency control
5
- * and backpressure.
6
- *
7
- * Wraps the official MCP server packages with middleware, auth, and
8
- * observability features.
9
- *
10
- * @module lib/server/mcp-app
11
- */
12
-
13
- import {
14
- type CallToolRequest,
15
- type CallToolResult,
16
- type ClientCapabilities,
17
- type Implementation,
18
- type InputRequiredResult,
19
- type ListResourcesResult,
20
- type ListToolsResult,
21
- ProtocolError,
22
- ProtocolErrorCode,
23
- type ReadResourceRequest,
24
- Server,
25
- type ServerCapabilities,
26
- type ServerContext,
27
- } from "@modelcontextprotocol/server";
28
- import {
29
- serveStdio,
30
- type StdioServerHandle,
31
- } from "@modelcontextprotocol/server/stdio";
32
- import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
33
- import { Hono } from "hono";
34
- import { cors } from "hono/cors";
35
- import { RequestQueue } from "./concurrency/request-queue.js";
36
- import { RateLimiter } from "./concurrency/rate-limiter.js";
37
- import { SchemaValidator } from "./validation/schema-validator.js";
38
- import { createMiddlewareRunner } from "./middleware/runner.js";
39
- import { createRateLimitMiddleware } from "./middleware/rate-limit.js";
40
- import { createValidationMiddleware } from "./middleware/validation.js";
41
- import { createBackpressureMiddleware } from "./middleware/backpressure.js";
42
- import type {
43
- McpLogLevel,
44
- Middleware,
45
- MiddlewareContext,
46
- MiddlewareResult,
47
- } from "./middleware/types.js";
48
- import { serve, type ServeHandle, unrefTimer } from "./runtime/runtime.js";
49
- import {
50
- AuthError,
51
- createAuthMiddleware,
52
- createForbiddenResponse,
53
- createUnauthorizedResponse,
54
- extractBearerToken,
55
- freezeAuthInfo,
56
- } from "./auth/middleware.js";
57
- import { createScopeMiddleware } from "./auth/scope-middleware.js";
58
- import { createAuthProviderFromConfig, loadAuthConfig } from "./auth/config.js";
59
- import type { AuthProvider } from "./auth/provider.js";
60
- import type { AuthInfo } from "./auth/types.js";
61
- import type {
62
- FetchHandler,
63
- HttpRateLimitContext,
64
- HttpServerOptions,
65
- McpAppOptions,
66
- McpAppsClientCapability,
67
- MCPResource,
68
- MCPTool,
69
- QueueMetrics,
70
- ResourceContent,
71
- ResourceHandler,
72
- StructuredToolResult,
73
- ToolHandler,
74
- } from "./types.js";
75
- import { getMcpAppsCapability, MCP_APP_MIME_TYPE } from "./types.js";
76
- import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
77
- import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
78
- import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
79
- import {
80
- collectMirroredParams,
81
- type MirroredParam,
82
- validateRequestHeaders,
83
- } from "./transport/request-headers.js";
84
- import {
85
- type DetailedTask,
86
- isAsyncTaskDescriptor,
87
- TaskStore,
88
- } from "./tasks/mod.js";
89
- import {
90
- checkInputRequestCapabilities,
91
- guardMrtrRetry,
92
- importStateKey,
93
- type InputRequestEntry,
94
- type InputRequiredSignal,
95
- MemoryMrtrReplayStore,
96
- type MrtrReplayStore,
97
- paramsDigest,
98
- sealRequestState,
99
- } from "./mrtr/mod.js";
100
- import {
101
- buildAcknowledgedMessage,
102
- encodeSSEEvent,
103
- type SubscriptionFilter,
104
- SubscriptionRegistry,
105
- type SubscriptionSink,
106
- } from "./subscriptions/subscription-registry.js";
107
- import { ServerMetrics } from "./observability/metrics.js";
108
- import type { SpanContext } from "@opentelemetry/api";
109
- import {
110
- endToolCallSpan,
111
- parseTraceParent,
112
- startToolCallSpan,
113
- } from "./observability/otel.js";
114
- import {
115
- BodyTooLargeError,
116
- DEFAULT_MAX_BODY_BYTES,
117
- getClientIpFromHeaders,
118
- readBodyWithLimit,
119
- } from "./http/body.js";
120
- import {
121
- bytesToHexLocal,
122
- callerPrincipal,
123
- noOwnerKeyError,
124
- noPrincipalError,
125
- taskOwnerKeyFor,
126
- } from "./http/request-guards.js";
127
- import {
128
- isRecord,
129
- jsonRpcResponse,
130
- MRTR_NO_AUTH_PRINCIPAL,
131
- } from "./http/wire.js";
132
-
133
- /**
134
- * Tool definition with handler
135
- */
136
- interface ToolWithHandler extends MCPTool {
137
- handler: ToolHandler;
138
- }
139
-
140
- /**
141
- * Internal tracking of registered resources
142
- */
143
- interface RegisteredResourceInfo {
144
- resource: MCPResource;
145
- handler: ResourceHandler;
146
- }
147
-
148
- // ── Track A (spec 2026-07-28) — Stateless transport constants ───────────────
149
-
150
- /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
151
- const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
152
-
153
- /** Namespaced clientInfo key in params._meta (SEP-2575 stateless transport) */
154
- const STATELESS_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo";
155
-
156
- /** Namespaced clientCapabilities key in params._meta (SEP-2575 stateless transport) */
157
- const STATELESS_CLIENT_CAPABILITIES_KEY =
158
- "io.modelcontextprotocol/clientCapabilities";
159
-
160
- /** Protocol versions accepted by this server in stateless mode */
161
- const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
162
- "2026-07-28",
163
- ];
164
-
165
- /** Namespaced serverInfo key in a result's _meta (spec 2026-07-28, SHOULD) */
166
- const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
167
-
168
- /**
169
- * Namespaced per-request log level in params._meta (spec 2026-07-28).
170
- * Replaces the removed `logging/setLevel` RPC: the level is now scoped to the
171
- * request that asked for it, so there is no server-side level to mutate.
172
- */
173
- const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
174
-
175
- /**
176
- * W3C trace context keys in `params._meta` (spec 2026-07-28, SEP-414).
177
- *
178
- * Unlike every other per-request field these are NOT namespaced — the revision
179
- * documents the bare W3C names, so that a `_meta` envelope carries the same
180
- * key a caller would put in an HTTP header.
181
- */
182
- const TRACEPARENT_KEY = "traceparent";
183
- const TRACESTATE_KEY = "tracestate";
184
-
185
- /** Protocol version whose wire format this server implements natively */
186
- const SPEC_2026_07_28 = "2026-07-28";
187
-
188
- /**
189
- * Tasks extension identifier (SEP-2663).
190
- *
191
- * Declaring it in `McpAppOptions.extensions` is what switches the extension on.
192
- * The spec forbids returning a task handle to a client that did not declare
193
- * support, and forbids advertising an extension we do not implement — so the
194
- * declaration gates both directions.
195
- */
196
- const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
197
-
198
- /** Version echoed in MCP-Protocol-Version header on error responses (server's only accepted version) */
199
- const STATELESS_FALLBACK_VERSION = "2026-07-28";
200
-
201
- const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
202
-
203
- // ── Error codes (spec 2026-07-28, allocation policy) ────────────────────────
204
- //
205
- // The final spec partitions the JSON-RPC server-error range:
206
- // -32000..-32019 implementation-defined (existing SDK usage grandfathered)
207
- // -32020..-32099 reserved for the MCP specification
208
- //
209
- // The codes below were renumbered between the May 2026 Release Candidate — which
210
- // 0.21.0 shipped against — and the final revision. Do not "restore" the RC
211
- // values: -32001 and -32004 no longer carry these MCP-defined meanings.
212
- //
213
- // Note the policy is stricter than "the low range is grandfathered": the spec
214
- // says new implementations SHOULD NOT use -32000..-32019 at all, and MUST NOT
215
- // emit -32002 (which 2025-11-25 used for resource-not-found). Our auth and
216
- // session errors therefore live outside the reserved range entirely — see
217
- // auth/middleware.ts.
218
-
219
- /** Headers disagree with the request body, or a required header is missing. */
220
- const MCP_HEADER_MISMATCH = -32020;
221
-
222
- /**
223
- * Client did not declare a capability the request requires.
224
- *
225
- * Emitted by the Tasks extension guard. `data.requiredCapabilities` must list
226
- * the missing capabilities alongside it.
227
- */
228
- const MCP_MISSING_REQUIRED_CLIENT_CAPABILITY = -32021;
229
-
230
- /** Requested protocol version is not one this server implements. */
231
- const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32022;
232
-
233
- interface StatelessClientMeta {
234
- readonly clientInfo?: Implementation;
235
- readonly clientCapabilities?: ClientCapabilities;
236
- readonly logLevel?: McpLogLevel;
237
- /** Caller's W3C trace context, so the tool span joins their trace. */
238
- readonly traceContext?: SpanContext;
239
- }
240
-
241
- /**
242
- * Read the W3C trace context out of `params._meta` (spec 2026-07-28, SEP-414).
243
- *
244
- * A malformed header leaves the span unparented rather than failing the call:
245
- * losing the trace join is an observability gap, refusing the tool call would
246
- * be an outage.
247
- *
248
- * `baggage` is deliberately NOT read. It is an unbounded, caller-controlled
249
- * key/value list that routinely carries tenant, user and session identifiers,
250
- * and the only thing this server could do with it is copy it into spans —
251
- * exporting whatever a caller put there to the trace backend, with no way to
252
- * know whether it holds a PII or a secret. Propagating it properly means the
253
- * OTel baggage API and an explicit allowlist of keys; until there is a use case
254
- * asking for that, reading it at all is a liability. The key stays reserved by
255
- * the spec, and this server ignores it.
256
- */
257
- function readTraceContext(
258
- meta: Record<string, unknown>,
259
- ): { traceContext?: SpanContext } {
260
- const traceContext = parseTraceParent(
261
- meta[TRACEPARENT_KEY],
262
- meta[TRACESTATE_KEY],
263
- );
264
- return traceContext ? { traceContext } : {};
265
- }
266
-
267
- /** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
268
- const MCP_LOG_LEVELS: readonly McpLogLevel[] = [
269
- "debug",
270
- "info",
271
- "notice",
272
- "warning",
273
- "error",
274
- "critical",
275
- "alert",
276
- "emergency",
277
- ];
278
-
279
- /**
280
- * Read the per-request log level out of `params._meta`.
281
- *
282
- * An unrecognized value is dropped rather than rejected: the level is an
283
- * optional hint, and failing a whole tool call because a client sent
284
- * `"verbose"` would be a worse outcome than emitting nothing.
285
- */
286
- function readLogLevel(meta: Record<string, unknown>): McpLogLevel | undefined {
287
- const raw = meta[STATELESS_LOG_LEVEL_KEY];
288
- return typeof raw === "string" && MCP_LOG_LEVELS.includes(raw as McpLogLevel)
289
- ? raw as McpLogLevel
290
- : undefined;
291
- }
292
-
293
- /**
294
- * Validate the client-owned subscriptions/listen filter before it reaches the
295
- * registry. The registry deliberately works with a typed SubscriptionFilter;
296
- * casting untrusted JSON into it made truthy values subscribe to list changes
297
- * and let invalid URI entries reach the SSE acknowledgement.
298
- */
299
- function validateSubscriptionFilter(
300
- filter: Record<string, unknown>,
301
- ):
302
- | { ok: true; filter: SubscriptionFilter }
303
- | {
304
- ok: false;
305
- message: string;
306
- bodyField: string;
307
- recovery: string;
308
- } {
309
- for (
310
- const field of [
311
- "toolsListChanged",
312
- "promptsListChanged",
313
- "resourcesListChanged",
314
- ] as const
315
- ) {
316
- if (filter[field] !== undefined && typeof filter[field] !== "boolean") {
317
- return {
318
- ok: false,
319
- message: `${field} must be a boolean when present`,
320
- bodyField: `params.notifications.${field}`,
321
- recovery:
322
- `Send ${field} as true or false, or omit it when that notification type is not requested.`,
323
- };
324
- }
325
- }
326
-
327
- for (const field of ["resourceSubscriptions", "taskIds"] as const) {
328
- const value = filter[field];
329
- if (value === undefined) continue;
330
- if (!Array.isArray(value)) {
331
- return {
332
- ok: false,
333
- message: `${field} must be an array of strings when present`,
334
- bodyField: `params.notifications.${field}`,
335
- recovery:
336
- `Send ${field} as an array of strings, or omit it when no identifiers are requested.`,
337
- };
338
- }
339
- const malformedIndex = value.findIndex((entry) =>
340
- typeof entry !== "string"
341
- );
342
- if (malformedIndex !== -1) {
343
- return {
344
- ok: false,
345
- message: `${field} entries must be strings`,
346
- bodyField: `params.notifications.${field}[${malformedIndex}]`,
347
- recovery:
348
- `Send only string entries in ${field}; remove or replace the malformed entry.`,
349
- };
350
- }
351
- }
352
-
353
- return { ok: true, filter: filter as SubscriptionFilter };
354
- }
355
-
356
- /**
357
- * Stamp a result with the spec-2026-07-28 envelope: the required `resultType`
358
- * (SEP-2322) and the server's identity under `_meta` (SEP-2575, SHOULD).
359
- *
360
- * `_meta` is merged, never replaced — tool results carry their own `_meta` (MCP
361
- * Apps UI hints, for instance) and losing it would break the viewers.
362
- *
363
- * Pure by design so the envelope can be asserted directly in tests without
364
- * standing up a server; the caller decides whether the envelope applies.
365
- */
366
- function completeResult(
367
- result: Record<string, unknown>,
368
- serverInfo: Implementation,
369
- ): Record<string, unknown> {
370
- const existingMeta = isRecord(result["_meta"]) ? result["_meta"] : undefined;
371
- return {
372
- ...result,
373
- resultType: "complete",
374
- _meta: { ...existingMeta, [STATELESS_SERVER_INFO_KEY]: serverInfo },
375
- };
376
- }
377
-
378
- /**
379
- * Reduce a handler-built result to the exact JSON object that will cross the
380
- * transport boundary. Preformatted proxy results bypass the normal text
381
- * serialisation path, so without this gate a BigInt or cycle could be stored as
382
- * a completed task and only explode on a later tasks/get response.
383
- */
384
- function canonicaliseWireResult(
385
- result: Record<string, unknown>,
386
- ): Record<string, unknown> {
387
- const serialised = JSON.stringify(result);
388
- if (serialised === undefined) {
389
- throw new Error("Tool result is not JSON-serialisable");
390
- }
391
- const canonical = JSON.parse(serialised);
392
- if (!isRecord(canonical)) {
393
- throw new Error("Tool result must serialise to an object");
394
- }
395
- return canonical;
396
- }
397
-
398
- // ─────────────────────────────────────────────────────────────────────────────
399
-
400
- /**
401
- * McpApp provides a high-performance MCP server
402
- *
403
- * Features:
404
- * - Wraps official @modelcontextprotocol/sdk
405
- * - Concurrency limiting (default: 10 max concurrent)
406
- * - Multiple backpressure strategies (sleep/queue/reject)
407
- * - Metrics for monitoring
408
- * - Graceful shutdown
409
- *
410
- * @example
411
- * ```typescript
412
- * const server = new McpApp({
413
- * name: "my-server",
414
- * version: "1.0.0",
415
- * maxConcurrent: 5,
416
- * backpressureStrategy: 'queue'
417
- * });
418
- *
419
- * server.registerTools(myTools, myHandlers);
420
- * await server.start();
421
- * ```
422
- */
423
- export class McpApp {
424
- /**
425
- * Server name — the identifier reported to MCP clients in `InitializeResult.serverInfo.name`.
426
- *
427
- * Exposed as a public readonly field (0.16.1) so consumers can use it for
428
- * log prefixes, tracing context, or any UI that wants to echo the server
429
- * identity without having to thread `options.name` through their code.
430
- * Immutable after construction, same value that appears in the MCP
431
- * `initialize` response.
432
- */
433
- public readonly name: string;
434
- private requestQueue: RequestQueue;
435
- private rateLimiter: RateLimiter | null = null;
436
- private schemaValidator: SchemaValidator | null = null;
437
- private tools = new Map<string, ToolWithHandler>();
438
-
439
- /**
440
- * Tool name → parameters the tool asked clients to mirror into
441
- * `Mcp-Param-{Name}` headers (spec 2026-07-28, `x-mcp-header`).
442
- *
443
- * Populated at registration so the per-request path is a map lookup rather
444
- * than a schema walk. Tools without annotations are simply absent.
445
- */
446
- private mirroredParams = new Map<string, MirroredParam[]>();
447
-
448
- /**
449
- * Task store for the Tasks extension, or `null` when the consumer did not
450
- * declare it.
451
- *
452
- * Created only on declaration: a server not using Tasks should not pay for a
453
- * sweep timer, and a `tasks/*` call against it must read as the unimplemented
454
- * method it is (404 + -32601) rather than hitting an empty store.
455
- */
456
- private taskStore: TaskStore | null;
457
-
458
- /**
459
- * Set synchronously at the top of `stop()`.
460
- *
461
- * Checked before spawning a task, because the pipeline is async: a handler that
462
- * settles during shutdown would otherwise start work in a store already drained,
463
- * producing a task that outlives its server. A synchronous flag is what makes
464
- * the check reliable — anything awaited leaves the same window open.
465
- */
466
- private stopping = false;
467
-
468
- /**
469
- * Live `subscriptions/listen` streams.
470
- *
471
- * Initialized unconditionally in startHttp(); null before the server starts
472
- * or in stdio mode.
473
- */
474
- private subscriptions: SubscriptionRegistry | null = null;
475
-
476
- /** Era-aware stdio serving handle, present only while start() is active. */
477
- private stdioHandle: StdioServerHandle | null = null;
478
-
479
- /** Protocol instance pinned by the stdio era negotiator, when connected. */
480
- private activeStdioServer: Server | null = null;
481
-
482
- /**
483
- * Imported HMAC key for sealing `requestState`, or `null` when the deployment
484
- * configured none.
485
- *
486
- * Resolved lazily on first use rather than in the constructor, because
487
- * `importStateKey` is async and a constructor cannot await.
488
- */
489
- /**
490
- * In-flight or resolved key import.
491
- *
492
- * A Promise, not a value plus a loaded flag: the flag was set before the await,
493
- * so a second request arriving during the import saw "loaded" with the key
494
- * still null, received an UNSIGNED requestState, and could then submit raw
495
- * inputResponses past the verification guard. Memoising the Promise makes every
496
- * caller await the same import.
497
- */
498
- private mrtrKeyPromise: Promise<CryptoKey | null> | null = null;
499
-
500
- /**
501
- * Consumes a verified requestState nonce before the handler runs.
502
- *
503
- * A signed deployment always has a store: process-local by default, or the
504
- * shared atomic implementation supplied by the consumer.
505
- */
506
- private readonly mrtrReplayStore: MrtrReplayStore | null;
507
-
508
- /**
509
- * Validated `ttlMs`. The spec requires servers to provide a value `>= 0`, and
510
- * an integer — clients are told to ignore a negative one, which would make a
511
- * misconfiguration silently do nothing instead of failing.
512
- *
513
- * Resolved once at construction: a per-response check would pay for the same
514
- * validation on every list call, and a bad value is a deployment error that
515
- * should surface at startup (AX: fast fail early).
516
- */
517
- private readonly cacheTtlMs: number;
518
- private resources = new Map<string, RegisteredResourceInfo>();
519
- private options: McpAppOptions;
520
- private started = false;
521
- private resourceHandlersInstalled = false;
522
-
523
- // Middleware pipeline
524
- private customMiddlewares: Middleware[] = [];
525
- private middlewareRunner:
526
- | ((ctx: MiddlewareContext) => Promise<MiddlewareResult>)
527
- | null = null;
528
-
529
- // Auth provider (set from options.auth or auto-configured from env)
530
- private authProvider: AuthProvider | null = null;
531
-
532
- // Observability
533
- private serverMetrics = new ServerMetrics();
534
-
535
- constructor(options: McpAppOptions) {
536
- this.options = options;
537
- this.name = options.name;
538
-
539
- // enableSampling / samplingClient are no-ops since 0.24.0 (SamplingBridge
540
- // was removed with MCP 2026-07-28). Warn loudly so migrating consumers
541
- // know immediately rather than discovering it silently in production.
542
- if (options.enableSampling || options.samplingClient) {
543
- (options.logger ?? console.error)(
544
- "[McpApp] WARNING: enableSampling and samplingClient have no effect " +
545
- "as of 0.24.0 — the SamplingBridge was removed with MCP 2026-07-28. " +
546
- "Remove these options from your McpApp constructor call.",
547
- );
548
- }
549
-
550
- const ttlMs = options.cache?.ttlMs ?? 0;
551
- if (!Number.isInteger(ttlMs) || ttlMs < 0) {
552
- throw new Error(
553
- `[McpApp] cache.ttlMs must be a non-negative integer (got ${ttlMs}). ` +
554
- "The spec requires servers to provide ttlMs >= 0, and clients are told " +
555
- "to ignore a negative value — so a bad one would silently disable " +
556
- "caching instead of failing.",
557
- );
558
- }
559
- this.cacheTtlMs = ttlMs;
560
-
561
- this.taskStore = options.extensions?.[TASKS_EXTENSION_ID] !== undefined
562
- ? new TaskStore({
563
- onNotification: (task) => this.onTaskChanged(task),
564
- unrefTimer: (id) => unrefTimer(id as unknown as number),
565
- })
566
- : null;
567
-
568
- // Validate the shape of the MRTR key here rather than on first use. The
569
- // import itself is async so it stays lazy, but a typo in a 64-hex-character
570
- // secret should surface at boot, not on the first request that needs it —
571
- // by which point it is a runtime failure in production traffic.
572
- const mrtrKey = options.mrtr?.signingKey;
573
- if (mrtrKey !== undefined && !/^[0-9a-f]{64}$/.test(mrtrKey)) {
574
- throw new Error(
575
- "[McpApp] mrtr.signingKey must be 64 lowercase hex characters (32 bytes). " +
576
- "Generate one with: crypto.getRandomValues(new Uint8Array(32)) rendered as hex, " +
577
- "or the exported generateStateKey() + exportStateKey() helpers.",
578
- );
579
- }
580
- if (
581
- options.mrtr?.replayStore !== undefined && mrtrKey === undefined
582
- ) {
583
- throw new Error(
584
- "[McpApp] mrtr.replayStore requires mrtr.signingKey. " +
585
- "Only a verified token exposes a trusted nonce to consume.",
586
- );
587
- }
588
- this.mrtrReplayStore = mrtrKey === undefined
589
- ? null
590
- : options.mrtr?.replayStore ?? new MemoryMrtrReplayStore();
591
- if (mrtrKey !== undefined && options.mrtr?.replayStore === undefined) {
592
- (options.logger ?? console.error)(
593
- "[McpApp] WARNING: MRTR replay protection is process-local. " +
594
- "Load-balanced deployments must configure one shared atomic mrtr.replayStore.",
595
- );
596
- }
597
-
598
- // Create request queue with concurrency control
599
- this.requestQueue = new RequestQueue({
600
- maxConcurrent: options.maxConcurrent ?? 10,
601
- strategy: options.backpressureStrategy ?? "sleep",
602
- sleepMs: options.backpressureSleepMs ?? 10,
603
- });
604
-
605
- // Optional rate limiting
606
- if (options.rateLimit) {
607
- this.rateLimiter = new RateLimiter({
608
- maxRequests: options.rateLimit.maxRequests,
609
- windowMs: options.rateLimit.windowMs,
610
- });
611
- }
612
-
613
- // Optional schema validation
614
- if (options.validateSchema) {
615
- this.schemaValidator = new SchemaValidator();
616
- }
617
-
618
- // A stdio probe may be discarded before a legacy fallback is opened. The
619
- // official serving entry therefore requires a factory, and every factory
620
- // invocation must receive a fresh protocol instance. Registries and the
621
- // middleware pipeline remain on McpApp; handlers close over those maps.
622
- this.resourceHandlersInstalled = options.expectResources === true;
623
- }
624
-
625
- /** Build one unconnected SDK server for one negotiated stdio era. */
626
- private createProtocolServer(): Server {
627
- const cacheHint = {
628
- ttlMs: this.cacheTtlMs,
629
- cacheScope: this.options.cache?.scope ?? "private",
630
- } as const;
631
- // Tasks currently have an HTTP adapter only. Keep its extension out of
632
- // stdio discovery until the same application port is served here; claiming
633
- // it and answering every tasks/* call with MethodNotFound would make the
634
- // capability declaration a lie. Other consumer-declared extensions remain
635
- // transport-neutral.
636
- const stdioExtensions = Object.fromEntries(
637
- Object.entries(this.options.extensions ?? {}).filter(
638
- ([id]) => id !== TASKS_EXTENSION_ID,
639
- ),
640
- );
641
- const capabilities = {
642
- // No listChanged promise: live tool registration does not currently emit
643
- // tools/list_changed. The registry remains usable, but refresh is not a
644
- // protocol guarantee until that notification is wired.
645
- tools: {},
646
- ...(Object.keys(stdioExtensions).length > 0
647
- ? {
648
- extensions: stdioExtensions as Record<string, object>,
649
- }
650
- : {}),
651
- } as ServerCapabilities;
652
- const server = new Server(
653
- { name: this.options.name, version: this.options.version },
654
- {
655
- capabilities,
656
- instructions: this.options.instructions,
657
- cacheHints: {
658
- "server/discover": cacheHint,
659
- "tools/list": cacheHint,
660
- "resources/list": cacheHint,
661
- "resources/templates/list": cacheHint,
662
- "resources/read": cacheHint,
663
- },
664
- },
665
- );
666
- this.setupHandlers(server);
667
- if (this.resourceHandlersInstalled) {
668
- this.installResourceHandlersOn(server);
669
- }
670
- return server;
671
- }
672
-
673
- /**
674
- * Pre-install the resources handlers on the low-level
675
- * SDK Server. This declares the `resources` capability BEFORE transport
676
- * connection, allowing dynamic resource registration after start().
677
- *
678
- * The handlers read from `this.resources` Map which is populated lazily
679
- * by registerResource() calls (e.g., after async MCP discovery).
680
- */
681
- private installResourceHandlers(): void {
682
- if (this.resourceHandlersInstalled) return;
683
- if (this.started) {
684
- throw new Error(
685
- "[McpApp] Cannot install resource handlers after the server starts. " +
686
- "Set expectResources: true or register resources before start().",
687
- );
688
- }
689
- this.resourceHandlersInstalled = true;
690
- }
691
-
692
- /** Install resource handlers on one fresh protocol instance. */
693
- private installResourceHandlersOn(server: Server): void {
694
- // Declare resources capability before transport connects
695
- server.registerCapabilities({ resources: { listChanged: true } });
696
-
697
- // resources/list — returns currently registered resources
698
- server.setRequestHandler("resources/list", () => {
699
- return {
700
- resources: Array.from(this.resources.values()).map((r) =>
701
- this.toResourceListing(r.resource)
702
- ),
703
- } as unknown as ListResourcesResult;
704
- });
705
-
706
- // resources/read — serve resource content by URI
707
- server.setRequestHandler(
708
- "resources/read",
709
- async (request: ReadResourceRequest) => {
710
- const uri = request.params.uri;
711
- const info = this.resources.get(uri);
712
- if (!info) {
713
- throw new ProtocolError(
714
- ProtocolErrorCode.InvalidParams,
715
- `Resource not found: ${uri}`,
716
- );
717
- }
718
-
719
- try {
720
- const finalContent = await this.readResourceForProtocol(
721
- uri,
722
- info.resource,
723
- info.handler,
724
- );
725
- return { contents: [finalContent] };
726
- } catch (error) {
727
- this.log(
728
- `[ERROR] Resource handler failed for ${uri}: ${
729
- error instanceof Error ? error.message : String(error)
730
- }`,
731
- );
732
- throw error;
733
- }
734
- },
735
- );
736
-
737
- // We currently expose concrete resources only. An explicit empty template
738
- // list is nevertheless required once the resources capability exists:
739
- // clients are entitled to ask which URI templates can be expanded.
740
- server.setRequestHandler("resources/templates/list", () => ({
741
- resourceTemplates: [],
742
- }));
743
- this.resourceLog("Resources capability installed");
744
- }
745
-
746
- /**
747
- * Setup MCP protocol request handlers
748
- */
749
- private setupHandlers(server: Server): void {
750
- // Wire up "initialized" notification callback (post-handshake)
751
- server.oninitialized = () => {
752
- this.initializedCallback?.();
753
- };
754
-
755
- // tools/list handler
756
- server.setRequestHandler("tools/list", () => {
757
- return { tools: this.buildToolListing() } as unknown as ListToolsResult;
758
- });
759
-
760
- // tools/call handler (delegates to middleware pipeline)
761
- server.setRequestHandler(
762
- "tools/call",
763
- async (
764
- request: CallToolRequest,
765
- ctx: ServerContext,
766
- ): Promise<CallToolResult | InputRequiredResult> => {
767
- const toolName = request.params.name;
768
- const args = request.params.arguments || {};
769
-
770
- // Per-request `_meta` is transport-independent. Trace context matters
771
- // here because a local server is exactly where a detached span is
772
- // hardest to correlate back to the host that caused it; `logLevel` is
773
- // read for the same reason it is on HTTP — the spec makes it
774
- // per-request, and a handler must stay silent without it.
775
- const meta = isRecord(request.params._meta)
776
- ? request.params._meta
777
- : undefined;
778
- const envelope = isRecord(ctx.mcpReq.envelope)
779
- ? ctx.mcpReq.envelope
780
- : undefined;
781
- const clientInfo = envelope?.[STATELESS_CLIENT_INFO_KEY] as
782
- | Implementation
783
- | undefined ?? server.getClientVersion();
784
- const clientCapabilities = envelope?.[
785
- STATELESS_CLIENT_CAPABILITIES_KEY
786
- ] as ClientCapabilities | undefined ??
787
- server.getClientCapabilities();
788
- const requestedLogLevel = envelope !== undefined
789
- ? readLogLevel(envelope)
790
- : undefined;
791
- const traceContext = meta !== undefined
792
- ? readTraceContext(meta)
793
- : undefined;
794
- const clientMeta: StatelessClientMeta | undefined =
795
- clientInfo !== undefined || clientCapabilities !== undefined ||
796
- requestedLogLevel !== undefined || traceContext !== undefined
797
- ? {
798
- ...(clientInfo !== undefined ? { clientInfo } : {}),
799
- ...(clientCapabilities !== undefined
800
- ? { clientCapabilities }
801
- : {}),
802
- ...(requestedLogLevel !== undefined
803
- ? { logLevel: requestedLogLevel }
804
- : {}),
805
- ...(traceContext ?? {}),
806
- }
807
- : undefined;
808
-
809
- // The v2 protocol layer lifts MRTR retry fields out of params before
810
- // invoking the handler. Preserve Casys' method/argument/principal and
811
- // single-use bindings on stdio just as the HTTP path does.
812
- const ingressDigest = await paramsDigest({
813
- arguments: args,
814
- name: toolName,
815
- });
816
- if ((ctx.mcpReq.droppedInputResponseKeys?.length ?? 0) > 0) {
817
- throw new ProtocolError(
818
- ProtocolErrorCode.InvalidParams,
819
- "inputResponses entries must be bare MCP result objects",
820
- {
821
- problem: "malformed_input_responses",
822
- droppedKeys: ctx.mcpReq.droppedInputResponseKeys,
823
- recovery:
824
- "Send each inputResponses value as the bare result object, without a {method, result} wrapper.",
825
- },
826
- );
827
- }
828
- const inputResponses = ctx.mcpReq.inputResponses;
829
- const echoedState = ctx.mcpReq.requestState<string>();
830
- const mrtr = await this.prepareProtocolMrtrRetry(
831
- inputResponses,
832
- echoedState,
833
- {
834
- principal: MRTR_NO_AUTH_PRINCIPAL,
835
- method: "tools/call",
836
- paramsDigest: ingressDigest,
837
- },
838
- );
839
-
840
- let result: unknown;
841
- try {
842
- result = await this.executeToolCall(
843
- toolName,
844
- args,
845
- undefined,
846
- undefined,
847
- undefined,
848
- clientMeta,
849
- mrtr,
850
- );
851
- } catch (error) {
852
- return this.handleToolError(
853
- error,
854
- toolName,
855
- ) as unknown as CallToolResult;
856
- }
857
-
858
- if (isRecord(result) && result["resultType"] === "input_required") {
859
- const built = await this.buildInputRequiredResult(
860
- result as unknown as InputRequiredSignal,
861
- {
862
- clientCapabilities,
863
- principal: MRTR_NO_AUTH_PRINCIPAL,
864
- method: "tools/call",
865
- paramsDigest: ingressDigest,
866
- },
867
- );
868
- if (!built.ok) {
869
- throw new ProtocolError(
870
- built.code,
871
- built.message,
872
- built.data,
873
- );
874
- }
875
- return built.result as unknown as InputRequiredResult;
876
- }
877
-
878
- // Serialization errors are framework bugs, not tool errors —
879
- // let them propagate
880
- return this.buildToolCallResult(
881
- toolName,
882
- result,
883
- ) as unknown as CallToolResult;
884
- },
885
- );
886
- }
887
-
888
- /**
889
- * The stateless HTTP `server/discover` result (spec 2026-07-28, SEP-2575).
890
- *
891
- * The stdio adapter deliberately does not call this builder: the official v2
892
- * serving entry owns discover, era selection, result stamping and its final
893
- * wire shape. Keeping this method HTTP-specific prevents a custom payload
894
- * from bypassing that authority again.
895
- */
896
- private buildDiscoverResult(): Record<string, unknown> {
897
- return this.stampResult(
898
- this.withCacheHints({
899
- supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
900
- capabilities: this.buildServerCapabilities(),
901
- serverInfo: {
902
- name: this.options.name,
903
- version: this.options.version,
904
- },
905
- ...(this.options.instructions
906
- ? { instructions: this.options.instructions }
907
- : {}),
908
- }, SPEC_2026_07_28),
909
- SPEC_2026_07_28,
910
- );
911
- }
912
-
913
- /**
914
- * Register tools with their handlers
915
- *
916
- * @param tools - Array of tool definitions (MCP format)
917
- * @param handlers - Map of tool name to handler function
918
- */
919
- registerTools(
920
- tools: MCPTool[],
921
- handlers: Map<string, ToolHandler>,
922
- ): void {
923
- if (this.started) {
924
- throw new Error(
925
- "[McpApp] Cannot register tools after server started. " +
926
- "Call registerTools() before start() or startHttp().",
927
- );
928
- }
929
- for (const tool of tools) {
930
- const handler = handlers.get(tool.name);
931
- if (!handler) {
932
- throw new Error(`No handler provided for tool: ${tool.name}`);
933
- }
934
-
935
- // Validate annotations BEFORE inserting: a throw must not leave the tool
936
- // half-registered. Registration is the right place to fail — a conforming
937
- // client drops the whole tool from `tools/list` over a malformed
938
- // annotation, so a typo would otherwise surface as a tool that silently
939
- // does not exist (AX: fast fail early).
940
- this.indexMirroredParams(tool);
941
-
942
- this.tools.set(tool.name, {
943
- ...tool,
944
- handler,
945
- });
946
-
947
- // Register schema for validation if enabled
948
- if (this.schemaValidator) {
949
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
950
- }
951
- }
952
-
953
- this.log(`Registered ${tools.length} tools`);
954
- }
955
-
956
- /**
957
- * Register a single tool
958
- *
959
- * @param tool - Tool definition
960
- * @param handler - Tool handler function
961
- */
962
- /**
963
- * Validate and index a tool's `x-mcp-header` annotations (spec 2026-07-28).
964
- *
965
- * Every registration path must go through here. Wiring it into `registerTools`
966
- * alone was a real bypass: a tool registered via `registerTool` or
967
- * `registerToolLive` carried annotations that clients would mirror into
968
- * `Mcp-Param-*` headers, while the server never required or checked them.
969
- *
970
- * Throws *before* the caller inserts the tool, so a rejected definition cannot
971
- * leave a half-registered tool behind.
972
- */
973
- private indexMirroredParams(tool: MCPTool): void {
974
- const invalid: string[] = [];
975
- const mirrored = collectMirroredParams(
976
- tool.inputSchema,
977
- (reason) => invalid.push(reason),
978
- );
979
- if (invalid.length > 0) {
980
- throw new Error(
981
- `[McpApp] Tool "${tool.name}" has invalid x-mcp-header annotations:\n` +
982
- invalid.map((r) => ` - ${r}`).join("\n"),
983
- );
984
- }
985
- // Replace wholesale: re-registering a tool without annotations must clear
986
- // whatever a previous definition left behind.
987
- if (mirrored.length > 0) this.mirroredParams.set(tool.name, mirrored);
988
- else this.mirroredParams.delete(tool.name);
989
- }
990
-
991
- registerTool(tool: MCPTool, handler: ToolHandler): void {
992
- if (this.started) {
993
- throw new Error(
994
- "[McpApp] Cannot register tools after server started. " +
995
- "Call registerTool() before start() or startHttp().",
996
- );
997
- }
998
- this.indexMirroredParams(tool);
999
- this.tools.set(tool.name, {
1000
- ...tool,
1001
- handler,
1002
- });
1003
-
1004
- // Register schema for validation if enabled
1005
- if (this.schemaValidator) {
1006
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
1007
- }
1008
-
1009
- this.log(`Registered tool: ${tool.name}`);
1010
- }
1011
-
1012
- /**
1013
- * Register a tool after the server has started (live registration).
1014
- *
1015
- * Unlike registerTool(), this can be called while the server is running.
1016
- * The tool becomes immediately available for tools/list and tools/call.
1017
- *
1018
- * Use case: relay proxy where tools are registered dynamically
1019
- * when remote owners connect/disconnect their tunnels.
1020
- *
1021
- * @param tool - Tool definition
1022
- * @param handler - Tool handler function
1023
- */
1024
- registerToolLive(tool: MCPTool, handler: ToolHandler): void {
1025
- this.indexMirroredParams(tool);
1026
- this.tools.set(tool.name, {
1027
- ...tool,
1028
- handler,
1029
- });
1030
-
1031
- if (this.schemaValidator) {
1032
- this.schemaValidator.addSchema(tool.name, tool.inputSchema);
1033
- }
1034
-
1035
- this.log(`Live-registered tool: ${tool.name} (total: ${this.tools.size})`);
1036
- }
1037
-
1038
- /**
1039
- * Register a tool that is only visible to the MCP App (UI layer),
1040
- * not to the model via tools/list.
1041
- *
1042
- * Equivalent to registerTool() with _meta.ui.visibility: ["app"].
1043
- * The tool is still callable via tools/call if the caller knows its name.
1044
- *
1045
- * @param tool - Tool definition
1046
- * @param handler - Tool handler function
1047
- */
1048
- registerAppOnlyTool(tool: MCPTool, handler: ToolHandler): void {
1049
- const merged: MCPTool = {
1050
- ...tool,
1051
- _meta: {
1052
- ...tool._meta,
1053
- ui: {
1054
- ...tool._meta?.ui,
1055
- visibility: ["app"],
1056
- },
1057
- } as MCPTool["_meta"],
1058
- };
1059
- this.registerTool(merged, handler);
1060
- }
1061
-
1062
- /**
1063
- * Unregister a tool (removes it from tools/list and tools/call).
1064
- *
1065
- * Can be called before or after start.
1066
- * In-flight calls to this tool will complete normally.
1067
- *
1068
- * @param toolName - Name of the tool to remove
1069
- * @returns true if the tool was found and removed
1070
- */
1071
- unregisterTool(toolName: string): boolean {
1072
- const deleted = this.tools.delete(toolName);
1073
- // Stale mirror metadata would make the server demand `Mcp-Param-*` headers
1074
- // for a tool that no longer exists.
1075
- this.mirroredParams.delete(toolName);
1076
- if (deleted) {
1077
- this.log(
1078
- `Unregistered tool: ${toolName} (remaining: ${this.tools.size})`,
1079
- );
1080
- }
1081
- return deleted;
1082
- }
1083
-
1084
- // ============================================
1085
- // Middleware Pipeline
1086
- // ============================================
1087
-
1088
- /**
1089
- * Add a custom middleware to the pipeline.
1090
- * Must be called before start()/startHttp().
1091
- *
1092
- * Custom middlewares execute between rate-limit and validation:
1093
- * rate-limit → **custom middlewares** → validation → backpressure → handler
1094
- *
1095
- * @param middleware - Middleware function
1096
- * @returns this (for chaining)
1097
- *
1098
- * @example
1099
- * ```typescript
1100
- * server.use(async (ctx, next) => {
1101
- * console.log(`Calling ${ctx.toolName}`);
1102
- * const result = await next();
1103
- * console.log(`Done ${ctx.toolName}`);
1104
- * return result;
1105
- * });
1106
- * ```
1107
- */
1108
- use(middleware: Middleware): this {
1109
- if (this.started) {
1110
- throw new Error(
1111
- "[McpApp] Cannot add middleware after server started. " +
1112
- "Call use() before start() or startHttp().",
1113
- );
1114
- }
1115
- this.customMiddlewares.push(middleware);
1116
- this.middlewareRunner = null; // Invalidate cached runner
1117
- return this;
1118
- }
1119
-
1120
- /**
1121
- * Build the middleware pipeline from config + custom middlewares.
1122
- * Called once at start()/startHttp() time.
1123
- *
1124
- * Pipeline order:
1125
- * rate-limit → auth → custom middlewares → scope-check → validation → backpressure → handler
1126
- */
1127
- private buildPipeline(): void {
1128
- const pipeline: Middleware[] = [];
1129
-
1130
- // 1. Rate limiting (if configured)
1131
- if (this.rateLimiter && this.options.rateLimit) {
1132
- pipeline.push(
1133
- createRateLimitMiddleware(this.rateLimiter, this.options.rateLimit),
1134
- );
1135
- }
1136
-
1137
- // 2. Auth middleware (if auth provider is set)
1138
- if (this.authProvider) {
1139
- pipeline.push(createAuthMiddleware(this.authProvider));
1140
- }
1141
-
1142
- // 3. Custom middlewares (logging, tracing, etc.)
1143
- pipeline.push(...this.customMiddlewares);
1144
-
1145
- // 4. Scope enforcement (if any tool has requiredScopes)
1146
- const toolScopes = new Map<string, string[]>();
1147
- for (const [name, tool] of this.tools) {
1148
- if (tool.requiredScopes?.length) {
1149
- toolScopes.set(name, tool.requiredScopes);
1150
- }
1151
- }
1152
- if (toolScopes.size > 0) {
1153
- pipeline.push(createScopeMiddleware(toolScopes));
1154
- }
1155
-
1156
- // 5. Schema validation (if enabled)
1157
- if (this.schemaValidator) {
1158
- pipeline.push(createValidationMiddleware(this.schemaValidator));
1159
- }
1160
-
1161
- // 6. Backpressure (always)
1162
- pipeline.push(createBackpressureMiddleware(this.requestQueue));
1163
-
1164
- this.middlewareRunner = createMiddlewareRunner(pipeline, (ctx) => {
1165
- const tool = this.tools.get(ctx.toolName);
1166
- if (!tool) {
1167
- throw new Error(`Unknown tool: ${ctx.toolName}`);
1168
- }
1169
- return Promise.resolve(tool.handler(ctx.args, {
1170
- toolName: ctx.toolName,
1171
- ...(ctx.request ? { request: ctx.request } : {}),
1172
- ...(typeof ctx.sessionId === "string"
1173
- ? { sessionId: ctx.sessionId }
1174
- : {}),
1175
- ...(ctx.authInfo ? { authInfo: ctx.authInfo as AuthInfo } : {}),
1176
- ...(ctx.clientInfo !== undefined ? { clientInfo: ctx.clientInfo } : {}),
1177
- ...(ctx.clientCapabilities !== undefined
1178
- ? { clientCapabilities: ctx.clientCapabilities }
1179
- : {}),
1180
- ...(ctx.logLevel !== undefined ? { logLevel: ctx.logLevel } : {}),
1181
- ...(ctx.inputResponses !== undefined
1182
- ? { inputResponses: ctx.inputResponses }
1183
- : {}),
1184
- ...(ctx.retryVerified !== undefined
1185
- ? { retryVerified: ctx.retryVerified }
1186
- : {}),
1187
- }));
1188
- });
1189
- }
1190
-
1191
- /**
1192
- * Execute a tool call through the middleware pipeline.
1193
- * Unified entry point for both STDIO and HTTP transports.
1194
- *
1195
- * @param toolName - Name of the tool to call
1196
- * @param args - Tool arguments
1197
- * @param request - HTTP request (undefined for STDIO)
1198
- * @param sessionId - HTTP session ID (undefined for STDIO)
1199
- * @returns Tool execution result
1200
- */
1201
- private async executeToolCall(
1202
- toolName: string,
1203
- args: Record<string, unknown>,
1204
- request?: Request,
1205
- sessionId?: string,
1206
- preVerifiedAuthInfo?: AuthInfo,
1207
- clientMeta?: StatelessClientMeta,
1208
- mrtr?: {
1209
- inputResponses?: Record<string, unknown>;
1210
- retryVerified?: boolean;
1211
- },
1212
- ): Promise<MiddlewareResult> {
1213
- if (!this.middlewareRunner) {
1214
- throw new Error(
1215
- "[McpApp] Pipeline not built. Call start() or startHttp() first.",
1216
- );
1217
- }
1218
-
1219
- const ctx: MiddlewareContext = {
1220
- toolName,
1221
- args,
1222
- request,
1223
- sessionId,
1224
- // Pass pre-verified authInfo from the HTTP gate so the auth
1225
- // middleware skips the redundant verifyToken call (avoids JWKS
1226
- // race conditions on concurrent cold-cache requests).
1227
- authInfo: preVerifiedAuthInfo,
1228
- ...(clientMeta?.clientInfo !== undefined
1229
- ? { clientInfo: clientMeta.clientInfo }
1230
- : {}),
1231
- ...(clientMeta?.clientCapabilities !== undefined
1232
- ? { clientCapabilities: clientMeta.clientCapabilities }
1233
- : {}),
1234
- ...(clientMeta?.logLevel !== undefined
1235
- ? { logLevel: clientMeta.logLevel }
1236
- : {}),
1237
- ...(mrtr?.inputResponses !== undefined
1238
- ? { inputResponses: mrtr.inputResponses }
1239
- : {}),
1240
- ...(mrtr?.retryVerified !== undefined
1241
- ? { retryVerified: mrtr.retryVerified }
1242
- : {}),
1243
- };
1244
-
1245
- // OTel span + metrics
1246
- const span = startToolCallSpan(
1247
- toolName,
1248
- {
1249
- "mcp.tool.name": toolName,
1250
- "mcp.server.name": this.options.name,
1251
- "mcp.transport": request ? "http" : "stdio",
1252
- "mcp.session.id": sessionId,
1253
- },
1254
- clientMeta?.traceContext,
1255
- );
1256
-
1257
- // Update gauges before execution
1258
- const queueMetrics = this.requestQueue.getMetrics();
1259
- this.serverMetrics.setGauges({
1260
- activeRequests: queueMetrics.inFlight,
1261
- queuedRequests: queueMetrics.queued,
1262
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
1263
- });
1264
-
1265
- const start = performance.now();
1266
- try {
1267
- const result = await this.middlewareRunner(ctx);
1268
- const durationMs = performance.now() - start;
1269
- this.serverMetrics.recordToolCall(toolName, true, durationMs);
1270
- endToolCallSpan(span, true, durationMs);
1271
- return result;
1272
- } catch (error) {
1273
- const durationMs = performance.now() - start;
1274
- const errorMsg = error instanceof Error ? error.message : String(error);
1275
- this.serverMetrics.recordToolCall(toolName, false, durationMs);
1276
- endToolCallSpan(span, false, durationMs, errorMsg);
1277
- throw error;
1278
- }
1279
- }
1280
-
1281
- // ============================================
1282
- // Resource Registration (MCP Apps SEP-1865)
1283
- // ============================================
1284
-
1285
- /**
1286
- * Apply CSP meta tag injection to HTML resource content (if configured).
1287
- * Only transforms text HTML content; blob responses pass through unchanged.
1288
- */
1289
- private applyResourceCsp(content: ResourceContent): ResourceContent {
1290
- if (!this.options.resourceCsp) return content;
1291
- const mediaType = content.mimeType.split(";", 1)[0].trim().toLowerCase();
1292
- if (
1293
- !this.isTextResourceContent(content) ||
1294
- mediaType !== "text/html"
1295
- ) {
1296
- return content;
1297
- }
1298
-
1299
- const cspValue = buildCspHeader(this.options.resourceCsp);
1300
- return {
1301
- ...content,
1302
- text: injectCspMetaTag(content.text, cspValue),
1303
- };
1304
- }
1305
-
1306
- private isTextResourceContent(
1307
- content: ResourceContent,
1308
- ): content is Extract<ResourceContent, { text: string }> {
1309
- return "text" in content;
1310
- }
1311
-
1312
- /** Standard padded base64 with zero pad bits, without whitespace or URL-safe substitutions. */
1313
- private isCanonicalBase64(blob: string): boolean {
1314
- try {
1315
- // `atob` accepts several equivalent spellings. Re-encoding is what
1316
- // rejects omitted padding, whitespace, URL-safe alphabets, and non-zero
1317
- // pad bits such as `/x==` (whose canonical form is `/w==`). Both APIs are
1318
- // Web-standard globals available in Deno and supported Node runtimes.
1319
- return btoa(atob(blob)) === blob;
1320
- } catch {
1321
- return false;
1322
- }
1323
- }
1324
-
1325
- /**
1326
- * Validate an untrusted handler result at the API boundary.
1327
- *
1328
- * TypeScript callers get the discriminated `ResourceContent` union at compile
1329
- * time. This check closes the equivalent JavaScript, `any`, and unchecked
1330
- * TypeScript paths before a malformed result reaches an MCP client.
1331
- */
1332
- private validateResourceContent(
1333
- requestedUri: string,
1334
- candidate: unknown,
1335
- resource: MCPResource,
1336
- ): ResourceContent {
1337
- if (!isRecord(candidate)) {
1338
- throw new Error("[McpApp] Resource handler must return an object");
1339
- }
1340
-
1341
- const hasText = Object.prototype.hasOwnProperty.call(candidate, "text");
1342
- const hasBlob = Object.prototype.hasOwnProperty.call(candidate, "blob");
1343
- if (hasText === hasBlob) {
1344
- throw new Error(
1345
- "[McpApp] Resource content must contain exactly one of text or blob",
1346
- );
1347
- }
1348
- if (candidate.uri !== requestedUri) {
1349
- throw new Error(
1350
- `[McpApp] Resource content URI must match requested URI: ${requestedUri}`,
1351
- );
1352
- }
1353
- if (Object.prototype.hasOwnProperty.call(candidate, "annotations")) {
1354
- throw new Error(
1355
- "[McpApp] Resource content annotations are not a ResourceContents field; put annotations on MCPResource metadata",
1356
- );
1357
- }
1358
- if (candidate._meta !== undefined && !isRecord(candidate._meta)) {
1359
- throw new Error(
1360
- "[McpApp] Resource content _meta must be an object when supplied",
1361
- );
1362
- }
1363
- if (
1364
- typeof candidate.mimeType !== "string" ||
1365
- candidate.mimeType.trim().length === 0
1366
- ) {
1367
- throw new Error(
1368
- "[McpApp] Resource content mimeType must be a non-empty string",
1369
- );
1370
- }
1371
- if (hasText && typeof candidate.text !== "string") {
1372
- throw new Error("[McpApp] Resource content text must be a string");
1373
- }
1374
- if (hasBlob) {
1375
- if (typeof candidate.blob !== "string") {
1376
- throw new Error("[McpApp] Resource content blob must be a string");
1377
- }
1378
- if (!this.isCanonicalBase64(candidate.blob)) {
1379
- throw new Error(
1380
- "[McpApp] Resource content blob must be canonical standard base64",
1381
- );
1382
- }
1383
- }
1384
-
1385
- if (
1386
- resource.mimeType !== undefined &&
1387
- candidate.mimeType !== resource.mimeType
1388
- ) {
1389
- throw new Error(
1390
- `[McpApp] Resource content mimeType must match registered metadata: ${resource.mimeType}`,
1391
- );
1392
- }
1393
- if (resource.size !== undefined) {
1394
- const actualSize = hasText
1395
- ? new TextEncoder().encode(candidate.text as string).byteLength
1396
- : atob(candidate.blob as string).length;
1397
- if (actualSize !== resource.size) {
1398
- throw new Error(
1399
- `[McpApp] Resource content size must match registered metadata: expected ${resource.size}, got ${actualSize}`,
1400
- );
1401
- }
1402
- }
1403
-
1404
- // Do not forward arbitrary JavaScript fields to the wire. In particular,
1405
- // annotations belong to Resource, not ResourceContents in the MCP schema.
1406
- return hasText
1407
- ? {
1408
- uri: requestedUri,
1409
- mimeType: candidate.mimeType,
1410
- text: candidate.text as string,
1411
- ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1412
- }
1413
- : {
1414
- uri: requestedUri,
1415
- mimeType: candidate.mimeType,
1416
- blob: candidate.blob as string,
1417
- ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1418
- };
1419
- }
1420
-
1421
- /** Run, validate, and CSP-harden a handler for a protocol response. */
1422
- private async readResourceForProtocol(
1423
- requestedUri: string,
1424
- resource: MCPResource,
1425
- handler: ResourceHandler,
1426
- ): Promise<ResourceContent> {
1427
- const content = this.validateResourceContent(
1428
- requestedUri,
1429
- await handler(new URL(requestedUri)),
1430
- resource,
1431
- );
1432
- // Size attests the bytes delivered to the client. CSP injection changes a
1433
- // text body, so validate the served representation too rather than only
1434
- // the handler's pre-injection value.
1435
- return this.validateResourceContent(
1436
- requestedUri,
1437
- this.applyResourceCsp(content),
1438
- resource,
1439
- );
1440
- }
1441
-
1442
- /** Convert public metadata into the exact wire listing shape. */
1443
- private toResourceListing(resource: MCPResource): Record<string, unknown> {
1444
- return {
1445
- uri: resource.uri,
1446
- name: resource.name,
1447
- ...(resource.title !== undefined ? { title: resource.title } : {}),
1448
- ...(resource.description !== undefined
1449
- ? { description: resource.description }
1450
- : {}),
1451
- ...(resource.mimeType !== undefined
1452
- ? { mimeType: resource.mimeType }
1453
- : {}),
1454
- ...(resource.size !== undefined ? { size: resource.size } : {}),
1455
- ...(resource.icons !== undefined ? { icons: resource.icons } : {}),
1456
- ...(resource.annotations !== undefined
1457
- ? { annotations: resource.annotations }
1458
- : {}),
1459
- ...(resource._meta !== undefined ? { _meta: resource._meta } : {}),
1460
- };
1461
- }
1462
-
1463
- /** Fail early rather than publishing a metadata value clients must ignore. */
1464
- private validateResourceMetadata(resource: MCPResource): void {
1465
- this.validateResourceUri(resource.uri);
1466
- if (typeof resource.name !== "string" || resource.name.length === 0) {
1467
- throw new Error("[McpApp] Resource name must be a non-empty string");
1468
- }
1469
- if (
1470
- resource.mimeType !== undefined &&
1471
- (typeof resource.mimeType !== "string" ||
1472
- resource.mimeType.trim().length === 0)
1473
- ) {
1474
- throw new Error(
1475
- "[McpApp] Resource mimeType must be a non-empty string when supplied",
1476
- );
1477
- }
1478
- if (
1479
- resource.size !== undefined &&
1480
- (!Number.isSafeInteger(resource.size) || resource.size < 0)
1481
- ) {
1482
- throw new Error(
1483
- `[McpApp] Resource size must be a non-negative safe integer (got ${resource.size})`,
1484
- );
1485
- }
1486
- }
1487
-
1488
- /**
1489
- * Resources are keyed by their wire URI, so accepting a spelling which URL
1490
- * canonicalisation changes would make list/read/handler identity ambiguous.
1491
- * Refuse it at registration instead of silently normalising a caller-owned
1492
- * identifier. Non-`ui:` schemes are valid MCP resources and remain allowed.
1493
- */
1494
- private validateResourceUri(uri: string): void {
1495
- if (typeof uri !== "string" || uri.length === 0) {
1496
- throw new Error("[McpApp] Resource URI must be a non-empty string");
1497
- }
1498
- let canonical: string;
1499
- try {
1500
- canonical = new URL(uri).toString();
1501
- } catch {
1502
- throw new Error(`[McpApp] Resource URI must be an absolute URI: ${uri}`);
1503
- }
1504
- if (canonical !== uri) {
1505
- throw new Error(
1506
- `[McpApp] Resource URI must be canonical: received ${uri}, canonical form is ${canonical}`,
1507
- );
1508
- }
1509
- }
1510
-
1511
- /** A consumer logger is observability, never a resource-commit dependency. */
1512
- private resourceLog(message: string): void {
1513
- try {
1514
- this.log(message);
1515
- } catch {
1516
- // Deliberately ignored: a throwing logger must not contradict a committed
1517
- // resource mutation or make a retry appear necessary.
1518
- }
1519
- }
1520
-
1521
- /**
1522
- * Publish the one post-commit list-changed projection for a mutation.
1523
- * It is best-effort by design: registry state is authoritative and callers
1524
- * must not receive a false failure after it changes.
1525
- */
1526
- private notifyResourceListChanged(): void {
1527
- if (!this.started) return;
1528
- if (this.subscriptions !== null) {
1529
- this.sendNotification("notifications/resources/list_changed");
1530
- return;
1531
- }
1532
- const server = this.activeStdioServer;
1533
- if (server === null) return;
1534
- void server.sendResourceListChanged().catch((error) => {
1535
- this.resourceLog(
1536
- `[WARN] Resource list changed notification was not delivered: ${
1537
- error instanceof Error ? error.message : String(error)
1538
- }`,
1539
- );
1540
- });
1541
- }
1542
-
1543
- /**
1544
- * Register a single resource
1545
- *
1546
- * @param resource - Resource definition with uri, name, description
1547
- * @param handler - Callback that returns ResourceContent when resource is read
1548
- * @throws Error if resource with same URI already registered
1549
- *
1550
- * @example
1551
- * ```typescript
1552
- * server.registerResource(
1553
- * { uri: "ui://my-server/viewer", name: "Viewer", description: "Data viewer" },
1554
- * async (uri) => ({
1555
- * uri: uri.toString(),
1556
- * mimeType: MCP_APP_MIME_TYPE,
1557
- * text: "<html>...</html>"
1558
- * })
1559
- * );
1560
- * ```
1561
- */
1562
- registerResource(resource: MCPResource, handler: ResourceHandler): void {
1563
- this.validateResourceMetadata(resource);
1564
-
1565
- if (typeof handler !== "function") {
1566
- throw new Error("[McpApp] Resource handler must be a function");
1567
- }
1568
-
1569
- // Check for duplicate
1570
- if (this.resources.has(resource.uri)) {
1571
- throw new Error(
1572
- `[McpApp] Resource already registered: ${resource.uri}`,
1573
- );
1574
- }
1575
-
1576
- // Static registrations lazily install the single low-level handler set.
1577
- // Once a transport starts, handler installation would be too late, so a
1578
- // deployment that needs late discovery must opt in with expectResources.
1579
- if (!this.resourceHandlersInstalled) {
1580
- if (this.started) {
1581
- throw new Error(
1582
- "[McpApp] Cannot register a resource after start without expectResources: true.",
1583
- );
1584
- }
1585
- this.installResourceHandlers();
1586
- }
1587
-
1588
- // The Map is the only registry. It commits atomically and has no secondary
1589
- // SDK entry which could survive a failed rollback as a ghost resource.
1590
- this.resources.set(resource.uri, { resource, handler });
1591
- this.resourceLog(`Registered resource: ${resource.name} (${resource.uri})`);
1592
- this.notifyResourceListChanged();
1593
- }
1594
-
1595
- /**
1596
- * Remove a resource from this server.
1597
- *
1598
- * It is safe before or after either transport starts once resources are
1599
- * installed. Returns `false` when no such URI is present, so callers can make
1600
- * idempotent cleanup calls without catching an error.
1601
- */
1602
- unregisterResource(uri: string): boolean {
1603
- const info = this.resources.get(uri);
1604
- if (!info) return false;
1605
-
1606
- this.resources.delete(uri);
1607
- this.resourceLog(`Unregistered resource: ${uri}`);
1608
- this.notifyResourceListChanged();
1609
- return true;
1610
- }
1611
-
1612
- /**
1613
- * Register multiple resources
1614
- *
1615
- * @param resources - Array of resource definitions
1616
- * @param handlers - Map of URI to handler function
1617
- * @throws Error if any resource is missing a handler (fail-fast)
1618
- */
1619
- registerResources(
1620
- resources: MCPResource[],
1621
- handlers: Map<string, ResourceHandler>,
1622
- ): void {
1623
- // No mutation means no capability installation and no notification.
1624
- if (resources.length === 0) return;
1625
- // Validate all handlers exist BEFORE registering any (fail-fast)
1626
- const missingHandlers: string[] = [];
1627
- for (const resource of resources) {
1628
- if (!handlers.has(resource.uri)) {
1629
- missingHandlers.push(resource.uri);
1630
- }
1631
- }
1632
-
1633
- if (missingHandlers.length > 0) {
1634
- throw new Error(
1635
- `[McpApp] Missing handlers for resources:\n` +
1636
- missingHandlers.map((uri) => ` - ${uri}`).join("\n"),
1637
- );
1638
- }
1639
-
1640
- // Validate no duplicates exist BEFORE registering any (atomic behavior)
1641
- const duplicateUris: string[] = [];
1642
- for (const resource of resources) {
1643
- if (this.resources.has(resource.uri)) {
1644
- duplicateUris.push(resource.uri);
1645
- }
1646
- }
1647
-
1648
- if (duplicateUris.length > 0) {
1649
- throw new Error(
1650
- `[McpApp] Resources already registered:\n` +
1651
- duplicateUris.map((uri) => ` - ${uri}`).join("\n"),
1652
- );
1653
- }
1654
-
1655
- // A duplicate inside this batch would otherwise fail only when the second
1656
- // registration is attempted, after the first has been made visible.
1657
- const seenUris = new Set<string>();
1658
- const repeatedUris = resources
1659
- .map((resource) => resource.uri)
1660
- .filter((uri) => {
1661
- if (seenUris.has(uri)) return true;
1662
- seenUris.add(uri);
1663
- return false;
1664
- });
1665
- if (repeatedUris.length > 0) {
1666
- throw new Error(
1667
- `[McpApp] Resources are repeated in this batch:\n` +
1668
- repeatedUris.map((uri) => ` - ${uri}`).join("\n"),
1669
- );
1670
- }
1671
-
1672
- for (const resource of resources) {
1673
- this.validateResourceMetadata(resource);
1674
- if (typeof handlers.get(resource.uri) !== "function") {
1675
- throw new Error(
1676
- `[McpApp] Resource handler must be a function: ${resource.uri}`,
1677
- );
1678
- }
1679
- }
1680
- if (!this.resourceHandlersInstalled) {
1681
- if (this.started) {
1682
- throw new Error(
1683
- "[McpApp] Cannot register resources after start without expectResources: true.",
1684
- );
1685
- }
1686
- this.installResourceHandlers();
1687
- }
1688
- // All validation and the one possible handler-install side effect happened
1689
- // before this point. A Map update cannot partially fail, so the batch gets
1690
- // one commit and one notification (or neither on validation failure).
1691
- for (const resource of resources) {
1692
- this.resources.set(resource.uri, {
1693
- resource,
1694
- handler: handlers.get(resource.uri)!,
1695
- });
1696
- }
1697
- this.resourceLog(`Registered ${resources.length} resources`);
1698
- if (resources.length > 0) this.notifyResourceListChanged();
1699
- }
1700
-
1701
- /**
1702
- * Register MCP Apps viewers with automatic dist path resolution.
1703
- *
1704
- * Replaces the manual pattern of: enumerate viewers → resolve paths → register resources.
1705
- * Each viewer gets a `ui://{prefix}/{viewerName}` resource URI.
1706
- *
1707
- * Viewers whose dist is not found are skipped with a warning (not an error),
1708
- * so that the server can start in dev without building UIs first.
1709
- *
1710
- * @returns Summary of registered and skipped viewers
1711
- */
1712
- registerViewers(config: RegisterViewersConfig): RegisterViewersSummary {
1713
- if (!config.prefix) {
1714
- throw new Error(
1715
- "[McpApp] registerViewers: prefix is required",
1716
- );
1717
- }
1718
-
1719
- // Resolve viewer list: explicit or auto-discovered
1720
- let viewerNames: string[];
1721
- if (config.viewers) {
1722
- viewerNames = config.viewers;
1723
- } else if (config.discover) {
1724
- viewerNames = discoverViewers(config.discover.uiDir, config.discover);
1725
- } else {
1726
- viewerNames = [];
1727
- }
1728
-
1729
- const humanNameFn = config.humanName ?? defaultHumanName;
1730
- const registered: string[] = [];
1731
- const skipped: string[] = [];
1732
-
1733
- for (const viewerName of viewerNames) {
1734
- const distPath = resolveViewerDistPath(
1735
- config.moduleUrl,
1736
- viewerName,
1737
- config.exists,
1738
- );
1739
-
1740
- if (!distPath) {
1741
- this.log(
1742
- `Warning: UI not built for ui://${config.prefix}/${viewerName}. ` +
1743
- `Run the UI build step first.`,
1744
- );
1745
- skipped.push(viewerName);
1746
- continue;
1747
- }
1748
-
1749
- const resourceUri = `ui://${config.prefix}/${viewerName}`;
1750
- const readFile = config.readFile;
1751
- const currentDistPath = distPath;
1752
-
1753
- this.registerResource(
1754
- {
1755
- uri: resourceUri,
1756
- name: humanNameFn(viewerName),
1757
- description: `MCP App: ${viewerName}`,
1758
- mimeType: MCP_APP_MIME_TYPE,
1759
- },
1760
- async () => {
1761
- const html = await Promise.resolve(readFile(currentDistPath));
1762
- const content: ResourceContent = {
1763
- uri: resourceUri,
1764
- mimeType: MCP_APP_MIME_TYPE,
1765
- text: html,
1766
- };
1767
- if (config.csp) {
1768
- content._meta = {
1769
- ui: { csp: config.csp },
1770
- };
1771
- }
1772
- return content;
1773
- },
1774
- );
1775
-
1776
- registered.push(viewerName);
1777
- }
1778
-
1779
- if (registered.length > 0) {
1780
- this.log(
1781
- `Registered ${registered.length} viewer(s): ${registered.join(", ")}`,
1782
- );
1783
- }
1784
-
1785
- return { registered, skipped };
1786
- }
1787
-
1788
- /**
1789
- * Start the MCP server with stdio transport
1790
- */
1791
- // Keep the established Promise API and rejection semantics even though the
1792
- // v2 serving entry returns its close handle synchronously.
1793
- // deno-lint-ignore require-await
1794
- async start(): Promise<void> {
1795
- // Guard FIRST. Resetting before the guard meant a concurrent start() during
1796
- // stop() cleared `stopping` and rebuilt the store on its way to failing with
1797
- // "already started" — after which a held request produced a live task on a
1798
- // stopped server. `startHttp()` had the order right; this did not.
1799
- if (this.started) {
1800
- throw new Error("Server already started");
1801
- }
1802
-
1803
- // Same reset as the HTTP path. Without it a stdio server that had been stopped
1804
- // kept `stopping` set and its store disposed, so it refused every task for the
1805
- // rest of its life — with nothing to say why.
1806
- this.prepareForStart();
1807
-
1808
- // Build middleware pipeline before connecting transport
1809
- this.buildPipeline();
1810
-
1811
- this.stdioHandle = serveStdio(() => {
1812
- const server = this.createProtocolServer();
1813
- this.activeStdioServer = server;
1814
- server.onclose = () => {
1815
- if (this.activeStdioServer === server) {
1816
- this.activeStdioServer = null;
1817
- }
1818
- };
1819
- return server;
1820
- }, {
1821
- onerror: (error) => {
1822
- this.log(`[ERROR] stdio transport: ${error.message}`);
1823
- },
1824
- });
1825
-
1826
- this.started = true;
1827
-
1828
- const rateLimitInfo = this.options.rateLimit
1829
- ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
1830
- : "";
1831
- const validationInfo = this.options.validateSchema
1832
- ? ", schema validation: on"
1833
- : "";
1834
-
1835
- this.log(
1836
- `Server started (max concurrent: ${
1837
- this.options.maxConcurrent ?? 10
1838
- }, strategy: ${
1839
- this.options.backpressureStrategy ?? "sleep"
1840
- }${rateLimitInfo}${validationInfo})`,
1841
- );
1842
- this.log(`Tools available: ${this.tools.size}`);
1843
- }
1844
-
1845
- /**
1846
- * Restore the invariants a running server relies on.
1847
- *
1848
- * Called by both transports' start paths. `stop()` disposes the task store and
1849
- * leaves it disposed — rebuilding it mid-teardown is what let an in-flight call
1850
- * spawn into a store nobody would drain — so coming back up is where a live one
1851
- * is created.
1852
- */
1853
- private prepareForStart(): void {
1854
- this.stopping = false;
1855
- if (
1856
- this.options.extensions?.[TASKS_EXTENSION_ID] !== undefined &&
1857
- (this.taskStore === null || this.taskStore.isDisposed)
1858
- ) {
1859
- this.taskStore = new TaskStore({
1860
- onNotification: (task) => this.onTaskChanged(task),
1861
- unrefTimer: (timerId) => unrefTimer(timerId as unknown as number),
1862
- });
1863
- }
1864
- }
1865
-
1866
- async stop(): Promise<void> {
1867
- // Synchronous, before any await: a handler settling during shutdown must see
1868
- // this immediately or it can still spawn a task.
1869
- this.stopping = true;
1870
-
1871
- // Release the subsystems whose timers exist from construction, BEFORE the
1872
- // `started` guard: they are created in the constructor, so a server that
1873
- // failed during startup still has them armed, and returning early left them
1874
- // running with no way to reach them again.
1875
- //
1876
- // Disposed and left disposed — NOT replaced. Replacing here opened a window
1877
- // where an in-flight call could spawn into a fresh store while the server was
1878
- // stopping, producing a task that outlived its server. `startHttp()` builds a
1879
- // new store instead, which keeps "a started server has a live store" true
1880
- // without inventing one mid-teardown.
1881
- if (this.taskStore) {
1882
- this.taskStore.drain();
1883
- this.taskStore.dispose();
1884
- }
1885
- if (this.subscriptions) {
1886
- this.subscriptions.shutdown();
1887
- this.subscriptions = null;
1888
- }
1889
-
1890
- if (!this.started) {
1891
- return;
1892
- }
1893
-
1894
- // Stop HTTP server if running
1895
- if (this.httpServer) {
1896
- await this.httpServer.shutdown();
1897
- this.httpServer = null;
1898
- }
1899
-
1900
- if (this.stdioHandle) {
1901
- const handle = this.stdioHandle;
1902
- this.stdioHandle = null;
1903
- await handle.close();
1904
- }
1905
- this.activeStdioServer = null;
1906
- this.started = false;
1907
-
1908
- this.log("Server stopped");
1909
- }
1910
-
1911
- // ============================================
1912
- // HTTP Server Support
1913
- // ============================================
1914
-
1915
- private httpServer: ServeHandle | null = null;
1916
-
1917
- /**
1918
- * Start the MCP server with HTTP transport (Streamable HTTP compatible)
1919
- *
1920
- * This creates an HTTP server that handles MCP JSON-RPC requests.
1921
- * Supports tools/list, tools/call, resources/list, resources/read.
1922
- *
1923
- * @param options - HTTP server options
1924
- * @returns Server instance with shutdown method
1925
- *
1926
- * @example
1927
- * ```typescript
1928
- * const server = new McpApp({ name: "my-server", version: "1.0.0" });
1929
- * server.registerTools(tools, handlers);
1930
- * server.registerResource(resource, handler);
1931
- *
1932
- * const http = await server.startHttp({ port: 3000 });
1933
- * // Server running on http://localhost:3000
1934
- *
1935
- * // Later: await http.shutdown();
1936
- * ```
1937
- */
1938
- async startHttp(
1939
- options: HttpServerOptions,
1940
- ): Promise<
1941
- { shutdown: () => Promise<void>; addr: { hostname: string; port: number } }
1942
- > {
1943
- if (this.started) {
1944
- throw new Error("Server already started");
1945
- }
1946
-
1947
- // Configure auth provider:
1948
- // 1. Programmatic (options.auth.provider) takes priority
1949
- // 2. Otherwise, auto-load from YAML + env vars
1950
- if (this.options.auth?.provider) {
1951
- this.authProvider = this.options.auth.provider;
1952
- this.log(
1953
- `Auth configured: provider=${this.authProvider.constructor.name}`,
1954
- );
1955
- } else {
1956
- const authConfig = await loadAuthConfig();
1957
- if (authConfig) {
1958
- this.authProvider = createAuthProviderFromConfig(authConfig);
1959
- this.log(
1960
- `Auth auto-configured from config: provider=${authConfig.provider}`,
1961
- );
1962
- }
1963
- }
1964
-
1965
- const requireAuth = options.requireAuth ?? false;
1966
- if (requireAuth && !this.authProvider) {
1967
- throw new Error(
1968
- "[McpApp] HTTP auth is required (requireAuth=true) but no auth provider is configured.",
1969
- );
1970
- }
1971
- if (!this.authProvider && !requireAuth) {
1972
- this.log(
1973
- "[WARN] HTTP auth is disabled. Set requireAuth=true or configure auth for production deployments.",
1974
- );
1975
- }
1976
-
1977
- // Build middleware pipeline (includes auth if configured)
1978
- this.buildPipeline();
1979
-
1980
- const hostname = options.hostname ?? "0.0.0.0";
1981
- this.prepareForStart();
1982
-
1983
- if (this.subscriptions === null) {
1984
- this.subscriptions = new SubscriptionRegistry({
1985
- serverInfo: { name: this.options.name, version: this.options.version },
1986
- });
1987
- this.subscriptions.startKeepAlive(
1988
- setInterval,
1989
- (id) => unrefTimer(id as unknown as number),
1990
- );
1991
- }
1992
-
1993
- const enableCors = options.cors ?? true;
1994
- const corsOrigins = options.corsOrigins ?? "*";
1995
- const maxBodyBytes = options.maxBodyBytes === null
1996
- ? null
1997
- : (options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1998
- const httpRateLimit = options.ipRateLimit;
1999
- const httpRateLimiter = httpRateLimit
2000
- ? new RateLimiter({
2001
- maxRequests: httpRateLimit.maxRequests,
2002
- windowMs: httpRateLimit.windowMs,
2003
- })
2004
- : null;
2005
-
2006
- // Create Hono app
2007
- const app = new Hono();
2008
-
2009
- const isWildcardCors = corsOrigins === "*" ||
2010
- (Array.isArray(corsOrigins) && corsOrigins.includes("*"));
2011
- if (enableCors && isWildcardCors) {
2012
- this.log(
2013
- "[WARN] CORS wildcard origin ('*') is active. " +
2014
- "Use corsOrigins: ['https://your-app.example.com'] in production.",
2015
- );
2016
- }
2017
-
2018
- // CORS middleware
2019
- if (enableCors) {
2020
- app.use(
2021
- "*",
2022
- cors({
2023
- origin: corsOrigins,
2024
- allowMethods: ["GET", "POST", "DELETE", "OPTIONS"],
2025
- allowHeaders: [
2026
- "Content-Type",
2027
- "Accept",
2028
- "Authorization",
2029
- "mcp-protocol-version",
2030
- // Spec 2026-07-28 request-metadata headers. Omitting them broke
2031
- // browser clients outright: the preflight rejects the actual request
2032
- // before the server ever sees it, so a conforming client could not
2033
- // send the headers the server now requires.
2034
- "mcp-method",
2035
- "mcp-name",
2036
- // `Mcp-Param-*` names are defined by the tools themselves, so the
2037
- // allowlist is derived from the registered annotations rather than
2038
- // opened to `*` — which would also widen it for every other header.
2039
- //
2040
- // Known limitation: a tool registered via `registerToolLive` AFTER
2041
- // startHttp() is not reflected here. Register annotated tools before
2042
- // starting, or widen `corsOrigins`/headers deliberately.
2043
- ...[...this.mirroredParams.values()]
2044
- .flat()
2045
- .map((param) => `mcp-param-${param.headerName.toLowerCase()}`),
2046
- ],
2047
- exposeHeaders: [
2048
- "Content-Length",
2049
- "mcp-protocol-version",
2050
- ],
2051
- maxAge: 600,
2052
- }),
2053
- );
2054
- }
2055
-
2056
- // Health check endpoint
2057
- app.get(
2058
- "/health",
2059
- (c) =>
2060
- c.json({
2061
- status: "ok",
2062
- server: this.options.name,
2063
- version: this.options.version,
2064
- }),
2065
- );
2066
-
2067
- // Prometheus metrics endpoint
2068
- app.get("/metrics", (_c) => {
2069
- // Update gauges before serving
2070
- const qm = this.requestQueue.getMetrics();
2071
- this.serverMetrics.setGauges({
2072
- activeRequests: qm.inFlight,
2073
- queuedRequests: qm.queued,
2074
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
2075
- });
2076
- return new Response(this.serverMetrics.toPrometheusFormat(), {
2077
- headers: { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" },
2078
- });
2079
- });
2080
-
2081
- // RFC 9728 Protected Resource Metadata endpoint
2082
- app.get("/.well-known/oauth-protected-resource", (c) => {
2083
- if (!this.authProvider) {
2084
- return c.text("Not Found", 404);
2085
- }
2086
- return c.json(this.authProvider.getResourceMetadata());
2087
- });
2088
-
2089
- // Auth verification helper for HTTP endpoints.
2090
- // Returns an error Response if auth is required but token is missing/invalid.
2091
- // Returns null if auth passes or is not configured.
2092
- //
2093
- // 0.15.0+: provider's getResourceMetadata() always returns a valid
2094
- // absolute URL in resource_metadata_url (type-enforced). We used to
2095
- // derive this URL from `metadata.resource` by string concatenation
2096
- // (see `buildMetadataUrl` helper, removed 0.15.0), which produced a
2097
- // broken URL when `resource` was an opaque URI per RFC 9728 § 2
2098
- // (e.g., an OIDC project ID used as JWT audience).
2099
- // Auth verification for HTTP endpoints. Returns the verified AuthInfo
2100
- // on success, or an error Response if auth fails. The caller stores
2101
- // the AuthInfo so the middleware pipeline can skip re-verification.
2102
- const verifyHttpAuth = async (
2103
- request: Request,
2104
- ): Promise<{ authInfo: AuthInfo } | { denied: Response }> => {
2105
- if (!this.authProvider) return { authInfo: {} as AuthInfo };
2106
-
2107
- const token = extractBearerToken(request);
2108
- if (!token) {
2109
- const metadata = this.authProvider.getResourceMetadata();
2110
- return {
2111
- denied: createUnauthorizedResponse(
2112
- metadata.resource_metadata_url,
2113
- "missing_token",
2114
- "Authorization header with Bearer token required",
2115
- ),
2116
- };
2117
- }
2118
-
2119
- const authInfo = await this.authProvider.verifyToken(token);
2120
- if (!authInfo) {
2121
- const metadata = this.authProvider.getResourceMetadata();
2122
- return {
2123
- denied: createUnauthorizedResponse(
2124
- metadata.resource_metadata_url,
2125
- "invalid_token",
2126
- "Invalid or expired token",
2127
- ),
2128
- };
2129
- }
2130
-
2131
- return { authInfo: freezeAuthInfo(authInfo) };
2132
- };
2133
-
2134
- const checkHttpRateLimit = async (
2135
- request: Request,
2136
- sessionId?: string,
2137
- overrideHeaders?: Headers, // Track A: sanitized headers for stateless mode (no mcp-session-id)
2138
- ): Promise<{ allowed: boolean; retryAfterMs: number }> => {
2139
- if (!httpRateLimiter || !httpRateLimit) {
2140
- return { allowed: true, retryAfterMs: 0 };
2141
- }
2142
-
2143
- const ip = getClientIpFromHeaders(request.headers);
2144
- const context: HttpRateLimitContext = {
2145
- ip,
2146
- method: request.method,
2147
- path: new URL(request.url).pathname,
2148
- headers: overrideHeaders ?? request.headers,
2149
- sessionId,
2150
- };
2151
- const key = httpRateLimit.keyExtractor?.(context) ?? ip;
2152
- const behavior = httpRateLimit.onLimitExceeded ?? "reject";
2153
-
2154
- if (behavior === "wait") {
2155
- try {
2156
- await httpRateLimiter.waitForSlot(key);
2157
- return { allowed: true, retryAfterMs: 0 };
2158
- } catch {
2159
- return {
2160
- allowed: false,
2161
- retryAfterMs: Math.max(
2162
- httpRateLimiter.getTimeUntilSlot(key),
2163
- httpRateLimit.windowMs,
2164
- ),
2165
- };
2166
- }
2167
- }
2168
-
2169
- if (!httpRateLimiter.checkLimit(key)) {
2170
- return {
2171
- allowed: false,
2172
- retryAfterMs: httpRateLimiter.getTimeUntilSlot(key),
2173
- };
2174
- }
2175
-
2176
- return { allowed: true, retryAfterMs: 0 };
2177
- };
2178
-
2179
- // Custom routes (registered before MCP catch-all)
2180
- if (options.customRoutes) {
2181
- for (const route of options.customRoutes) {
2182
- app[route.method](route.path, (c) => route.handler(c.req.raw));
2183
- }
2184
- }
2185
-
2186
- // Legacy verbs from 2025-03-26..2025-11-25: GET opened a standalone SSE
2187
- // stream, DELETE terminated a session. Neither exists in this revision, and
2188
- // the spec says a server supporting only this revision SHOULD answer both
2189
- // with 405 — not 404, which an older client would read as "no MCP endpoint
2190
- // here" and use to fall back to the deprecated HTTP+SSE transport.
2191
- // Use subscriptions/listen for server-initiated notifications.
2192
- // deno-lint-ignore no-explicit-any
2193
- const methodNotAllowed = (c: any) => c.text("Method Not Allowed", 405);
2194
- app.get("/mcp", methodNotAllowed);
2195
- app.get("/", methodNotAllowed);
2196
- app.delete("/mcp", methodNotAllowed);
2197
- app.delete("/", methodNotAllowed);
2198
-
2199
- // MCP endpoint - POST handles JSON-RPC
2200
- const handleMcpPost = async (
2201
- c: {
2202
- req: {
2203
- json: () => Promise<unknown>;
2204
- raw: Request;
2205
- header: (name: string) => string | undefined;
2206
- };
2207
- json: (data: unknown, status?: number) => Response;
2208
- /** Accumulate a response header (Hono Context API — Track A: MCP-Protocol-Version) */
2209
- header: (name: string, value: string) => void;
2210
- },
2211
- ) => {
2212
- let requestId: string | number | null = null;
2213
- try {
2214
- // Strip mcp-session-id from headers passed to rate-limit context
2215
- // so a keyExtractor cannot use session IDs to bypass IP-level limits.
2216
- const rlHeaders = (() => {
2217
- const h = new Headers(c.req.raw.headers);
2218
- h.delete("mcp-session-id");
2219
- return h;
2220
- })();
2221
- const rateLimit = await checkHttpRateLimit(
2222
- c.req.raw,
2223
- undefined,
2224
- rlHeaders,
2225
- );
2226
- if (!rateLimit.allowed) {
2227
- const retryAfter = Math.max(
2228
- 1,
2229
- Math.ceil(rateLimit.retryAfterMs / 1000),
2230
- );
2231
- return jsonRpcResponse(
2232
- {
2233
- jsonrpc: "2.0",
2234
- id: null,
2235
- error: {
2236
- code: -32000,
2237
- message: `Rate limit exceeded. Retry after ${retryAfter}s`,
2238
- },
2239
- },
2240
- 429,
2241
- { "Retry-After": retryAfter.toString() },
2242
- );
2243
- }
2244
-
2245
- let body: {
2246
- id?: string | number;
2247
- method?: string;
2248
- params?: Record<string, unknown>;
2249
- };
2250
- try {
2251
- const bodyBytes = await readBodyWithLimit(c.req.raw, maxBodyBytes);
2252
- const bodyText = new TextDecoder().decode(bodyBytes);
2253
- const parsed = JSON.parse(bodyText);
2254
- if (!parsed || typeof parsed !== "object") {
2255
- throw new Error("Invalid JSON payload");
2256
- }
2257
- body = parsed as {
2258
- id?: string | number;
2259
- method?: string;
2260
- params?: Record<string, unknown>;
2261
- };
2262
- } catch (error) {
2263
- if (error instanceof BodyTooLargeError) {
2264
- return jsonRpcResponse({
2265
- jsonrpc: "2.0",
2266
- id: null,
2267
- error: { code: -32000, message: error.message },
2268
- }, 413);
2269
- }
2270
- throw error;
2271
- }
2272
-
2273
- const { id, method, params } = body;
2274
- requestId = id ?? null;
2275
-
2276
- // Auth gate: when requireAuth is configured, ALL requests (including
2277
- // initialize) must be authenticated per MCP spec 2025-06-18. The 401
2278
- // response with WWW-Authenticate triggers OAuth discovery in MCP
2279
- // clients (Claude.ai, Cursor). Without this, clients receive a 200 on
2280
- // initialize and never attempt the OAuth/DCR flow.
2281
- let httpAuthInfo: AuthInfo | undefined;
2282
- if (this.authProvider) {
2283
- const authResult = await verifyHttpAuth(c.req.raw);
2284
- if ("denied" in authResult) return authResult.denied;
2285
- httpAuthInfo = authResult.authInfo;
2286
- }
2287
-
2288
- // The `MCP-Protocol-Version` header is REQUIRED on every POST, and its
2289
- // absence is a header-validation failure — not a malformed body. The
2290
- // spec is explicit: "Validation failure conditions include: A required
2291
- // standard header (MCP-Protocol-Version, Mcp-Method, Mcp-Name) is
2292
- // missing", answered with 400 + -32020 (HeaderMismatch).
2293
- //
2294
- // This has to run BEFORE the `_meta` version check below, because a
2295
- // legacy client sends neither and would otherwise get -32602 for a
2296
- // missing body field when the primary violation is the missing header.
2297
- // A client reading -32602 looks for the wrong fix.
2298
- //
2299
- // Notifications are exempt: the revision leaves header requirements for
2300
- // notification POSTs undefined, so demanding one there invents a rule.
2301
- if (
2302
- id !== undefined && c.req.header("MCP-Protocol-Version") === undefined
2303
- ) {
2304
- return jsonRpcResponse(
2305
- {
2306
- jsonrpc: "2.0",
2307
- id,
2308
- error: {
2309
- code: MCP_HEADER_MISMATCH,
2310
- message:
2311
- "Missing required header 'MCP-Protocol-Version'. It must be present and match params._meta['io.modelcontextprotocol/protocolVersion'].",
2312
- data: {
2313
- problem: "missing_header",
2314
- header: "MCP-Protocol-Version",
2315
- recovery:
2316
- "Send MCP-Protocol-Version: 2026-07-28 and the matching _meta field.",
2317
- },
2318
- },
2319
- },
2320
- 400,
2321
- { "MCP-Protocol-Version": SPEC_2026_07_28 },
2322
- );
2323
- }
2324
-
2325
- // Per-request protocolVersion validation (spec 2026-07-28).
2326
- // Must run BEFORE any method dispatch so every call (not just initialize)
2327
- // is validated. Sets MCP-Protocol-Version header on all subsequent responses
2328
- // via Hono's c.header() accumulation.
2329
- // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
2330
- const clientVersion = isRecord(params) && isRecord(params["_meta"])
2331
- ? params["_meta"][STATELESS_PROTO_KEY]
2332
- : undefined;
2333
-
2334
- // `clientCapabilities` is a REQUIRED per-request `_meta` field in the
2335
- // final spec (`clientInfo` is not — it is only SHOULD). A request
2336
- // missing a required field is malformed: -32602 + HTTP 400.
2337
- //
2338
- // Checked after the version so a client on an unsupported revision
2339
- // gets the clearer version error first.
2340
- // Must be an OBJECT, not merely present. `!== undefined` accepted
2341
- // `null`, a scalar or an array, which then reached the handler as a
2342
- // supposed ClientCapabilities and failed later as -32603 — an internal
2343
- // error for what is plainly a malformed request.
2344
- const capabilitiesValid = isRecord(params) &&
2345
- isRecord(params["_meta"]) &&
2346
- isRecord(params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY]);
2347
-
2348
- if (typeof clientVersion !== "string") {
2349
- // Header uses fallback version — no negotiated version available yet
2350
- return jsonRpcResponse(
2351
- {
2352
- jsonrpc: "2.0",
2353
- id,
2354
- error: {
2355
- code: JSONRPC_INVALID_PARAMS,
2356
- message: `Missing required field '${STATELESS_PROTO_KEY}'`,
2357
- },
2358
- },
2359
- 400,
2360
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2361
- );
2362
- }
2363
-
2364
- if (!STATELESS_SUPPORTED_VERSIONS.includes(clientVersion)) {
2365
- // AX: data carries machine-readable supported/requested for agent recovery
2366
- return jsonRpcResponse(
2367
- {
2368
- jsonrpc: "2.0",
2369
- id,
2370
- error: {
2371
- code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
2372
- message: `Unsupported protocolVersion: "${clientVersion}"`,
2373
- data: {
2374
- supported: [...STATELESS_SUPPORTED_VERSIONS],
2375
- requested: clientVersion,
2376
- },
2377
- },
2378
- },
2379
- 400,
2380
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2381
- );
2382
- }
2383
-
2384
- if (!capabilitiesValid) {
2385
- return jsonRpcResponse(
2386
- {
2387
- jsonrpc: "2.0",
2388
- id,
2389
- error: {
2390
- code: JSONRPC_INVALID_PARAMS,
2391
- message:
2392
- `Missing or malformed field '${STATELESS_CLIENT_CAPABILITIES_KEY}' in params._meta: expected an object`,
2393
- data: {
2394
- problem: "missing_field",
2395
- bodyField:
2396
- `params._meta['${STATELESS_CLIENT_CAPABILITIES_KEY}']`,
2397
- recovery:
2398
- "Send a ClientCapabilities object; `{}` is valid and means no capabilities declared.",
2399
- },
2400
- },
2401
- },
2402
- 400,
2403
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2404
- );
2405
- }
2406
-
2407
- // Track C: request-metadata headers (SEP-2243).
2408
- //
2409
- // Notifications are exempt: the revision explicitly leaves header
2410
- // requirements for notification POSTs undefined, so a missing
2411
- // `Mcp-Method` there is not a violation to invent.
2412
- if (id !== undefined) {
2413
- const validation = validateRequestHeaders({
2414
- getHeader: (name) => c.req.header(name),
2415
- method: typeof method === "string" ? method : "",
2416
- params: isRecord(params) ? params : undefined,
2417
- bodyProtocolVersion: clientVersion,
2418
- mirroredParams: typeof params?.name === "string"
2419
- ? this.mirroredParams.get(params.name)
2420
- : undefined,
2421
- });
2422
- if (!validation.ok) {
2423
- return jsonRpcResponse(
2424
- {
2425
- jsonrpc: "2.0",
2426
- id,
2427
- error: {
2428
- code: MCP_HEADER_MISMATCH,
2429
- message: validation.message,
2430
- // AX: the caller has to fix the request, so what to fix
2431
- // travels as data. `problem` is an enum to switch on,
2432
- // `recovery` is one concrete action — neither requires
2433
- // parsing the English message.
2434
- data: validation.detail,
2435
- },
2436
- },
2437
- 400,
2438
- { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
2439
- );
2440
- }
2441
- }
2442
-
2443
- const statelessVersion: string = clientVersion;
2444
- // Spec 2026-07-28: echo negotiated version in every response header.
2445
- // c.header() accumulates headers — all subsequent c.json() calls inherit it.
2446
- c.header("MCP-Protocol-Version", statelessVersion);
2447
-
2448
- if (method === "server/discover") {
2449
- return c.json({
2450
- jsonrpc: "2.0",
2451
- id,
2452
- result: this.buildDiscoverResult(),
2453
- });
2454
- }
2455
-
2456
- // Initialize — respond without creating a session or emitting Mcp-Session-Id.
2457
- // statelessVersion is guaranteed defined here (version check above returned early otherwise).
2458
- if (method === "initialize") {
2459
- return c.json({
2460
- jsonrpc: "2.0",
2461
- id,
2462
- result: this.stampResult({
2463
- protocolVersion: statelessVersion,
2464
- capabilities: this.buildServerCapabilities(),
2465
- serverInfo: {
2466
- name: this.options.name,
2467
- version: this.options.version,
2468
- },
2469
- ...(this.options.instructions
2470
- ? { instructions: this.options.instructions }
2471
- : {}),
2472
- }, statelessVersion),
2473
- });
2474
- // Note: c.json() inherits MCP-Protocol-Version header set above.
2475
- // No Mcp-Session-Id header emitted — stateless by design.
2476
- }
2477
-
2478
- // Tools call (delegates to middleware pipeline, which handles auth internally)
2479
- if (method === "tools/call") {
2480
- // Dispatch by method rather than the truthiness of `name`. An empty
2481
- // string can be represented faithfully by Mcp-Name, but it is not a
2482
- // usable tool name and must be InvalidParams rather than an apparent
2483
- // method that this server does not implement.
2484
- const toolParams = isRecord(params) ? params : undefined;
2485
- if (
2486
- toolParams === undefined ||
2487
- typeof toolParams["name"] !== "string" ||
2488
- toolParams["name"].length === 0
2489
- ) {
2490
- return jsonRpcResponse(
2491
- {
2492
- jsonrpc: "2.0",
2493
- id,
2494
- error: {
2495
- code: JSONRPC_INVALID_PARAMS,
2496
- message:
2497
- "tools/call requires a non-empty string 'name' parameter",
2498
- },
2499
- },
2500
- 400,
2501
- );
2502
- }
2503
- const toolName = toolParams["name"];
2504
- const args = (toolParams["arguments"] as Record<string, unknown>) ||
2505
- {};
2506
- const statelessClientMeta:
2507
- | StatelessClientMeta
2508
- | undefined = isRecord(params) && isRecord(params["_meta"])
2509
- ? {
2510
- clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
2511
- | Implementation
2512
- | undefined,
2513
- clientCapabilities: params["_meta"][
2514
- STATELESS_CLIENT_CAPABILITIES_KEY
2515
- ] as ClientCapabilities | undefined,
2516
- logLevel: readLogLevel(params["_meta"]),
2517
- ...readTraceContext(params["_meta"]),
2518
- }
2519
- : undefined;
2520
-
2521
- // MRTR retry fields live in `params` directly — siblings of `_meta`,
2522
- // not members of it, unlike every other per-request field. Reading them
2523
- // from `_meta` yields a silent undefined even when the client sent them.
2524
- //
2525
- // MRTR is always enabled on 2026-07-28 (the only supported version).
2526
- const mrtrEnabled = true;
2527
-
2528
- // Digest of the arguments AS RECEIVED, taken before the middleware
2529
- // pipeline runs. Re-deriving it at seal time would hash whatever the
2530
- // pipeline left in `args` — validation coercion, defaults, redaction —
2531
- // so a client replaying the request byte-for-byte would fail
2532
- // `wrong_params` through no fault of its own.
2533
- const ingressDigest = mrtrEnabled
2534
- ? await paramsDigest({ arguments: args, name: toolName })
2535
- : "";
2536
- // A scalar or array `inputResponses` was silently dropped, so a client
2537
- // sending the wrong shape saw its answers ignored and the same
2538
- // InputRequiredResult come back, with nothing to indicate why.
2539
- const rawResponses = mrtrEnabled && isRecord(params)
2540
- ? params["inputResponses"]
2541
- : undefined;
2542
- if (rawResponses !== undefined && !isRecord(rawResponses)) {
2543
- return jsonRpcResponse(
2544
- {
2545
- jsonrpc: "2.0",
2546
- id,
2547
- error: {
2548
- code: JSONRPC_INVALID_PARAMS,
2549
- message:
2550
- "inputResponses must be an object keyed by the ids from inputRequests",
2551
- data: {
2552
- problem: "malformed_field",
2553
- bodyField: "params.inputResponses",
2554
- recovery:
2555
- "Send an object whose keys match the inputRequests keys the server issued.",
2556
- },
2557
- },
2558
- },
2559
- 400,
2560
- {
2561
- "MCP-Protocol-Version": statelessVersion,
2562
- },
2563
- );
2564
- }
2565
- const echoedResponses = isRecord(rawResponses)
2566
- ? rawResponses
2567
- : undefined;
2568
- const echoedState = mrtrEnabled && isRecord(params) &&
2569
- typeof params["requestState"] === "string"
2570
- ? params["requestState"]
2571
- : undefined;
2572
-
2573
- // A retry carrying answers but no token cannot be verified, and the
2574
- // server always issues a token when it has a key. So this combination
2575
- // is either a confused client or an attempt to inject answers past the
2576
- // verification gate — refuse it rather than forwarding unverified
2577
- // responses to the handler.
2578
- // Resolved only when MRTR is actually in play. Resolving on every 2026
2579
- // tools/call meant a transient key-import failure also broke ordinary
2580
- // tools that never touch MRTR.
2581
- const needsKey = mrtrEnabled &&
2582
- (echoedResponses !== undefined || echoedState !== undefined);
2583
- const guardKey = needsKey
2584
- ? await this.getMrtrKeySafe(
2585
- id,
2586
- statelessVersion,
2587
- )
2588
- : { key: null as CryptoKey | null };
2589
- if ("error" in guardKey) return guardKey.error;
2590
- // Only a signed retry needs an authenticated principal. Ordinary
2591
- // calls and explicitly unprotected state retain their prior behavior.
2592
- let retryPrincipal = MRTR_NO_AUTH_PRINCIPAL;
2593
- if (echoedState !== undefined && guardKey.key !== null) {
2594
- const principal = callerPrincipal(httpAuthInfo);
2595
- if (principal === null) {
2596
- return noPrincipalError(id, statelessVersion);
2597
- }
2598
- retryPrincipal = principal;
2599
- }
2600
-
2601
- const retryOutcome = await guardMrtrRetry({
2602
- ...(echoedResponses !== undefined
2603
- ? { inputResponses: echoedResponses }
2604
- : {}),
2605
- ...(echoedState !== undefined ? { requestState: echoedState } : {}),
2606
- key: guardKey.key,
2607
- replayStore: this.mrtrReplayStore,
2608
- bindings: {
2609
- principal: retryPrincipal,
2610
- method: "tools/call",
2611
- paramsDigest: ingressDigest,
2612
- },
2613
- });
2614
- if (retryOutcome.kind === "missing_state") {
2615
- return jsonRpcResponse(
2616
- {
2617
- jsonrpc: "2.0",
2618
- id,
2619
- error: {
2620
- code: JSONRPC_INVALID_PARAMS,
2621
- message:
2622
- "inputResponses supplied without the requestState issued with them",
2623
- data: {
2624
- problem: "missing_request_state",
2625
- recovery:
2626
- "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
2627
- },
2628
- },
2629
- },
2630
- 400,
2631
- { "MCP-Protocol-Version": statelessVersion },
2632
- );
2633
- }
2634
- if (retryOutcome.kind === "invalid_state") {
2635
- return jsonRpcResponse(
2636
- {
2637
- jsonrpc: "2.0",
2638
- id,
2639
- error: {
2640
- code: JSONRPC_INVALID_PARAMS,
2641
- message: `Invalid requestState: ${retryOutcome.reason}`,
2642
- data: { reason: retryOutcome.reason },
2643
- },
2644
- },
2645
- 400,
2646
- { "MCP-Protocol-Version": statelessVersion },
2647
- );
2648
- }
2649
- if (retryOutcome.kind === "replay_store_unavailable") {
2650
- if (retryOutcome.reason === "consume_failed") {
2651
- this.log(
2652
- "[WARN] MRTR replay store unavailable; retry rejected before handler",
2653
- );
2654
- }
2655
- return jsonRpcResponse(
2656
- {
2657
- jsonrpc: "2.0",
2658
- id,
2659
- error: {
2660
- code: ErrorCode.InternalError,
2661
- message: "MRTR replay protection is unavailable",
2662
- data: {
2663
- problem: "mrtr_replay_store_unavailable",
2664
- recovery: retryOutcome.reason === "missing"
2665
- ? "Configure mrtr.signingKey with a working replay store and retry the full interaction."
2666
- : "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2667
- },
2668
- },
2669
- },
2670
- 500,
2671
- { "MCP-Protocol-Version": statelessVersion },
2672
- );
2673
- }
2674
- if (retryOutcome.kind === "replayed") {
2675
- return jsonRpcResponse(
2676
- {
2677
- jsonrpc: "2.0",
2678
- id,
2679
- error: {
2680
- code: JSONRPC_INVALID_PARAMS,
2681
- message: "Invalid requestState: replayed",
2682
- data: { reason: "replayed" },
2683
- },
2684
- },
2685
- 400,
2686
- { "MCP-Protocol-Version": statelessVersion },
2687
- );
2688
- }
2689
- const retryVerified = retryOutcome.retryVerified;
2690
-
2691
- try {
2692
- const result = await this.executeToolCall(
2693
- toolName,
2694
- args,
2695
- c.req.raw,
2696
- undefined,
2697
- httpAuthInfo,
2698
- statelessClientMeta,
2699
- {
2700
- ...(echoedResponses !== undefined
2701
- ? { inputResponses: echoedResponses }
2702
- : {}),
2703
- ...(retryVerified !== undefined ? { retryVerified } : {}),
2704
- },
2705
- );
2706
- // MRTR: the handler is asking the client for input rather than
2707
- // returning a result. Checked BEFORE the task branch and before
2708
- // stampResult, which would overwrite resultType with "complete".
2709
- if (
2710
- mrtrEnabled && isRecord(result) &&
2711
- result["resultType"] === "input_required"
2712
- ) {
2713
- const sealPrincipal = callerPrincipal(httpAuthInfo);
2714
- if (sealPrincipal === null) {
2715
- return noPrincipalError(
2716
- id,
2717
- statelessVersion,
2718
- );
2719
- }
2720
- const built = await this.buildInputRequiredResult(
2721
- result as unknown as InputRequiredSignal,
2722
- {
2723
- clientCapabilities: statelessClientMeta?.clientCapabilities,
2724
- principal: sealPrincipal,
2725
- method: "tools/call",
2726
- paramsDigest: ingressDigest,
2727
- },
2728
- );
2729
- if (!built.ok) {
2730
- return jsonRpcResponse(
2731
- {
2732
- jsonrpc: "2.0",
2733
- id,
2734
- error: {
2735
- code: built.code,
2736
- message: built.message,
2737
- ...(built.data !== undefined ? { data: built.data } : {}),
2738
- },
2739
- },
2740
- // Status follows the code: an InternalError is a server fault
2741
- // (500), a capability or shape problem is the caller's (400).
2742
- // Flattening both to 400 told a client to fix a request that a
2743
- // misconfigured signing key had broken — and the sibling ingress
2744
- // path already answered 500 for exactly that.
2745
- built.code === ErrorCode.InternalError ? 500 : 400,
2746
- {
2747
- "MCP-Protocol-Version": statelessVersion,
2748
- },
2749
- );
2750
- }
2751
- return c.json({ jsonrpc: "2.0", id, result: built.result });
2752
- }
2753
-
2754
- // Tasks extension: the handler asked for a task handle instead of
2755
- // a synchronous result.
2756
- if (isAsyncTaskDescriptor(result)) {
2757
- const guard = this.requireTasksCapability(
2758
- statelessClientMeta?.clientCapabilities,
2759
- id,
2760
- );
2761
- if (guard) return guard;
2762
-
2763
- // Owner binding: the spec requires an authorization check on every
2764
- // task-related request, and a task id alone is only one line of
2765
- // defence.
2766
- if (this.stopping || this.taskStore === null) {
2767
- return jsonRpcResponse(
2768
- {
2769
- jsonrpc: "2.0",
2770
- id,
2771
- error: {
2772
- code: ErrorCode.InternalError,
2773
- message:
2774
- "Server is shutting down; no new tasks are accepted.",
2775
- data: {
2776
- problem: "server_stopping",
2777
- recovery: "Retry against a running instance.",
2778
- },
2779
- },
2780
- },
2781
- 503,
2782
- {
2783
- "MCP-Protocol-Version": statelessVersion,
2784
- },
2785
- );
2786
- }
2787
- const ownerPrincipal = callerPrincipal(httpAuthInfo);
2788
- if (ownerPrincipal === null) {
2789
- return noPrincipalError(
2790
- id,
2791
- statelessVersion,
2792
- );
2793
- }
2794
- const owner = await taskOwnerKeyFor(
2795
- this.options,
2796
- httpAuthInfo,
2797
- c.req.raw,
2798
- ownerPrincipal,
2799
- );
2800
- if (owner === null) {
2801
- return noOwnerKeyError(
2802
- id,
2803
- statelessVersion,
2804
- );
2805
- }
2806
- // Re-checked, and wrapped: the guard above sits before two awaits
2807
- // (the principal lookup and the async owner hook), so shutdown can
2808
- // begin in between. Without this, spawn()'s post-disposal throw
2809
- // would escape to the POST-level catch and be reported as -32700
2810
- // "Parse error".
2811
- let task;
2812
- try {
2813
- task = this.taskStore.spawn(
2814
- result,
2815
- owner,
2816
- // Same conversion the synchronous path uses, so a handler's
2817
- // return value produces an identical result either way.
2818
- (raw) => this.buildToolCallResult(toolName, raw),
2819
- );
2820
- } catch (spawnError) {
2821
- // Narrowed to the actual shutdown condition. A blanket catch
2822
- // reported a legitimate throw from the handler's own task setup as
2823
- // "server is shutting down" — a diagnosis that sends the reader to
2824
- // look at the wrong thing entirely, on a perfectly healthy server.
2825
- if (this.stopping || this.taskStore.isDisposed) {
2826
- return jsonRpcResponse(
2827
- {
2828
- jsonrpc: "2.0",
2829
- id,
2830
- error: {
2831
- code: ErrorCode.InternalError,
2832
- message:
2833
- "Server is shutting down; no new tasks are accepted.",
2834
- data: {
2835
- problem: "server_stopping",
2836
- recovery: "Retry against a running instance.",
2837
- },
2838
- },
2839
- },
2840
- 503,
2841
- {
2842
- "MCP-Protocol-Version": statelessVersion,
2843
- },
2844
- );
2845
- }
2846
- // A real failure: let the tool error path report it as such.
2847
- throw spawnError;
2848
- }
2849
- return c.json({
2850
- jsonrpc: "2.0",
2851
- id,
2852
- // NOT stampResult(): that writes resultType "complete", and a
2853
- // CreateTaskResult carries "task". Its fields are flat on the
2854
- // result, not nested under a `task` key.
2855
- //
2856
- // Note the asymmetry with tasks/get below, which DOES carry
2857
- // "complete" — that is an ordinary RPC response which happens to
2858
- // describe a task. The spec states this distinction three times;
2859
- // conflating them is the likeliest mistake here.
2860
- result: this.stampResult(
2861
- { ...task },
2862
- statelessVersion,
2863
- "task",
2864
- ),
2865
- });
2866
- }
2867
-
2868
- return c.json({
2869
- jsonrpc: "2.0",
2870
- id,
2871
- result: this.stampResult(
2872
- this.buildToolCallResult(toolName, result),
2873
- statelessVersion,
2874
- ),
2875
- });
2876
- } catch (error) {
2877
- // Handle AuthError with proper HTTP status codes
2878
- if (error instanceof AuthError) {
2879
- if (
2880
- error.code === "missing_token" || error.code === "invalid_token"
2881
- ) {
2882
- return createUnauthorizedResponse(
2883
- error.resourceMetadataUrl,
2884
- error.code,
2885
- error.message,
2886
- );
2887
- }
2888
- if (error.code === "insufficient_scope") {
2889
- return createForbiddenResponse(
2890
- error.requiredScopes ?? [],
2891
- error.resourceMetadataUrl,
2892
- );
2893
- }
2894
- }
2895
-
2896
- // Delegate to centralized error handler
2897
- try {
2898
- const isErrorResult = this.handleToolError(error, toolName);
2899
- return c.json({
2900
- jsonrpc: "2.0",
2901
- id,
2902
- // An `isError: true` tool result is still a completed JSON-RPC
2903
- // result, so it carries `resultType: "complete"`. Only MRTR
2904
- // interim results (Track B) use `"input_required"`.
2905
- result: this.stampResult(
2906
- isErrorResult as Record<string, unknown>,
2907
- statelessVersion,
2908
- ),
2909
- });
2910
- } catch (rethrown) {
2911
- this.log(
2912
- `Error executing tool ${toolName}: ${
2913
- rethrown instanceof Error
2914
- ? rethrown.message
2915
- : String(rethrown)
2916
- }`,
2917
- );
2918
- const errorMessage = rethrown instanceof Error
2919
- ? rethrown.message
2920
- : "Tool execution failed";
2921
- const errorCode = errorMessage.startsWith("Unknown tool")
2922
- ? -32602
2923
- : errorMessage.startsWith("Rate limit")
2924
- ? -32000
2925
- : -32603;
2926
- return c.json({
2927
- jsonrpc: "2.0",
2928
- id,
2929
- error: { code: errorCode, message: errorMessage },
2930
- });
2931
- }
2932
- }
2933
- }
2934
-
2935
- // Auth gate already applied above (covers all methods including tools/call, tools/list, etc.)
2936
- // Note: tools/call also runs auth again in the middleware pipeline (createAuthMiddleware),
2937
- // which provides per-tool scope enforcement. The top-level check above is the gate
2938
- // that triggers OAuth discovery (401 with WWW-Authenticate).
2939
-
2940
- // Tools list
2941
- if (method === "tools/list") {
2942
- return c.json({
2943
- jsonrpc: "2.0",
2944
- id,
2945
- result: this.stampResult(
2946
- this.withCacheHints(
2947
- { tools: this.buildToolListing() },
2948
- statelessVersion,
2949
- ),
2950
- statelessVersion,
2951
- ),
2952
- });
2953
- }
2954
-
2955
- // Resources list
2956
- if (method === "resources/list") {
2957
- return c.json({
2958
- jsonrpc: "2.0",
2959
- id,
2960
- result: this.stampResult(
2961
- this.withCacheHints({
2962
- resources: Array.from(this.resources.values()).map((r) =>
2963
- this.toResourceListing(r.resource)
2964
- ),
2965
- }, statelessVersion),
2966
- statelessVersion,
2967
- ),
2968
- });
2969
- }
2970
-
2971
- // Concrete resources only for now. Keep this endpoint explicit rather
2972
- // than falling through to MethodNotFound once resources are advertised.
2973
- if (method === "resources/templates/list") {
2974
- return c.json({
2975
- jsonrpc: "2.0",
2976
- id,
2977
- result: this.stampResult(
2978
- this.withCacheHints({ resourceTemplates: [] }, statelessVersion),
2979
- statelessVersion,
2980
- ),
2981
- });
2982
- }
2983
-
2984
- // Resources read
2985
- if (method === "resources/read") {
2986
- // Dispatch by method, not the truthiness of its routing parameter.
2987
- // `uri: ""` has a valid empty Mcp-Name header representation, but it
2988
- // is not a usable resource URI. Letting it skip this branch turned a
2989
- // malformed resources/read into a misleading -32601 method-not-found.
2990
- const uri = isRecord(params) && typeof params["uri"] === "string" &&
2991
- params["uri"].length > 0
2992
- ? params["uri"]
2993
- : undefined;
2994
- if (uri === undefined) {
2995
- return jsonRpcResponse(
2996
- {
2997
- jsonrpc: "2.0",
2998
- id,
2999
- error: {
3000
- code: JSONRPC_INVALID_PARAMS,
3001
- message:
3002
- "resources/read requires a non-empty string 'uri' parameter",
3003
- },
3004
- },
3005
- 400,
3006
- );
3007
- }
3008
- const resourceInfo = this.resources.get(uri);
3009
-
3010
- if (!resourceInfo) {
3011
- return c.json({
3012
- jsonrpc: "2.0",
3013
- id,
3014
- error: { code: -32602, message: `Resource not found: ${uri}` },
3015
- });
3016
- }
3017
-
3018
- try {
3019
- const finalContent = await this.readResourceForProtocol(
3020
- uri,
3021
- resourceInfo.resource,
3022
- resourceInfo.handler,
3023
- );
3024
- return c.json({
3025
- jsonrpc: "2.0",
3026
- id,
3027
- result: this.stampResult(
3028
- this.withCacheHints(
3029
- { contents: [finalContent] },
3030
- statelessVersion,
3031
- {
3032
- // resources/read is the only cacheable method an MRTR retry
3033
- // can target, so it is the only one that needs this guard.
3034
- isMrtrRetry: isRecord(params) &&
3035
- (params["requestState"] !== undefined ||
3036
- params["inputResponses"] !== undefined),
3037
- },
3038
- ),
3039
- statelessVersion,
3040
- ),
3041
- });
3042
- } catch (error) {
3043
- this.log(
3044
- `Error reading resource ${uri}: ${
3045
- error instanceof Error ? error.message : String(error)
3046
- }`,
3047
- );
3048
- return c.json({
3049
- jsonrpc: "2.0",
3050
- id,
3051
- error: {
3052
- code: -32603,
3053
- message: error instanceof Error
3054
- ? error.message
3055
- : "Resource read failed",
3056
- },
3057
- });
3058
- }
3059
- }
3060
-
3061
- // ── subscriptions/listen (SEP-2575) ──────────────────────────────
3062
- //
3063
- // Replaces the removed HTTP GET stream and resources/subscribe. The
3064
- // response IS the stream: a long-lived SSE body carrying only the
3065
- // notification types the client opted into.
3066
- if (method === "subscriptions/listen" && this.subscriptions !== null) {
3067
- const registry = this.subscriptions;
3068
-
3069
- // A notification-shaped listen makes no sense: the response IS the
3070
- // stream, and the subscription id IS this request's id — with no id
3071
- // there is nothing to correlate notifications to.
3072
- if (id === undefined) {
3073
- return jsonRpcResponse(
3074
- {
3075
- jsonrpc: "2.0",
3076
- id: null,
3077
- error: {
3078
- code: JSONRPC_INVALID_PARAMS,
3079
- message:
3080
- "subscriptions/listen requires a JSON-RPC id: the response is the notification stream, and the id identifies the subscription",
3081
- },
3082
- },
3083
- 400,
3084
- );
3085
- }
3086
- const subscriptionId: string | number = id as string | number;
3087
- // A missing or non-object filter is malformed, not "subscribe to
3088
- // nothing": a client that meant to subscribe would otherwise get a
3089
- // 200 stream that stays silent forever, with no way to tell why.
3090
- if (!isRecord(params) || !isRecord(params["notifications"])) {
3091
- return jsonRpcResponse(
3092
- {
3093
- jsonrpc: "2.0",
3094
- id,
3095
- error: {
3096
- code: JSONRPC_INVALID_PARAMS,
3097
- message:
3098
- "subscriptions/listen requires a 'notifications' object naming the types to receive",
3099
- data: {
3100
- problem: "missing_field",
3101
- bodyField: "params.notifications",
3102
- recovery:
3103
- 'Send params.notifications, e.g. { toolsListChanged: true } or { resourceSubscriptions: ["ui://x"] }.',
3104
- },
3105
- },
3106
- },
3107
- 400,
3108
- );
3109
- }
3110
- const filter = validateSubscriptionFilter(
3111
- params["notifications"] as Record<string, unknown>,
3112
- );
3113
- if (!filter.ok) {
3114
- return jsonRpcResponse(
3115
- {
3116
- jsonrpc: "2.0",
3117
- id,
3118
- error: {
3119
- code: JSONRPC_INVALID_PARAMS,
3120
- message: filter.message,
3121
- data: {
3122
- problem: "malformed_field",
3123
- bodyField: filter.bodyField,
3124
- recovery: filter.recovery,
3125
- },
3126
- },
3127
- },
3128
- 400,
3129
- );
3130
- }
3131
- const requested = filter.filter;
3132
-
3133
- // Recognising `taskIds` is mandatory even though pushing task updates is
3134
- // not: a client that asks for task notifications without declaring the
3135
- // Tasks extension MUST be refused. Accepting it would open a stream that
3136
- // can never deliver, with nothing to say why.
3137
- if (
3138
- Array.isArray(requested.taskIds) && requested.taskIds.length > 0
3139
- ) {
3140
- const guard = this.requireTasksCapability(
3141
- isRecord(params["_meta"])
3142
- ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3143
- | ClientCapabilities
3144
- | undefined
3145
- : undefined,
3146
- id,
3147
- );
3148
- if (guard) return guard;
3149
- }
3150
-
3151
- // Computed ONCE by the registry and reused for both the
3152
- // acknowledgement and the registration. Deriving it independently here
3153
- // is how a client ends up told it subscribed to a set the registry does
3154
- // not actually enforce.
3155
- const agreed = registry.computeAgreedFilter(requested);
3156
-
3157
- let internalKey: string | null = null;
3158
- const stream = new ReadableStream<Uint8Array>({
3159
- start: (controller) => {
3160
- let closed = false;
3161
- const sink: SubscriptionSink = {
3162
- enqueue(chunk) {
3163
- // The cancel() callback fires before unregister(), so a write
3164
- // can race a closed controller on every client disconnect.
3165
- if (closed) return;
3166
- try {
3167
- controller.enqueue(chunk);
3168
- } catch {
3169
- closed = true;
3170
- }
3171
- },
3172
- close() {
3173
- if (closed) return;
3174
- closed = true;
3175
- try {
3176
- controller.close();
3177
- } catch { /* already closed */ }
3178
- },
3179
- get isClosed() {
3180
- return closed;
3181
- },
3182
- };
3183
-
3184
- // The acknowledgement MUST be the first message on the stream, so
3185
- // it is enqueued BEFORE registering — otherwise a fan-out landing
3186
- // in between would precede it.
3187
- sink.enqueue(
3188
- encodeSSEEvent(
3189
- buildAcknowledgedMessage(subscriptionId, agreed),
3190
- ),
3191
- );
3192
- internalKey = registry.register(subscriptionId, agreed, sink);
3193
- },
3194
- cancel: () => {
3195
- // Client closed the stream: that IS the cancellation signal on
3196
- // HTTP, and the server must send nothing further.
3197
- if (internalKey !== null) {
3198
- registry.unregister(internalKey, "client");
3199
- }
3200
- },
3201
- });
3202
-
3203
- return new Response(stream, {
3204
- status: 200,
3205
- headers: {
3206
- "Content-Type": "text/event-stream",
3207
- "Cache-Control": "no-cache",
3208
- Connection: "keep-alive",
3209
- // Tells nginx and friends not to buffer, without which events sit
3210
- // in a proxy until the buffer fills.
3211
- "X-Accel-Buffering": "no",
3212
- "MCP-Protocol-Version": statelessVersion,
3213
- },
3214
- });
3215
- }
3216
-
3217
- // ── Tasks extension (io.modelcontextprotocol/tasks) ──────────────
3218
- //
3219
- // The capability guard repeats on every one of these, not just at task
3220
- // creation: the spec requires the missing-capability error for a
3221
- // non-declaring client issuing tasks/get, tasks/update OR tasks/cancel.
3222
- // Guarding creation alone would still let such a client poll and cancel
3223
- // tasks it could never have been handed.
3224
- // Capability-gated: a non-declaring client must not reach tasks/*.
3225
- // The version gate (STATELESS_SUPPORTED_VERSIONS) upstream of this block
3226
- // already rejects any peer running a pre-2026 protocol version.
3227
- if (
3228
- this.taskStore !== null &&
3229
- (method === "tasks/get" || method === "tasks/update" ||
3230
- method === "tasks/cancel")
3231
- ) {
3232
- // These are requests, never notifications. Without an id they would
3233
- // otherwise slip past header validation — which exempts notifications —
3234
- // then mutate task state and answer with an id-less, malformed
3235
- // JSON-RPC response.
3236
- if (id === undefined) {
3237
- return jsonRpcResponse(
3238
- {
3239
- jsonrpc: "2.0",
3240
- id: null,
3241
- error: {
3242
- code: JSONRPC_INVALID_PARAMS,
3243
- message: `${method} is a request and requires a JSON-RPC id`,
3244
- data: {
3245
- problem: "missing_field",
3246
- bodyField: "id",
3247
- recovery:
3248
- "Send the call as a JSON-RPC request with an id, not as a notification.",
3249
- },
3250
- },
3251
- },
3252
- 400,
3253
- );
3254
- }
3255
- const store = this.taskStore;
3256
- const guard = this.requireTasksCapability(
3257
- isRecord(params) && isRecord(params["_meta"])
3258
- ? params["_meta"][STATELESS_CLIENT_CAPABILITIES_KEY] as
3259
- | ClientCapabilities
3260
- | undefined
3261
- : undefined,
3262
- id,
3263
- );
3264
- if (guard) return guard;
3265
-
3266
- const taskId =
3267
- isRecord(params) && typeof params["taskId"] === "string"
3268
- ? params["taskId"]
3269
- : undefined;
3270
- if (taskId === undefined) {
3271
- return jsonRpcResponse(
3272
- {
3273
- jsonrpc: "2.0",
3274
- id,
3275
- error: {
3276
- code: JSONRPC_INVALID_PARAMS,
3277
- message: `${method} requires a string 'taskId' parameter`,
3278
- },
3279
- },
3280
- 400,
3281
- );
3282
- }
3283
-
3284
- const callerBase = callerPrincipal(httpAuthInfo);
3285
- if (callerBase === null) {
3286
- return noPrincipalError(
3287
- id,
3288
- statelessVersion,
3289
- );
3290
- }
3291
- const caller = await taskOwnerKeyFor(
3292
- this.options,
3293
- httpAuthInfo,
3294
- c.req.raw,
3295
- callerBase,
3296
- );
3297
- if (caller === null) {
3298
- return noOwnerKeyError(
3299
- id,
3300
- statelessVersion,
3301
- );
3302
- }
3303
-
3304
- if (method === "tasks/get") {
3305
- const task = store.get(taskId, caller);
3306
- if (task === null) {
3307
- return c.json({
3308
- jsonrpc: "2.0",
3309
- id,
3310
- error: {
3311
- code: JSONRPC_INVALID_PARAMS,
3312
- message: `Unknown taskId: ${taskId}`,
3313
- },
3314
- });
3315
- }
3316
- // "complete", not "task" — see the note at task creation.
3317
- return c.json({
3318
- jsonrpc: "2.0",
3319
- id,
3320
- result: this.stampResult({ ...task }, statelessVersion),
3321
- });
3322
- }
3323
-
3324
- if (method === "tasks/update") {
3325
- // Spec field name is `inputResponses`, matching MRTR's vocabulary.
3326
- const responses = isRecord(params) &&
3327
- isRecord(params["inputResponses"])
3328
- ? params["inputResponses"]
3329
- : undefined;
3330
- if (responses === undefined) {
3331
- return jsonRpcResponse(
3332
- {
3333
- jsonrpc: "2.0",
3334
- id,
3335
- error: {
3336
- code: JSONRPC_INVALID_PARAMS,
3337
- message: "tasks/update requires an 'inputResponses' object",
3338
- },
3339
- },
3340
- 400,
3341
- );
3342
- }
3343
- if (!store.update(taskId, responses, caller)) {
3344
- // SHOULD be an error for an unknown id — and an id belonging to
3345
- // another caller is reported identically, so the response never
3346
- // confirms that someone else's task exists.
3347
- return c.json({
3348
- jsonrpc: "2.0",
3349
- id,
3350
- error: {
3351
- code: JSONRPC_INVALID_PARAMS,
3352
- message: `Unknown taskId: ${taskId}`,
3353
- },
3354
- });
3355
- }
3356
- // MUST be an EMPTY acknowledgement (beyond the resultType envelope).
3357
- // Returning the task state instead would look helpful and be
3358
- // non-conformant — and the spec calls the ack eventually consistent,
3359
- // so any state returned here could already be stale.
3360
- return c.json({
3361
- jsonrpc: "2.0",
3362
- id,
3363
- result: this.stampResult({}, statelessVersion),
3364
- });
3365
- }
3366
-
3367
- // tasks/cancel — likewise an empty ack. Cancellation is cooperative:
3368
- // the server acknowledges intent, and the task may still finish or
3369
- // reach a different terminal status.
3370
- if (!store.cancel(taskId, caller)) {
3371
- return c.json({
3372
- jsonrpc: "2.0",
3373
- id,
3374
- error: {
3375
- code: JSONRPC_INVALID_PARAMS,
3376
- message: `Unknown taskId: ${taskId}`,
3377
- },
3378
- });
3379
- }
3380
- return c.json({
3381
- jsonrpc: "2.0",
3382
- id,
3383
- result: this.stampResult({}, statelessVersion),
3384
- });
3385
- }
3386
-
3387
- // `ping` and `logging/setLevel` were REMOVED by spec 2026-07-28.
3388
- // They fall through to method-not-found below (404 + -32601), which is
3389
- // how a client distinguishes a modern server from a legacy HTTP+SSE one.
3390
- if (method === "prompts/list") {
3391
- return c.json({
3392
- jsonrpc: "2.0",
3393
- id,
3394
- result: this.stampResult(
3395
- this.withCacheHints({ prompts: [] }, statelessVersion),
3396
- statelessVersion,
3397
- ),
3398
- });
3399
- }
3400
- if (method === "completion/complete") {
3401
- return c.json({
3402
- jsonrpc: "2.0",
3403
- id,
3404
- result: this.stampResult(
3405
- { completion: { values: [] } },
3406
- statelessVersion,
3407
- ),
3408
- });
3409
- }
3410
-
3411
- // Handle notifications: a method and NO id (JSON-RPC 2.0).
3412
- //
3413
- // `!id` was wrong: `0` is a valid id and is falsy, so a request with
3414
- // `id: 0` was answered 202-with-no-body as though it were a
3415
- // notification. The spec only forbids `null`.
3416
- if (method && id === undefined) {
3417
- return new Response(null, { status: 202 });
3418
- }
3419
-
3420
- // Malformed request: no method at all
3421
- if (!method) {
3422
- return c.json({
3423
- jsonrpc: "2.0",
3424
- id: id ?? null,
3425
- error: {
3426
- code: -32600,
3427
- message: "Invalid Request: missing 'method' field",
3428
- },
3429
- });
3430
- }
3431
-
3432
- // Method not found.
3433
- //
3434
- // Spec 2026-07-28 requires HTTP **404** here, not 200: "If the server
3435
- // does not implement the requested RPC method, it MUST respond with
3436
- // 404 Not Found and a JSON-RPC error with code -32601". The status is
3437
- // load-bearing — a client probing an unknown URL uses exactly this
3438
- // response to tell a modern MCP endpoint from a legacy HTTP+SSE server.
3439
- //
3440
- // This also covers the removed methods (`ping`, `logging/setLevel`).
3441
- return jsonRpcResponse(
3442
- {
3443
- jsonrpc: "2.0",
3444
- id,
3445
- error: { code: -32601, message: `Method not found: ${method}` },
3446
- },
3447
- 404,
3448
- );
3449
- } catch (error) {
3450
- this.log(
3451
- `HTTP request error: ${
3452
- error instanceof Error ? error.message : String(error)
3453
- }`,
3454
- );
3455
- return c.json({
3456
- jsonrpc: "2.0",
3457
- id: requestId,
3458
- error: { code: -32700, message: "Parse error" },
3459
- });
3460
- }
3461
- };
3462
-
3463
- // deno-lint-ignore no-explicit-any
3464
- app.post("/mcp", handleMcpPost as any);
3465
- // deno-lint-ignore no-explicit-any
3466
- app.post("/", handleMcpPost as any);
3467
-
3468
- // Embedded mode: skip serve(), surface the Hono fetch handler to the
3469
- // caller and let them mount it inside their own framework (Fresh, Hono,
3470
- // Express, etc.).
3471
- if (options.embedded) {
3472
- if (!options.embeddedHandlerCallback) {
3473
- throw new Error(
3474
- "[McpApp] embedded=true requires embeddedHandlerCallback",
3475
- );
3476
- }
3477
- // deno-lint-ignore no-explicit-any
3478
- options.embeddedHandlerCallback(app.fetch as any);
3479
- this.started = true;
3480
- this.log(
3481
- `HTTP handler ready (embedded mode — no port bound, max concurrent: ${
3482
- this.options.maxConcurrent ?? 10
3483
- })`,
3484
- );
3485
- return {
3486
- shutdown: async () => {
3487
- await this.stop();
3488
- },
3489
- addr: { hostname: "embedded", port: 0 },
3490
- };
3491
- }
3492
-
3493
- // Start server
3494
- this.httpServer = serve(
3495
- {
3496
- port: options.port,
3497
- hostname,
3498
- maxBodyBytes,
3499
- onListen: options.onListen ?? ((info) => {
3500
- this.log(
3501
- `HTTP server started on http://${info.hostname}:${info.port}`,
3502
- );
3503
- }),
3504
- },
3505
- app.fetch,
3506
- );
3507
-
3508
- this.started = true;
3509
-
3510
- const rateLimitInfo = this.options.rateLimit
3511
- ? `, rate limit: ${this.options.rateLimit.maxRequests}/${this.options.rateLimit.windowMs}ms`
3512
- : "";
3513
- const validationInfo = this.options.validateSchema
3514
- ? ", schema validation: on"
3515
- : "";
3516
-
3517
- this.log(
3518
- `Server started HTTP mode (max concurrent: ${
3519
- this.options.maxConcurrent ?? 10
3520
- }, strategy: ${
3521
- this.options.backpressureStrategy ?? "sleep"
3522
- }${rateLimitInfo}${validationInfo})`,
3523
- );
3524
- this.log(
3525
- `Tools available: ${this.tools.size}, Resources: ${this.resources.size}`,
3526
- );
3527
-
3528
- return {
3529
- shutdown: async () => {
3530
- await this.stop();
3531
- },
3532
- addr: { hostname, port: options.port },
3533
- };
3534
- }
3535
-
3536
- /**
3537
- * Build the HTTP middleware stack and return its fetch handler without
3538
- * binding a port. Use this when you want to mount the MCP HTTP layer
3539
- * inside another HTTP framework on Deno (Fresh, Hono, `Deno.serve`) or
3540
- * Node (Express, Hono-on-Node) instead of giving up port ownership to
3541
- * {@link startHttp}.
3542
- *
3543
- * **Runtime targets:** `@casys/mcp-server` is Deno-first — the canonical
3544
- * deployment path is Deno 2.x on Deno Deploy or self-hosted Deno, with
3545
- * a Node 20+ distribution via `scripts/build-node.sh` as a secondary
3546
- * target. Cloudflare Workers, workerd, and browser runtimes are not
3547
- * supported — if you target those, use
3548
- * [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server)
3549
- * directly instead.
3550
- *
3551
- * The returned handler accepts a Web Standard {@link Request} and returns
3552
- * a Web Standard {@link Response}. It exposes the same routes as
3553
- * {@link startHttp}: `POST /mcp`, `GET /health`, `GET /metrics`, and
3554
- * `GET /.well-known/oauth-protected-resource`. `GET /mcp` returns 405.
3555
- *
3556
- * Auth, multi-tenant middleware, scope checks, and rate limiting are all
3557
- * applied identically. OTel hooks are started, so the server is fully
3558
- * live after this returns — just without its own listening socket.
3559
- *
3560
- * Multi-tenant SaaS pattern: cache one `McpApp` per tenant
3561
- * and call `getFetchHandler()` once per server, then dispatch each
3562
- * inbound request to the right cached handler from your framework's
3563
- * routing layer.
3564
- *
3565
- * @example
3566
- * ```typescript
3567
- * // In a Fresh route at routes/mcp/[...path].tsx
3568
- * const server = new McpApp({ name: "my-mcp", version: "1.0.0" });
3569
- * server.registerTools(tools, handlers);
3570
- * const handler = await server.getFetchHandler({
3571
- * requireAuth: true,
3572
- * auth: { provider: myAuthProvider },
3573
- * });
3574
- * // Later, in your route handler:
3575
- * return await handler(ctx.req);
3576
- * ```
3577
- *
3578
- * @param options - Same as {@link startHttp}, minus `port`/`hostname`/`onListen`.
3579
- * @returns A Web Standard fetch handler.
3580
- */
3581
- async getFetchHandler(
3582
- options: Omit<HttpServerOptions, "port" | "hostname" | "onListen"> = {},
3583
- ): Promise<FetchHandler> {
3584
- let captured: FetchHandler | null = null;
3585
- await this.startHttp({
3586
- // port/hostname are unused in embedded mode but the type requires them.
3587
- // Pass sentinel values that would never bind even if used.
3588
- port: 0,
3589
- ...options,
3590
- embedded: true,
3591
- embeddedHandlerCallback: (handler) => {
3592
- captured = handler;
3593
- },
3594
- });
3595
- if (!captured) {
3596
- // Defensive: startHttp should always invoke the callback synchronously
3597
- // before returning. If it didn't, something is structurally wrong.
3598
- throw new Error(
3599
- "[McpApp] getFetchHandler: embedded callback was not invoked",
3600
- );
3601
- }
3602
- return captured;
3603
- }
3604
-
3605
- /**
3606
- * Read the MCP Apps capability advertised by the connected client.
3607
- *
3608
- * Returns the capability object (possibly empty `{}`) when the client
3609
- * advertised support for MCP Apps via its `extensions` capability,
3610
- * or `undefined` when:
3611
- * - the client did not send capabilities yet (called before initialize)
3612
- * - the client did not advertise the MCP Apps extension at all
3613
- * - the client sent a malformed extension value
3614
- *
3615
- * Use this from a tool handler to decide whether to return a UI
3616
- * resource (`_meta.ui`) or a text-only fallback. Hosts that don't
3617
- * support MCP Apps will silently drop the `_meta.ui` field, but
3618
- * checking explicitly lets you serve a richer text response when
3619
- * the UI path isn't available.
3620
- *
3621
- * @returns MCP Apps capability or `undefined` if not supported.
3622
- *
3623
- * @example
3624
- * ```typescript
3625
- * const cap = app.getClientMcpAppsCapability();
3626
- * if (cap?.mimeTypes?.includes(MCP_APP_MIME_TYPE)) {
3627
- * return {
3628
- * content: [{ type: "text", text: summary }],
3629
- * _meta: { ui: { resourceUri: "ui://my-app/dashboard" } },
3630
- * };
3631
- * }
3632
- * return { content: [{ type: "text", text: detailedTextFallback }] };
3633
- * ```
3634
- *
3635
- * @see {@link getMcpAppsCapability} for the standalone reader
3636
- * @see {@link MCP_APPS_EXTENSION_ID} for the extension key
3637
- */
3638
- getClientMcpAppsCapability(): McpAppsClientCapability | undefined {
3639
- return getMcpAppsCapability(
3640
- this.activeStdioServer?.getClientCapabilities(),
3641
- );
3642
- }
3643
-
3644
- /**
3645
- * Get queue metrics for monitoring
3646
- */
3647
- getMetrics(): QueueMetrics {
3648
- return this.requestQueue.getMetrics();
3649
- }
3650
-
3651
- /**
3652
- * Get full server metrics (counters, histograms, gauges)
3653
- */
3654
- getServerMetrics(): import("./observability/metrics.js").ServerMetricsSnapshot {
3655
- const qm = this.requestQueue.getMetrics();
3656
- this.serverMetrics.setGauges({
3657
- activeRequests: qm.inFlight,
3658
- queuedRequests: qm.queued,
3659
- rateLimiterKeys: this.rateLimiter?.getMetrics().keys ?? 0,
3660
- });
3661
- return this.serverMetrics.getSnapshot();
3662
- }
3663
-
3664
- /**
3665
- * Get Prometheus text format metrics
3666
- */
3667
- getPrometheusMetrics(): string {
3668
- return this.serverMetrics.toPrometheusFormat();
3669
- }
3670
-
3671
- /**
3672
- * Get rate limiter metrics (if rate limiting is enabled)
3673
- */
3674
- getRateLimitMetrics(): { keys: number; totalRequests: number } | null {
3675
- return this.rateLimiter?.getMetrics() ?? null;
3676
- }
3677
-
3678
- /**
3679
- * Get rate limiter instance (for advanced use cases)
3680
- */
3681
- getRateLimiter(): RateLimiter | null {
3682
- return this.rateLimiter;
3683
- }
3684
-
3685
- /**
3686
- * Get schema validator instance (for advanced use cases)
3687
- */
3688
- getSchemaValidator(): SchemaValidator | null {
3689
- return this.schemaValidator;
3690
- }
3691
-
3692
- /**
3693
- * Check if server is started
3694
- */
3695
- isStarted(): boolean {
3696
- return this.started;
3697
- }
3698
-
3699
- /**
3700
- * Get number of registered tools
3701
- */
3702
- getToolCount(): number {
3703
- return this.tools.size;
3704
- }
3705
-
3706
- /**
3707
- * Get tool names
3708
- */
3709
- getToolNames(): string[] {
3710
- return Array.from(this.tools.keys());
3711
- }
3712
-
3713
- // ============================================
3714
- // Resource Introspection (MCP Apps)
3715
- // ============================================
3716
-
3717
- /**
3718
- * Get number of registered resources
3719
- */
3720
- getResourceCount(): number {
3721
- return this.resources.size;
3722
- }
3723
-
3724
- /**
3725
- * Get registered resource URIs
3726
- */
3727
- getResourceUris(): string[] {
3728
- return Array.from(this.resources.keys());
3729
- }
3730
-
3731
- /**
3732
- * Check if a resource is registered
3733
- */
3734
- hasResource(uri: string): boolean {
3735
- return this.resources.has(uri);
3736
- }
3737
-
3738
- /**
3739
- * Get resource info by URI (for testing/debugging)
3740
- */
3741
- getResourceInfo(uri: string): MCPResource | undefined {
3742
- return this.resources.get(uri)?.resource;
3743
- }
3744
-
3745
- /**
3746
- * Read resource content by URI.
3747
- * Invokes the registered handler directly (no MCP protocol round-trip).
3748
- * Returns null if the resource is not registered.
3749
- */
3750
- async readResourceContent(uri: string): Promise<ResourceContent | null> {
3751
- const entry = this.resources.get(uri);
3752
- if (!entry) return null;
3753
- return this.validateResourceContent(
3754
- uri,
3755
- await entry.handler(new URL(uri)),
3756
- entry.resource,
3757
- );
3758
- }
3759
-
3760
- /**
3761
- * Send a JSON-RPC notification to the connected transport.
3762
- *
3763
- * Routing depends on the transport:
3764
- * - **HTTP**: fanned out to `subscriptions/listen` streams, only to
3765
- * subscribers that opted into that notification type.
3766
- * - **stdio**: written to stdout via the SDK transport.
3767
- *
3768
- * @param method - Notification method (e.g. "notifications/tools/list_changed")
3769
- * @param params - Notification parameters
3770
- */
3771
- sendNotification(
3772
- method: string,
3773
- params?: Record<string, unknown>,
3774
- ): void {
3775
- if (!this.started) return;
3776
-
3777
- // Route through the subscription registry (subscriptions/listen streams).
3778
- if (this.subscriptions !== null) {
3779
- switch (method) {
3780
- case "notifications/tools/list_changed":
3781
- this.subscriptions.fanOut("toolsListChanged");
3782
- return;
3783
- case "notifications/prompts/list_changed":
3784
- this.subscriptions.fanOut("promptsListChanged");
3785
- return;
3786
- case "notifications/resources/list_changed":
3787
- this.subscriptions.fanOut("resourcesListChanged");
3788
- return;
3789
- case "notifications/resources/updated": {
3790
- const uri = isRecord(params) && typeof params["uri"] === "string"
3791
- ? params["uri"]
3792
- : undefined;
3793
- if (uri === undefined) {
3794
- this.log(
3795
- "[WARN] notifications/resources/updated requires a string 'uri' param; dropped",
3796
- );
3797
- return;
3798
- }
3799
- this.subscriptions.fanOutResourceUpdated(uri);
3800
- return;
3801
- }
3802
- default:
3803
- // subscriptions/listen carries only the four change types a client can
3804
- // opt into. Anything else — a request-scoped progress or log message —
3805
- // belongs on the response stream of the request it relates to, which is
3806
- // not something this method can reach. Say so rather than drop silently.
3807
- this.log(
3808
- `[WARN] sendNotification("${method}") has no delivery channel in stateless mode: ` +
3809
- "only the four subscriptions/listen change types can be pushed. " +
3810
- "Request-scoped notifications must travel on their own request's response stream.",
3811
- );
3812
- return;
3813
- }
3814
- }
3815
-
3816
- // For stdio mode, send via the one protocol instance pinned by the era
3817
- // negotiator. A probe instance may already be closed while its replacement
3818
- // is being built, so never route through the constructor-time template.
3819
- const server = this.activeStdioServer;
3820
- if (server === null) return;
3821
- void server.notification({ method, params }).catch(() => {
3822
- // Transport may not support notifications yet (pre-initialized).
3823
- });
3824
- }
3825
-
3826
- /**
3827
- * Register a callback for the "initialized" notification.
3828
- * Called after client sends "initialized" (post-handshake).
3829
- */
3830
- onInitialized(callback: () => void): void {
3831
- this.initializedCallback = callback;
3832
- }
3833
-
3834
- private initializedCallback: (() => void) | null = null;
3835
-
3836
- /**
3837
- * Check if a handler result is a pre-formatted MCP result.
3838
- * Pre-formatted results have a `content` array and are passed through
3839
- * without re-wrapping. This supports proxy/gateway patterns.
3840
- */
3841
- private isPreformattedResult(
3842
- result: unknown,
3843
- ): result is {
3844
- content: Array<{ type: string; text: string }>;
3845
- _meta?: Record<string, unknown>;
3846
- } {
3847
- if (!result || typeof result !== "object") return false;
3848
- const obj = result as Record<string, unknown>;
3849
- return Array.isArray(obj.content) &&
3850
- obj.content.length > 0 &&
3851
- typeof obj.content[0] === "object" &&
3852
- obj.content[0] !== null &&
3853
- "type" in obj.content[0] &&
3854
- "text" in obj.content[0];
3855
- }
3856
-
3857
- /**
3858
- * Apply the spec-2026-07-28 result envelope when — and only when — the peer
3859
- * negotiated that revision.
3860
- *
3861
- * This helper applies on the custom stateless HTTP transport, which only
3862
- * accepts 2026-07-28. Stdio results are neutral here: the official v2 codec
3863
- * stamps modern responses and leaves a negotiated legacy connection clean.
3864
- *
3865
- * Omitting the envelope for a genuinely legacy peer is safe in the other
3866
- * direction too: the spec instructs clients to read a missing `resultType` as
3867
- * `"complete"`.
3868
- *
3869
- * Every HTTP result path funnels through here. Adding a new one without it is
3870
- * the failure mode to watch for — hence the conformance test that walks the
3871
- * method table rather than asserting one endpoint at a time.
3872
- *
3873
- * @param negotiatedVersion Version from the request's `_meta`, or `undefined`
3874
- * where no per-request negotiation happens.
3875
- */
3876
- private stampResult(
3877
- result: Record<string, unknown>,
3878
- negotiatedVersion?: string,
3879
- resultType: "complete" | "task" = "complete",
3880
- ): Record<string, unknown> {
3881
- if (negotiatedVersion !== SPEC_2026_07_28) return result;
3882
- return {
3883
- ...completeResult(result, {
3884
- name: this.options.name,
3885
- version: this.options.version,
3886
- }),
3887
- resultType,
3888
- };
3889
- }
3890
-
3891
- /**
3892
- * Validate one MRTR retry delivered through the v2 protocol server.
3893
- *
3894
- * The SDK owns era-specific lifting and legacy fulfilment; Casys owns the
3895
- * integrity bindings and nonce consumption of its sealed requestState.
3896
- * Protocol errors deliberately escape the tool-error wrapper so clients see
3897
- * a JSON-RPC error instead of a successful tools/call result with isError.
3898
- */
3899
- private async prepareProtocolMrtrRetry(
3900
- inputResponses: Record<string, unknown> | undefined,
3901
- requestState: string | undefined,
3902
- context: {
3903
- principal: string;
3904
- method: string;
3905
- paramsDigest: string;
3906
- },
3907
- ): Promise<{
3908
- inputResponses?: Record<string, unknown>;
3909
- retryVerified?: boolean;
3910
- }> {
3911
- const needsKey = inputResponses !== undefined || requestState !== undefined;
3912
- let key: CryptoKey | null = null;
3913
- if (needsKey) {
3914
- try {
3915
- key = await this.getMrtrKey();
3916
- } catch (error) {
3917
- throw new ProtocolError(
3918
- ProtocolErrorCode.InternalError,
3919
- "MRTR signing key is unavailable",
3920
- {
3921
- problem: "mrtr_key_unavailable",
3922
- detail: error instanceof Error ? error.message : String(error),
3923
- recovery:
3924
- "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
3925
- },
3926
- );
3927
- }
3928
- }
3929
-
3930
- const outcome = await guardMrtrRetry({
3931
- ...(inputResponses !== undefined ? { inputResponses } : {}),
3932
- ...(requestState !== undefined ? { requestState } : {}),
3933
- key,
3934
- replayStore: this.mrtrReplayStore,
3935
- bindings: context,
3936
- });
3937
-
3938
- if (outcome.kind === "missing_state") {
3939
- throw new ProtocolError(
3940
- ProtocolErrorCode.InvalidParams,
3941
- "inputResponses supplied without the requestState issued with them",
3942
- {
3943
- problem: "missing_request_state",
3944
- recovery:
3945
- "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
3946
- },
3947
- );
3948
- }
3949
- if (outcome.kind === "invalid_state") {
3950
- throw new ProtocolError(
3951
- ProtocolErrorCode.InvalidParams,
3952
- `Invalid requestState: ${outcome.reason}`,
3953
- { reason: outcome.reason },
3954
- );
3955
- }
3956
- if (outcome.kind === "replay_store_unavailable") {
3957
- if (outcome.reason === "consume_failed") {
3958
- this.log(
3959
- "[WARN] MRTR replay store unavailable; retry rejected before handler",
3960
- );
3961
- }
3962
- throw new ProtocolError(
3963
- ProtocolErrorCode.InternalError,
3964
- "MRTR replay protection is unavailable",
3965
- {
3966
- problem: "mrtr_replay_store_unavailable",
3967
- recovery: outcome.reason === "missing"
3968
- ? "Configure mrtr.signingKey with a working replay store and retry the full interaction."
3969
- : "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
3970
- },
3971
- );
3972
- }
3973
- if (outcome.kind === "replayed") {
3974
- throw new ProtocolError(
3975
- ProtocolErrorCode.InvalidParams,
3976
- "Invalid requestState: replayed",
3977
- { reason: "replayed" },
3978
- );
3979
- }
3980
-
3981
- return {
3982
- ...(inputResponses !== undefined ? { inputResponses } : {}),
3983
- ...(outcome.retryVerified !== undefined
3984
- ? { retryVerified: outcome.retryVerified }
3985
- : {}),
3986
- };
3987
- }
3988
-
3989
- /**
3990
- * Resolve the MRTR signing key once, warning if a deployment has none.
3991
- *
3992
- * A missing key is not an error: the spec permits unprotected `requestState`
3993
- * when tampering can cause nothing worse than the request failing. It is a
3994
- * loud warning because that condition is easy to believe and hard to verify.
3995
- */
3996
- /**
3997
- * Key lookup that reports failure instead of throwing.
3998
- *
3999
- * The `tools/call` call sites sit outside the tool try/catch, so a throw would
4000
- * reach the POST-level catch and surface as -32700 "Parse error" — the same trap
4001
- * the earlier throwing principal guard fell into. Returns a ready response
4002
- * instead.
4003
- */
4004
- private async getMrtrKeySafe(
4005
- id: unknown,
4006
- version: string,
4007
- ): Promise<{ key: CryptoKey | null } | { error: Response }> {
4008
- try {
4009
- return { key: await this.getMrtrKey() };
4010
- } catch (error) {
4011
- return {
4012
- error: jsonRpcResponse(
4013
- {
4014
- jsonrpc: "2.0",
4015
- id,
4016
- error: {
4017
- code: ErrorCode.InternalError,
4018
- message: "MRTR signing key is unavailable",
4019
- data: {
4020
- problem: "mrtr_key_unavailable",
4021
- detail: error instanceof Error ? error.message : String(error),
4022
- recovery:
4023
- "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
4024
- },
4025
- },
4026
- },
4027
- 500,
4028
- { "MCP-Protocol-Version": version },
4029
- ),
4030
- };
4031
- }
4032
- }
4033
-
4034
- private getMrtrKey(): Promise<CryptoKey | null> {
4035
- // Assigned synchronously, so two concurrent callers share one import rather
4036
- // than one of them observing a half-initialised state.
4037
- //
4038
- // A REJECTED import is un-memoised in the catch below: caching the rejection
4039
- // poisoned the instance permanently, and every later retry surfaced it through
4040
- // the POST-level catch as -32700 "Parse error" — wrong code, and no second
4041
- // attempt ever made. A transient WebCrypto failure should not be terminal.
4042
- this.mrtrKeyPromise ??= (async () => {
4043
- const hex = this.options.mrtr?.signingKey;
4044
- if (hex === undefined) {
4045
- this.log(
4046
- "[WARN] MRTR requestState is unprotected: no mrtr.signingKey configured. " +
4047
- "A client can tamper with it. Only acceptable when requestState " +
4048
- "influences nothing beyond whether the request succeeds.",
4049
- );
4050
- return null;
4051
- }
4052
- try {
4053
- return await importStateKey(hex);
4054
- } catch (error) {
4055
- // Drop the memoised rejection so a later request retries the import.
4056
- this.mrtrKeyPromise = null;
4057
- throw new Error(
4058
- `[McpApp] mrtr.signingKey could not be imported: ${
4059
- error instanceof Error ? error.message : String(error)
4060
- }`,
4061
- );
4062
- }
4063
- })();
4064
- return this.mrtrKeyPromise;
4065
- }
4066
-
4067
- /**
4068
- * Turn a handler's `InputRequiredSignal` into the wire result.
4069
- *
4070
- * Validates what the spec puts on the server rather than the client:
4071
- * - at least one of `inputRequests` / `requestState` must be present;
4072
- * - no input request may name a capability the client did not declare.
4073
- *
4074
- * A violation is the server author's bug, so it surfaces as `-32603` rather
4075
- * than being emitted as an invalid MRTR result for the client to puzzle over.
4076
- */
4077
- private async buildInputRequiredResult(
4078
- signal: InputRequiredSignal,
4079
- context: {
4080
- clientCapabilities: ClientCapabilities | undefined;
4081
- principal: string;
4082
- method: string;
4083
- /** Digest of the arguments as received, taken before the pipeline ran. */
4084
- paramsDigest: string;
4085
- },
4086
- ): Promise<
4087
- { ok: true; result: Record<string, unknown> } | {
4088
- ok: false;
4089
- message: string;
4090
- code: number;
4091
- data?: Record<string, unknown>;
4092
- }
4093
- > {
4094
- const requests = signal.inputRequests;
4095
-
4096
- // `Object.keys(null)` throws, and `inputRequests: null` survives JSON — so an
4097
- // unchecked map reached the generic tool-error path as a 200 instead of being
4098
- // classified as the malformed server output it is. Validated before enumerating.
4099
- if (requests !== undefined && !isRecord(requests)) {
4100
- return {
4101
- ok: false,
4102
- code: ErrorCode.InternalError,
4103
- message: "Malformed inputRequest: inputRequests must be an object",
4104
- };
4105
- }
4106
-
4107
- const hasRequests = requests !== undefined &&
4108
- Object.keys(requests).length > 0;
4109
-
4110
- if (!hasRequests && signal.requestState === undefined) {
4111
- return {
4112
- ok: false,
4113
- code: ErrorCode.InternalError,
4114
- message:
4115
- "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
4116
- };
4117
- }
4118
-
4119
- let canonicalRequests: Record<string, unknown> | undefined;
4120
- if (hasRequests) {
4121
- const check = checkInputRequestCapabilities(
4122
- requests as Record<string, InputRequestEntry>,
4123
- context.clientCapabilities as Record<string, unknown> | undefined,
4124
- );
4125
- if (!check.ok) {
4126
- // A structurally invalid input request is the SERVER's bug. Reporting it
4127
- // as -32021 told the client to declare a capability it already had, and
4128
- // hid the real fault behind a client-facing error.
4129
- if (check.kind === "malformed") {
4130
- return {
4131
- ok: false,
4132
- code: ErrorCode.InternalError,
4133
- message: `Malformed inputRequest: ${
4134
- check.missingCapabilities.join(", ")
4135
- }`,
4136
- };
4137
- }
4138
- // Spec rule 7 is a MUST NOT on the server: never ask for input the
4139
- // client cannot provide. Emitting it anyway would strand the request.
4140
- return {
4141
- ok: false,
4142
- code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
4143
- message:
4144
- `Cannot request input for capabilities the client did not declare: ${
4145
- check.missingCapabilities.join(", ")
4146
- }`,
4147
- // ClientCapabilities-shaped so a typed client can read it directly and
4148
- // learn which capability to declare.
4149
- data: {
4150
- // The check supplies a nested shape for sub-capabilities; otherwise
4151
- // the names are top-level keys.
4152
- requiredCapabilities: check.requiredCapabilities ??
4153
- Object.fromEntries(
4154
- check.missingCapabilities.map((cap) => [cap, {}]),
4155
- ),
4156
- },
4157
- };
4158
- }
4159
- canonicalRequests = check.canonicalRequests;
4160
- }
4161
-
4162
- // Seal the token so the retry can be proven legitimate. The payload holds
4163
- // only bindings — principal, method, argument digest, expiry, nonce — not
4164
- // application state: since the digest guarantees identical arguments, a
4165
- // handler rebuilds its context from those.
4166
- //
4167
- // The principal binding is only meaningful when auth is configured; see the
4168
- // verification site. Sealing happens AFTER the capability check on purpose —
4169
- // no point minting a token for a result that will be refused.
4170
- // Resolved here regardless of `needsKey` at ingress: a FIRST leg carries
4171
- // neither MRTR field and still needs a sealed token. A rejected import is
4172
- // reported as what it is rather than surfacing as a tool failure — the
4173
- // handler did nothing wrong.
4174
- let key: CryptoKey | null;
4175
- try {
4176
- key = await this.getMrtrKey();
4177
- } catch (error) {
4178
- return {
4179
- ok: false,
4180
- code: ErrorCode.InternalError,
4181
- message: "MRTR signing key is unavailable",
4182
- data: {
4183
- problem: "mrtr_key_unavailable",
4184
- detail: error instanceof Error ? error.message : String(error),
4185
- recovery:
4186
- "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
4187
- },
4188
- };
4189
- }
4190
- let requestState = signal.requestState;
4191
- if (key !== null) {
4192
- const ttl = this.options.mrtr?.defaultTtlSecs ?? 300;
4193
- requestState = await sealRequestState({
4194
- sub: context.principal,
4195
- method: context.method,
4196
- paramsDigest: context.paramsDigest,
4197
- exp: Math.floor(Date.now() / 1000) + ttl,
4198
- nonce: bytesToHexLocal(crypto.getRandomValues(new Uint8Array(16))),
4199
- }, key);
4200
- }
4201
-
4202
- // No `?? requests` fallback. Falling back to the handler's object would
4203
- // silently restore the very bypass this closes — a fallback that reopens a
4204
- // security hole is worse than a failure. If the invariant ever breaks, say so.
4205
- if (hasRequests && canonicalRequests === undefined) {
4206
- return {
4207
- ok: false,
4208
- code: ErrorCode.InternalError,
4209
- message:
4210
- "Internal invariant violated: inputRequests were not canonicalised before emission",
4211
- };
4212
- }
4213
-
4214
- // Serialisation can EMPTY the map: JSON drops keys whose value is `undefined`,
4215
- // so `{ ask: undefined }` canonicalises to `{}`. The at-least-one rule was
4216
- // checked against the original, so that emitted an InputRequiredResult with an
4217
- // empty map and — where no key is configured — no requestState either, leaving
4218
- // the client nothing to answer and no reason to retry.
4219
- const canonicalCount = canonicalRequests === undefined
4220
- ? 0
4221
- : Object.keys(canonicalRequests).length;
4222
- if (hasRequests && canonicalCount === 0) {
4223
- return {
4224
- ok: false,
4225
- code: ErrorCode.InternalError,
4226
- message:
4227
- "inputRequests contained no serialisable entries (keys with an undefined value are dropped by JSON)",
4228
- };
4229
- }
4230
- if (canonicalCount === 0 && requestState === undefined) {
4231
- return {
4232
- ok: false,
4233
- code: ErrorCode.InternalError,
4234
- message:
4235
- "An InputRequiredResult must carry at least one of inputRequests or requestState (spec 2026-07-28, MRTR server rule 6)",
4236
- };
4237
- }
4238
-
4239
- return {
4240
- ok: true,
4241
- result: {
4242
- resultType: "input_required",
4243
- // This path deliberately cannot use stampResult(): that would replace
4244
- // its `input_required` discriminator with `complete`. It is still a
4245
- // 2026 Result, though, so carry the same server identity envelope as
4246
- // every other response.
4247
- _meta: {
4248
- [STATELESS_SERVER_INFO_KEY]: {
4249
- name: this.options.name,
4250
- version: this.options.version,
4251
- },
4252
- },
4253
- // The clone the check inspected, NOT the handler's object. Serialising the
4254
- // original a second time lets a stateful `toJSON()` return a different
4255
- // value for the response than the gate approved.
4256
- ...(canonicalRequests !== undefined
4257
- ? { inputRequests: canonicalRequests }
4258
- : {}),
4259
- ...(requestState !== undefined ? { requestState } : {}),
4260
- },
4261
- };
4262
- }
4263
-
4264
- /**
4265
- * Reject a Tasks request from a client that did not declare the extension.
4266
- *
4267
- * Returns a ready 400 response to return, or `null` when the client is
4268
- * entitled to proceed. Two distinct spec rules converge here: a server
4269
- * **MUST NOT** hand a task to a non-declaring client, and **MUST** answer the
4270
- * missing-capability error when one calls `tasks/*`.
4271
- *
4272
- * `-32021` (`MissingRequiredClientCapability`) is the code, and
4273
- * `data.requiredCapabilities` is required to list what was missing — a client
4274
- * that gets this back needs to know which capability to add, not just that
4275
- * something was absent.
4276
- */
4277
- private requireTasksCapability(
4278
- clientCapabilities: ClientCapabilities | undefined,
4279
- id: unknown,
4280
- ): Response | null {
4281
- if (this.taskStore === null) {
4282
- return jsonRpcResponse(
4283
- {
4284
- jsonrpc: "2.0",
4285
- id,
4286
- error: {
4287
- code: ErrorCode.MethodNotFound,
4288
- message:
4289
- `Tasks extension is not enabled on this server (declare "${TASKS_EXTENSION_ID}" in McpAppOptions.extensions)`,
4290
- },
4291
- },
4292
- 404,
4293
- );
4294
- }
4295
-
4296
- const extensions = clientCapabilities?.extensions;
4297
- const declared = isRecord(extensions) &&
4298
- extensions[TASKS_EXTENSION_ID] !== undefined;
4299
- if (declared) return null;
4300
-
4301
- return jsonRpcResponse(
4302
- {
4303
- jsonrpc: "2.0",
4304
- id,
4305
- error: {
4306
- code: MCP_MISSING_REQUIRED_CLIENT_CAPABILITY,
4307
- message:
4308
- `Client did not declare the "${TASKS_EXTENSION_ID}" extension`,
4309
- // ClientCapabilities-shaped, per the schema: capability keys mapping
4310
- // to their settings object. An array of names would not deserialise
4311
- // into `ClientCapabilities` on a typed client.
4312
- data: {
4313
- requiredCapabilities: { extensions: { [TASKS_EXTENSION_ID]: {} } },
4314
- },
4315
- },
4316
- },
4317
- 400,
4318
- );
4319
- }
4320
-
4321
- /**
4322
- * Task status transitions, for pushing to subscribers.
4323
- *
4324
- * The spec's notification method is `notifications/tasks` — not a
4325
- * `tasks/`-prefixed name, which would collide with the request methods.
4326
- *
4327
- * Delivery goes out over `subscriptions/listen` once that route is wired
4328
- * (Track G); the registry exists but the transport does not yet open streams.
4329
- * Until then this is intentionally a no-op beyond the log: polling via
4330
- * `tasks/get` is the spec's default and works without it.
4331
- */
4332
- private onTaskChanged(task: DetailedTask): void {
4333
- this.log(`task ${task.taskId} → ${task.status}`);
4334
- }
4335
-
4336
- /**
4337
- * Add the required `CacheableResult` fields (spec 2026-07-28, SEP-2549).
4338
- *
4339
- * Applies to `tools/list`, `prompts/list`, `resources/list`, `resources/read`
4340
- * and `resources/templates/list`, where the final spec makes both fields
4341
- * required rather than optional. Same version gate as {@link stampResult}:
4342
- * neither field exists in an earlier revision.
4343
- *
4344
- * Both are hints — a client that ignores them stays correct, it just polls
4345
- * more often.
4346
- */
4347
- private withCacheHints(
4348
- result: Record<string, unknown>,
4349
- negotiatedVersion?: string,
4350
- request?: { readonly isMrtrRetry?: boolean },
4351
- ): Record<string, unknown> {
4352
- if (negotiatedVersion !== SPEC_2026_07_28) return result;
4353
-
4354
- // A result produced by an MRTR retry MUST NOT be cached: it depends on
4355
- // `inputResponses` / `requestState`, which are not part of the cache key, so
4356
- // a cache would serve it for a later request that supplied different input.
4357
- // Emitting no hints is how a server declines to make the result cacheable —
4358
- // clients read an absent ttlMs as 0.
4359
- if (request?.isMrtrRetry) return result;
4360
-
4361
- return {
4362
- ...result,
4363
- ttlMs: this.cacheTtlMs,
4364
- cacheScope: this.options.cache?.scope ?? "private",
4365
- };
4366
- }
4367
-
4368
- /**
4369
- * Capabilities advertised on `server/discover` and `initialize`.
4370
- *
4371
- * Single source of truth: these two responses used to build the same object
4372
- * independently, which is how they drift.
4373
- *
4374
- * `extensions` (spec 2026-07-28) is the declaration point for opt-in
4375
- * extensions such as `io.modelcontextprotocol/tasks`. It is emitted only when
4376
- * the consumer actually declares one — an empty `extensions: {}` would read as
4377
- * "this server supports no extensions", which is a stronger claim than we can
4378
- * make while MCP Apps support is de-facto (via `ui://` resources) rather than
4379
- * declared. Wire it up here once the Apps extension identifier is pinned.
4380
- */
4381
- private buildServerCapabilities(): Record<string, unknown> {
4382
- const { extensions } = this.options;
4383
- // The declaration in options is the single source of truth: `taskStore` is
4384
- // created from it, so advertising and behaviour cannot drift apart.
4385
- return {
4386
- tools: {},
4387
- // Capability lifetime is defined by installed handlers, not the current
4388
- // Map size. A dynamic registry may correctly be empty at initialize and
4389
- // gain resources later; `listChanged` tells clients to refresh then.
4390
- resources: this.resourceHandlersInstalled
4391
- ? { listChanged: true }
4392
- : undefined,
4393
- ...(extensions && Object.keys(extensions).length > 0
4394
- ? { extensions }
4395
- : {}),
4396
- };
4397
- }
4398
-
4399
- /**
4400
- * Build the tools/list response, filtering out app-only tools
4401
- * and passing through outputSchema/annotations when defined.
4402
- */
4403
- private buildToolListing(): Array<Record<string, unknown>> {
4404
- return Array.from(this.tools.values())
4405
- .filter((t) => {
4406
- const vis = (t._meta?.ui as { visibility?: unknown } | undefined)
4407
- ?.visibility;
4408
- if (Array.isArray(vis) && !vis.includes("model")) return false;
4409
- return true;
4410
- })
4411
- .map((t) => {
4412
- const entry: Record<string, unknown> = {
4413
- name: t.name,
4414
- description: t.description,
4415
- inputSchema: t.inputSchema,
4416
- _meta: t._meta,
4417
- };
4418
- if (t.outputSchema !== undefined) entry.outputSchema = t.outputSchema;
4419
- if (t.annotations !== undefined) entry.annotations = t.annotations;
4420
- return entry;
4421
- })
4422
- // Spec 2026-07-28 (minor change 3): return tools in a deterministic order.
4423
- // It lets clients cache the list and improves LLM prompt-cache hit rates.
4424
- //
4425
- // Map iteration is already insertion-ordered, so this only matters where
4426
- // registration order itself is unstable — which it is for the relay/proxy
4427
- // case, where tools are registered as child servers are discovered
4428
- // asynchronously. Sorting by name makes the output independent of who
4429
- // answered first.
4430
- //
4431
- // Deliberately not `localeCompare`: that orders differently per host
4432
- // locale, reintroducing the very non-determinism being removed here.
4433
- .sort((a, b) =>
4434
- (a.name as string) < (b.name as string)
4435
- ? -1
4436
- : (a.name as string) > (b.name as string)
4437
- ? 1
4438
- : 0
4439
- );
4440
- }
4441
-
4442
- /**
4443
- * Check if a handler result is a StructuredToolResult
4444
- * (has content as string + structuredContent as object).
4445
- */
4446
- private isStructuredToolResult(
4447
- result: unknown,
4448
- ): result is StructuredToolResult {
4449
- if (!result || typeof result !== "object") return false;
4450
- const obj = result as Record<string, unknown>;
4451
- return (
4452
- typeof obj.content === "string" &&
4453
- obj.structuredContent !== null &&
4454
- obj.structuredContent !== undefined &&
4455
- typeof obj.structuredContent === "object" &&
4456
- !Array.isArray(obj.structuredContent)
4457
- );
4458
- }
4459
-
4460
- /**
4461
- * Build a CallToolResult from the handler's return value.
4462
- * Priority: preformatted > structuredToolResult > plain value.
4463
- */
4464
- private buildToolCallResult(
4465
- toolName: string,
4466
- result: unknown,
4467
- ): Record<string, unknown> {
4468
- // Proxy/gateway pattern — pass through as-is
4469
- if (this.isPreformattedResult(result)) {
4470
- return canonicaliseWireResult(result as Record<string, unknown>);
4471
- }
4472
-
4473
- const tool = this.tools.get(toolName);
4474
-
4475
- // StructuredToolResult: separate content (for LLM) and structuredContent (for viewer)
4476
- if (this.isStructuredToolResult(result)) {
4477
- const r: Record<string, unknown> = {
4478
- content: [{ type: "text", text: result.content }],
4479
- structuredContent: result.structuredContent,
4480
- };
4481
- if (tool?._meta) r._meta = tool._meta;
4482
- return canonicaliseWireResult(r);
4483
- }
4484
-
4485
- // Plain value: JSON-stringify into content[0].text
4486
- const r: Record<string, unknown> = {
4487
- content: [{
4488
- type: "text",
4489
- text: typeof result === "string"
4490
- ? result
4491
- : JSON.stringify(result, null, 2),
4492
- }],
4493
- };
4494
- if (tool?._meta) r._meta = tool._meta;
4495
- return canonicaliseWireResult(r);
4496
- }
4497
-
4498
- /**
4499
- * Handle a tool execution error using the configured toolErrorMapper.
4500
- * Returns an isError result if the mapper handles it, otherwise rethrows.
4501
- */
4502
- private handleToolError(
4503
- error: unknown,
4504
- toolName: string,
4505
- ): Record<string, unknown> {
4506
- const mapper = this.options.toolErrorMapper;
4507
- if (mapper) {
4508
- let msg: string | null;
4509
- try {
4510
- msg = mapper(error, toolName);
4511
- } catch (mapperError) {
4512
- this.log(
4513
- `toolErrorMapper threw for tool ${toolName}: ${
4514
- mapperError instanceof Error
4515
- ? mapperError.message
4516
- : String(mapperError)
4517
- } (original error: ${
4518
- error instanceof Error ? error.message : String(error)
4519
- })`,
4520
- );
4521
- // Fall through to rethrow original error
4522
- msg = null;
4523
- }
4524
- if (msg !== null) {
4525
- this.log(`Tool ${toolName} returned business error: ${msg}`);
4526
- return {
4527
- content: [{ type: "text", text: msg }],
4528
- isError: true,
4529
- };
4530
- }
4531
- }
4532
- // No mapper or mapper returned null → rethrow
4533
- this.log(
4534
- `Error executing tool ${toolName}: ${
4535
- error instanceof Error ? error.message : String(error)
4536
- }`,
4537
- );
4538
- throw error;
4539
- }
4540
-
4541
- /**
4542
- * Log message using custom logger or stderr
4543
- */
4544
- private log(msg: string): void {
4545
- if (this.options.logger) {
4546
- this.options.logger(msg);
4547
- } else {
4548
- console.error(`[${this.options.name}] ${msg}`);
4549
- }
4550
- }
4551
- }
4552
-
4553
- // ── registerViewers types ──────────────────────────────────────────
4554
-
4555
- /** Configuration for registerViewers() */
4556
- export interface RegisterViewersConfig {
4557
- /** URI prefix — viewers get `ui://{prefix}/{viewerName}` */
4558
- prefix: string;
4559
- /** import.meta.url of the consumer's server.ts (for resolving dist paths) */
4560
- moduleUrl: string;
4561
- /** Check if a path or URL exists. Receives a filesystem path for local
4562
- * modules (file://) or an HTTPS URL for remote modules (JSR, CDN). */
4563
- exists: (path: string) => boolean;
4564
- /** Read a file and return its content as string */
4565
- readFile: (path: string) => string | Promise<string>;
4566
- /** Explicit list of viewer names. If omitted, use `discover`. */
4567
- viewers?: string[];
4568
- /** Auto-discover viewers by scanning a directory */
4569
- discover?: {
4570
- uiDir: string;
4571
- } & DiscoverViewersFS;
4572
- /** Custom function to generate human-readable names. Default: kebab-to-Title. */
4573
- humanName?: (viewerName: string) => string;
4574
- /** MCP Apps CSP — declares external domains the viewer needs (tiles, APIs, CDNs).
4575
- * Uses McpUiCsp from @casys/mcp-compose (resourceDomains, connectDomains). */
4576
- csp?: {
4577
- resourceDomains?: string[];
4578
- connectDomains?: string[];
4579
- frameDomains?: string[];
4580
- };
4581
- }
4582
-
4583
- /** Summary returned by registerViewers() */
4584
- export interface RegisterViewersSummary {
4585
- registered: string[];
4586
- skipped: string[];
4587
- }
4588
-
4589
- /** Default: "invoice-viewer" → "Invoice Viewer" */
4590
- function defaultHumanName(name: string): string {
4591
- return name
4592
- .split("-")
4593
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
4594
- .join(" ");
4595
- }