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