@casys/mcp-server 0.26.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,10 @@ Protocol servers in TypeScript.
9
9
 
10
10
  Composable middleware, OAuth2 auth, dual transport, observability, and
11
11
  everything you need to ship reliable MCP servers. Built on the official
12
- [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/sdk).
12
+ [`@modelcontextprotocol/server`](https://www.npmjs.com/package/@modelcontextprotocol/server)
13
+ and
14
+ [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk)
15
+ packages.
13
16
 
14
17
  ```
15
18
  rate-limit → auth → custom middleware → scope-check → validation → backpressure → handler
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.26.0",
3
+ "version": "0.26.1",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
@@ -10,6 +10,7 @@
10
10
  "test": "tsx --test src/**/*_test.ts"
11
11
  },
12
12
  "dependencies": {
13
+ "@modelcontextprotocol/server": "^2.0.0",
13
14
  "@modelcontextprotocol/sdk": "^1.29.0",
14
15
  "@modelcontextprotocol/ext-apps": "^1.7.4",
15
16
  "hono": "^4.0.0",
package/src/mcp-app.ts CHANGED
@@ -4,28 +4,32 @@
4
4
  * High-performance MCP server with built-in concurrency control
5
5
  * and backpressure.
6
6
  *
7
- * Wraps the official @modelcontextprotocol/sdk with production-ready
8
- * middleware, auth, and observability features.
7
+ * Wraps the official MCP server packages with middleware, auth, and
8
+ * observability features.
9
9
  *
10
10
  * @module lib/server/mcp-app
11
11
  */
12
12
 
13
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
14
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
13
  import {
16
14
  type CallToolRequest,
17
- CallToolRequestSchema,
15
+ type CallToolResult,
18
16
  type ClientCapabilities,
19
- ErrorCode,
20
17
  type Implementation,
21
- type JSONRPCRequest,
22
- ListResourcesRequestSchema,
23
- ListResourceTemplatesRequestSchema,
24
- ListToolsRequestSchema,
25
- McpError,
18
+ type InputRequiredResult,
19
+ type ListResourcesResult,
20
+ type ListToolsResult,
21
+ ProtocolError,
22
+ ProtocolErrorCode,
26
23
  type ReadResourceRequest,
27
- ReadResourceRequestSchema,
28
- } from "@modelcontextprotocol/sdk/types.js";
24
+ Server,
25
+ type ServerCapabilities,
26
+ type ServerContext,
27
+ } from "@modelcontextprotocol/server";
28
+ import {
29
+ serveStdio,
30
+ type StdioServerHandle,
31
+ } from "@modelcontextprotocol/server/stdio";
32
+ import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
29
33
  import { Hono } from "hono";
30
34
  import { cors } from "hono/cors";
31
35
  import { RequestQueue } from "./concurrency/request-queue.js";
@@ -84,6 +88,7 @@ import {
84
88
  } from "./tasks/mod.js";
85
89
  import {
86
90
  checkInputRequestCapabilities,
91
+ guardMrtrRetry,
87
92
  importStateKey,
88
93
  type InputRequestEntry,
89
94
  type InputRequiredSignal,
@@ -91,7 +96,6 @@ import {
91
96
  type MrtrReplayStore,
92
97
  paramsDigest,
93
98
  sealRequestState,
94
- verifyRequestState,
95
99
  } from "./mrtr/mod.js";
96
100
  import {
97
101
  buildAcknowledgedMessage,
@@ -120,7 +124,11 @@ import {
120
124
  noPrincipalError,
121
125
  taskOwnerKeyFor,
122
126
  } from "./http/request-guards.js";
123
- import { isRecord, jsonRpcResponse } from "./http/wire.js";
127
+ import {
128
+ isRecord,
129
+ jsonRpcResponse,
130
+ MRTR_NO_AUTH_PRINCIPAL,
131
+ } from "./http/wire.js";
124
132
 
125
133
  /**
126
134
  * Tool definition with handler
@@ -423,7 +431,6 @@ export class McpApp {
423
431
  * `initialize` response.
424
432
  */
425
433
  public readonly name: string;
426
- private mcpServer: McpServer;
427
434
  private requestQueue: RequestQueue;
428
435
  private rateLimiter: RateLimiter | null = null;
429
436
  private schemaValidator: SchemaValidator | null = null;
@@ -466,6 +473,12 @@ export class McpApp {
466
473
  */
467
474
  private subscriptions: SubscriptionRegistry | null = null;
468
475
 
476
+ /** Era-aware stdio serving handle, present only while start() is active. */
477
+ private stdioHandle: StdioServerHandle | null = null;
478
+
479
+ /** Protocol instance pinned by the stdio era negotiator, when connected. */
480
+ private activeStdioServer: Server | null = null;
481
+
469
482
  /**
470
483
  * Imported HMAC key for sealing `requestState`, or `null` when the deployment
471
484
  * configured none.
@@ -582,23 +595,6 @@ export class McpApp {
582
595
  );
583
596
  }
584
597
 
585
- // Create SDK MCP server
586
- this.mcpServer = new McpServer(
587
- {
588
- name: options.name,
589
- version: options.version,
590
- },
591
- {
592
- capabilities: {
593
- tools: {},
594
- ...(options.expectResources
595
- ? { resources: { listChanged: true } }
596
- : {}),
597
- },
598
- instructions: options.instructions,
599
- },
600
- );
601
-
602
598
  // Create request queue with concurrency control
603
599
  this.requestQueue = new RequestQueue({
604
600
  maxConcurrent: options.maxConcurrent ?? 10,
@@ -619,13 +615,59 @@ export class McpApp {
619
615
  this.schemaValidator = new SchemaValidator();
620
616
  }
621
617
 
622
- // Setup MCP protocol handlers
623
- this.setupHandlers();
618
+ // A stdio probe may be discarded before a legacy fallback is opened. The
619
+ // official serving entry therefore requires a factory, and every factory
620
+ // invocation must receive a fresh protocol instance. Registries and the
621
+ // middleware pipeline remain on McpApp; handlers close over those maps.
622
+ this.resourceHandlersInstalled = options.expectResources === true;
623
+ }
624
624
 
625
- // Pre-declare resources capability so resources can be added after start()
626
- if (options.expectResources) {
627
- this.installResourceHandlers();
625
+ /** Build one unconnected SDK server for one negotiated stdio era. */
626
+ private createProtocolServer(): Server {
627
+ const cacheHint = {
628
+ ttlMs: this.cacheTtlMs,
629
+ cacheScope: this.options.cache?.scope ?? "private",
630
+ } as const;
631
+ // Tasks currently have an HTTP adapter only. Keep its extension out of
632
+ // stdio discovery until the same application port is served here; claiming
633
+ // it and answering every tasks/* call with MethodNotFound would make the
634
+ // capability declaration a lie. Other consumer-declared extensions remain
635
+ // transport-neutral.
636
+ const stdioExtensions = Object.fromEntries(
637
+ Object.entries(this.options.extensions ?? {}).filter(
638
+ ([id]) => id !== TASKS_EXTENSION_ID,
639
+ ),
640
+ );
641
+ const capabilities = {
642
+ // No listChanged promise: live tool registration does not currently emit
643
+ // tools/list_changed. The registry remains usable, but refresh is not a
644
+ // protocol guarantee until that notification is wired.
645
+ tools: {},
646
+ ...(Object.keys(stdioExtensions).length > 0
647
+ ? {
648
+ extensions: stdioExtensions as Record<string, object>,
649
+ }
650
+ : {}),
651
+ } as ServerCapabilities;
652
+ const server = new Server(
653
+ { name: this.options.name, version: this.options.version },
654
+ {
655
+ capabilities,
656
+ instructions: this.options.instructions,
657
+ cacheHints: {
658
+ "server/discover": cacheHint,
659
+ "tools/list": cacheHint,
660
+ "resources/list": cacheHint,
661
+ "resources/templates/list": cacheHint,
662
+ "resources/read": cacheHint,
663
+ },
664
+ },
665
+ );
666
+ this.setupHandlers(server);
667
+ if (this.resourceHandlersInstalled) {
668
+ this.installResourceHandlersOn(server);
628
669
  }
670
+ return server;
629
671
  }
630
672
 
631
673
  /**
@@ -644,29 +686,32 @@ export class McpApp {
644
686
  "Set expectResources: true or register resources before start().",
645
687
  );
646
688
  }
647
- const server = this.mcpServer.server;
689
+ this.resourceHandlersInstalled = true;
690
+ }
648
691
 
692
+ /** Install resource handlers on one fresh protocol instance. */
693
+ private installResourceHandlersOn(server: Server): void {
649
694
  // Declare resources capability before transport connects
650
695
  server.registerCapabilities({ resources: { listChanged: true } });
651
696
 
652
697
  // resources/list — returns currently registered resources
653
- server.setRequestHandler(ListResourcesRequestSchema, () => {
698
+ server.setRequestHandler("resources/list", () => {
654
699
  return {
655
700
  resources: Array.from(this.resources.values()).map((r) =>
656
701
  this.toResourceListing(r.resource)
657
702
  ),
658
- };
703
+ } as unknown as ListResourcesResult;
659
704
  });
660
705
 
661
706
  // resources/read — serve resource content by URI
662
707
  server.setRequestHandler(
663
- ReadResourceRequestSchema,
708
+ "resources/read",
664
709
  async (request: ReadResourceRequest) => {
665
710
  const uri = request.params.uri;
666
711
  const info = this.resources.get(uri);
667
712
  if (!info) {
668
- throw new McpError(
669
- ErrorCode.InvalidParams,
713
+ throw new ProtocolError(
714
+ ProtocolErrorCode.InvalidParams,
670
715
  `Resource not found: ${uri}`,
671
716
  );
672
717
  }
@@ -692,34 +737,33 @@ export class McpApp {
692
737
  // We currently expose concrete resources only. An explicit empty template
693
738
  // list is nevertheless required once the resources capability exists:
694
739
  // clients are entitled to ask which URI templates can be expanded.
695
- server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
740
+ server.setRequestHandler("resources/templates/list", () => ({
696
741
  resourceTemplates: [],
697
742
  }));
698
-
699
- this.resourceHandlersInstalled = true;
700
743
  this.resourceLog("Resources capability installed");
701
744
  }
702
745
 
703
746
  /**
704
747
  * Setup MCP protocol request handlers
705
748
  */
706
- private setupHandlers(): void {
707
- const server = this.mcpServer.server;
708
-
749
+ private setupHandlers(server: Server): void {
709
750
  // Wire up "initialized" notification callback (post-handshake)
710
751
  server.oninitialized = () => {
711
752
  this.initializedCallback?.();
712
753
  };
713
754
 
714
755
  // tools/list handler
715
- server.setRequestHandler(ListToolsRequestSchema, () => {
716
- return { tools: this.buildToolListing() };
756
+ server.setRequestHandler("tools/list", () => {
757
+ return { tools: this.buildToolListing() } as unknown as ListToolsResult;
717
758
  });
718
759
 
719
760
  // tools/call handler (delegates to middleware pipeline)
720
761
  server.setRequestHandler(
721
- CallToolRequestSchema,
722
- async (request: CallToolRequest) => {
762
+ "tools/call",
763
+ async (
764
+ request: CallToolRequest,
765
+ ctx: ServerContext,
766
+ ): Promise<CallToolResult | InputRequiredResult> => {
723
767
  const toolName = request.params.name;
724
768
  const args = request.params.arguments || {};
725
769
 
@@ -728,15 +772,70 @@ export class McpApp {
728
772
  // hardest to correlate back to the host that caused it; `logLevel` is
729
773
  // read for the same reason it is on HTTP — the spec makes it
730
774
  // per-request, and a handler must stay silent without it.
731
- const meta = request.params._meta;
732
- const clientMeta: StatelessClientMeta | undefined = isRecord(meta)
733
- ? {
734
- ...readTraceContext(meta),
735
- ...(readLogLevel(meta) !== undefined
736
- ? { logLevel: readLogLevel(meta) }
737
- : {}),
738
- }
775
+ const meta = isRecord(request.params._meta)
776
+ ? request.params._meta
777
+ : undefined;
778
+ const envelope = isRecord(ctx.mcpReq.envelope)
779
+ ? ctx.mcpReq.envelope
739
780
  : undefined;
781
+ const clientInfo = envelope?.[STATELESS_CLIENT_INFO_KEY] as
782
+ | Implementation
783
+ | undefined ?? server.getClientVersion();
784
+ const clientCapabilities = envelope?.[
785
+ STATELESS_CLIENT_CAPABILITIES_KEY
786
+ ] as ClientCapabilities | undefined ??
787
+ server.getClientCapabilities();
788
+ const requestedLogLevel = envelope !== undefined
789
+ ? readLogLevel(envelope)
790
+ : undefined;
791
+ const traceContext = meta !== undefined
792
+ ? readTraceContext(meta)
793
+ : undefined;
794
+ const clientMeta: StatelessClientMeta | undefined =
795
+ clientInfo !== undefined || clientCapabilities !== undefined ||
796
+ requestedLogLevel !== undefined || traceContext !== undefined
797
+ ? {
798
+ ...(clientInfo !== undefined ? { clientInfo } : {}),
799
+ ...(clientCapabilities !== undefined
800
+ ? { clientCapabilities }
801
+ : {}),
802
+ ...(requestedLogLevel !== undefined
803
+ ? { logLevel: requestedLogLevel }
804
+ : {}),
805
+ ...(traceContext ?? {}),
806
+ }
807
+ : undefined;
808
+
809
+ // The v2 protocol layer lifts MRTR retry fields out of params before
810
+ // invoking the handler. Preserve Casys' method/argument/principal and
811
+ // single-use bindings on stdio just as the HTTP path does.
812
+ const ingressDigest = await paramsDigest({
813
+ arguments: args,
814
+ name: toolName,
815
+ });
816
+ if ((ctx.mcpReq.droppedInputResponseKeys?.length ?? 0) > 0) {
817
+ throw new ProtocolError(
818
+ ProtocolErrorCode.InvalidParams,
819
+ "inputResponses entries must be bare MCP result objects",
820
+ {
821
+ problem: "malformed_input_responses",
822
+ droppedKeys: ctx.mcpReq.droppedInputResponseKeys,
823
+ recovery:
824
+ "Send each inputResponses value as the bare result object, without a {method, result} wrapper.",
825
+ },
826
+ );
827
+ }
828
+ const inputResponses = ctx.mcpReq.inputResponses;
829
+ const echoedState = ctx.mcpReq.requestState<string>();
830
+ const mrtr = await this.prepareProtocolMrtrRetry(
831
+ inputResponses,
832
+ echoedState,
833
+ {
834
+ principal: MRTR_NO_AUTH_PRINCIPAL,
835
+ method: "tools/call",
836
+ paramsDigest: ingressDigest,
837
+ },
838
+ );
740
839
 
741
840
  let result: unknown;
742
841
  try {
@@ -747,60 +846,52 @@ export class McpApp {
747
846
  undefined,
748
847
  undefined,
749
848
  clientMeta,
849
+ mrtr,
750
850
  );
751
851
  } catch (error) {
752
- return this.handleToolError(error, toolName);
852
+ return this.handleToolError(
853
+ error,
854
+ toolName,
855
+ ) as unknown as CallToolResult;
856
+ }
857
+
858
+ if (isRecord(result) && result["resultType"] === "input_required") {
859
+ const built = await this.buildInputRequiredResult(
860
+ result as unknown as InputRequiredSignal,
861
+ {
862
+ clientCapabilities,
863
+ principal: MRTR_NO_AUTH_PRINCIPAL,
864
+ method: "tools/call",
865
+ paramsDigest: ingressDigest,
866
+ },
867
+ );
868
+ if (!built.ok) {
869
+ throw new ProtocolError(
870
+ built.code,
871
+ built.message,
872
+ built.data,
873
+ );
874
+ }
875
+ return built.result as unknown as InputRequiredResult;
753
876
  }
754
877
 
755
878
  // Serialization errors are framework bugs, not tool errors —
756
879
  // let them propagate
757
- return this.buildToolCallResult(toolName, result);
880
+ return this.buildToolCallResult(
881
+ toolName,
882
+ result,
883
+ ) as unknown as CallToolResult;
758
884
  },
759
885
  );
760
-
761
- // `server/discover` over stdio (spec 2026-07-28, SEP-2575).
762
- //
763
- // The spec makes this RPC a MUST for every server and names stdio as a
764
- // primary use: a client probes it for backward compatibility. That matters
765
- // here precisely because the SDK's stdio handshake still negotiates
766
- // 2025-11-25 — `server/discover` is then the only way for a peer to learn
767
- // this server also speaks 2026-07-28 over HTTP.
768
- //
769
- // Routed through `fallbackRequestHandler` rather than `setRequestHandler`
770
- // because the latter takes a Zod schema, and the method is absent from the
771
- // SDK's type surface. Adding a Zod dependency to declare one schema would
772
- // put a peer dependency in the public API for a single string comparison.
773
- // Every other unknown method keeps its previous answer: MethodNotFound.
774
- server.fallbackRequestHandler = (request: JSONRPCRequest) => {
775
- if (request.method !== "server/discover") {
776
- // Same text the SDK used for an unrouted method. It still reaches the
777
- // wire as "MCP error -32601: Method not found" — `McpError` prefixes
778
- // its own message and a handler cannot raise the code without it. The
779
- // code is unchanged, which is what a peer switches on; the string
780
- // difference is pinned by a test and noted in the changelog. Appending
781
- // the method name on top of that would have been a second, gratuitous
782
- // change to the same field.
783
- throw new McpError(ErrorCode.MethodNotFound, "Method not found");
784
- }
785
- return Promise.resolve(this.buildDiscoverResult());
786
- };
787
886
  }
788
887
 
789
888
  /**
790
- * The `server/discover` result (spec 2026-07-28, SEP-2575).
791
- *
792
- * Single source of truth for both transports. They used to be one inline
793
- * object on the HTTP path; a stdio copy would have been the second place to
794
- * forget `instructions` or a new capability.
889
+ * The stateless HTTP `server/discover` result (spec 2026-07-28, SEP-2575).
795
890
  *
796
- * Always stamped as 2026-07-28 regardless of what the transport negotiated.
797
- * That is deliberate but not free: nothing gates the method, so a peer that
798
- * negotiated `2025-11-25` over stdio can call it and receive an envelope it
799
- * never agreed to. The alternative is worse — stamping the negotiated version
800
- * would make the probe answer "2025" to the client asking whether this server
801
- * speaks 2026, which is the one question it exists to answer. Treat
802
- * `server/discover` as a cross-version exception: its result describes what
803
- * the server supports, not what the current transport negotiated.
891
+ * The stdio adapter deliberately does not call this builder: the official v2
892
+ * serving entry owns discover, era selection, result stamping and its final
893
+ * wire shape. Keeping this method HTTP-specific prevents a custom payload
894
+ * from bypassing that authority again.
804
895
  */
805
896
  private buildDiscoverResult(): Record<string, unknown> {
806
897
  return this.stampResult(
@@ -1434,19 +1525,19 @@ export class McpApp {
1434
1525
  */
1435
1526
  private notifyResourceListChanged(): void {
1436
1527
  if (!this.started) return;
1437
- try {
1438
- if (this.subscriptions !== null) {
1439
- this.sendNotification("notifications/resources/list_changed");
1440
- } else {
1441
- this.mcpServer.sendResourceListChanged();
1442
- }
1443
- } catch (error) {
1528
+ if (this.subscriptions !== null) {
1529
+ this.sendNotification("notifications/resources/list_changed");
1530
+ return;
1531
+ }
1532
+ const server = this.activeStdioServer;
1533
+ if (server === null) return;
1534
+ void server.sendResourceListChanged().catch((error) => {
1444
1535
  this.resourceLog(
1445
1536
  `[WARN] Resource list changed notification was not delivered: ${
1446
1537
  error instanceof Error ? error.message : String(error)
1447
1538
  }`,
1448
1539
  );
1449
- }
1540
+ });
1450
1541
  }
1451
1542
 
1452
1543
  /**
@@ -1697,6 +1788,9 @@ export class McpApp {
1697
1788
  /**
1698
1789
  * Start the MCP server with stdio transport
1699
1790
  */
1791
+ // Keep the established Promise API and rejection semantics even though the
1792
+ // v2 serving entry returns its close handle synchronously.
1793
+ // deno-lint-ignore require-await
1700
1794
  async start(): Promise<void> {
1701
1795
  // Guard FIRST. Resetting before the guard meant a concurrent start() during
1702
1796
  // stop() cleared `stopping` and rebuilt the store on its way to failing with
@@ -1714,8 +1808,20 @@ export class McpApp {
1714
1808
  // Build middleware pipeline before connecting transport
1715
1809
  this.buildPipeline();
1716
1810
 
1717
- const transport = new StdioServerTransport();
1718
- await this.mcpServer.server.connect(transport);
1811
+ this.stdioHandle = serveStdio(() => {
1812
+ const server = this.createProtocolServer();
1813
+ this.activeStdioServer = server;
1814
+ server.onclose = () => {
1815
+ if (this.activeStdioServer === server) {
1816
+ this.activeStdioServer = null;
1817
+ }
1818
+ };
1819
+ return server;
1820
+ }, {
1821
+ onerror: (error) => {
1822
+ this.log(`[ERROR] stdio transport: ${error.message}`);
1823
+ },
1824
+ });
1719
1825
 
1720
1826
  this.started = true;
1721
1827
 
@@ -1791,7 +1897,12 @@ export class McpApp {
1791
1897
  this.httpServer = null;
1792
1898
  }
1793
1899
 
1794
- await this.mcpServer.server.close();
1900
+ if (this.stdioHandle) {
1901
+ const handle = this.stdioHandle;
1902
+ this.stdioHandle = null;
1903
+ await handle.close();
1904
+ }
1905
+ this.activeStdioServer = null;
1795
1906
  this.started = false;
1796
1907
 
1797
1908
  this.log("Server stopped");
@@ -2459,8 +2570,6 @@ export class McpApp {
2459
2570
  ? params["requestState"]
2460
2571
  : undefined;
2461
2572
 
2462
- let retryVerified: boolean | undefined;
2463
-
2464
2573
  // A retry carrying answers but no token cannot be verified, and the
2465
2574
  // server always issues a token when it has a key. So this combination
2466
2575
  // is either a confused client or an attempt to inject answers past the
@@ -2478,10 +2587,31 @@ export class McpApp {
2478
2587
  )
2479
2588
  : { key: null as CryptoKey | null };
2480
2589
  if ("error" in guardKey) return guardKey.error;
2481
- if (
2482
- echoedResponses !== undefined && echoedState === undefined &&
2483
- guardKey.key !== null
2484
- ) {
2590
+ // Only a signed retry needs an authenticated principal. Ordinary
2591
+ // calls and explicitly unprotected state retain their prior behavior.
2592
+ let retryPrincipal = MRTR_NO_AUTH_PRINCIPAL;
2593
+ if (echoedState !== undefined && guardKey.key !== null) {
2594
+ const principal = callerPrincipal(httpAuthInfo);
2595
+ if (principal === null) {
2596
+ return noPrincipalError(id, statelessVersion);
2597
+ }
2598
+ retryPrincipal = principal;
2599
+ }
2600
+
2601
+ const retryOutcome = await guardMrtrRetry({
2602
+ ...(echoedResponses !== undefined
2603
+ ? { inputResponses: echoedResponses }
2604
+ : {}),
2605
+ ...(echoedState !== undefined ? { requestState: echoedState } : {}),
2606
+ key: guardKey.key,
2607
+ replayStore: this.mrtrReplayStore,
2608
+ bindings: {
2609
+ principal: retryPrincipal,
2610
+ method: "tools/call",
2611
+ paramsDigest: ingressDigest,
2612
+ },
2613
+ });
2614
+ if (retryOutcome.kind === "missing_state") {
2485
2615
  return jsonRpcResponse(
2486
2616
  {
2487
2617
  jsonrpc: "2.0",
@@ -2498,129 +2628,65 @@ export class McpApp {
2498
2628
  },
2499
2629
  },
2500
2630
  400,
2631
+ { "MCP-Protocol-Version": statelessVersion },
2632
+ );
2633
+ }
2634
+ if (retryOutcome.kind === "invalid_state") {
2635
+ return jsonRpcResponse(
2501
2636
  {
2502
- "MCP-Protocol-Version": statelessVersion,
2637
+ jsonrpc: "2.0",
2638
+ id,
2639
+ error: {
2640
+ code: JSONRPC_INVALID_PARAMS,
2641
+ message: `Invalid requestState: ${retryOutcome.reason}`,
2642
+ data: { reason: retryOutcome.reason },
2643
+ },
2503
2644
  },
2645
+ 400,
2646
+ { "MCP-Protocol-Version": statelessVersion },
2504
2647
  );
2505
2648
  }
2506
-
2507
- if (echoedState !== undefined) {
2508
- const key = guardKey.key;
2509
- if (key === null) {
2510
- // Unprotected mode: nothing to verify, and the handler is told so
2511
- // rather than being handed a false assurance.
2512
- retryVerified = false;
2513
- } else {
2514
- // On an authenticated server this binds the token to one user, so
2515
- // a token minted for A cannot be spent by B. On an UNAUTHENTICATED
2516
- // server every caller is "anonymous", and the binding protects
2517
- // nothing — correctly so: without auth there is no user boundary to
2518
- // cross, and any caller could invoke the tool directly anyway. The
2519
- // method and argument bindings still apply in both cases.
2520
- const principal = callerPrincipal(httpAuthInfo);
2521
- if (principal === null) {
2522
- return noPrincipalError(
2523
- id,
2524
- statelessVersion,
2525
- );
2526
- }
2527
- const verdict = await verifyRequestState(echoedState, key, {
2528
- principal,
2529
- method: "tools/call",
2530
- paramsDigest: ingressDigest,
2531
- });
2532
- if (!verdict.ok) {
2533
- // Attacker-controlled input that failed its integrity or binding
2534
- // checks. Rejected before the handler runs, and the reason is
2535
- // returned so a legitimate client can recover (e.g. re-elicit
2536
- // after an expiry) rather than guessing.
2537
- return jsonRpcResponse(
2538
- {
2539
- jsonrpc: "2.0",
2540
- id,
2541
- error: {
2542
- code: JSONRPC_INVALID_PARAMS,
2543
- message: `Invalid requestState: ${verdict.reason}`,
2544
- data: { reason: verdict.reason },
2545
- },
2546
- },
2547
- 400,
2548
- );
2549
- }
2550
-
2551
- const replayStore = this.mrtrReplayStore;
2552
- if (replayStore === null) {
2553
- return jsonRpcResponse(
2554
- {
2555
- jsonrpc: "2.0",
2556
- id,
2557
- error: {
2558
- code: ErrorCode.InternalError,
2559
- message: "MRTR replay protection is unavailable",
2560
- data: {
2561
- problem: "mrtr_replay_store_unavailable",
2562
- recovery:
2563
- "Configure mrtr.signingKey with a working replay store and retry the full interaction.",
2564
- },
2565
- },
2566
- },
2567
- 500,
2568
- { "MCP-Protocol-Version": statelessVersion },
2569
- );
2570
- }
2571
-
2572
- let consumed: boolean;
2573
- try {
2574
- const storeResult = await replayStore.consume(
2575
- verdict.payload.nonce,
2576
- verdict.payload.exp,
2577
- );
2578
- if (storeResult !== true && storeResult !== false) {
2579
- throw new Error(
2580
- "mrtr.replayStore.consume() must return a boolean",
2581
- );
2582
- }
2583
- consumed = storeResult;
2584
- } catch {
2585
- this.log(
2586
- "[WARN] MRTR replay store unavailable; retry rejected before handler",
2587
- );
2588
- return jsonRpcResponse(
2589
- {
2590
- jsonrpc: "2.0",
2591
- id,
2592
- error: {
2593
- code: ErrorCode.InternalError,
2594
- message: "MRTR replay protection is unavailable",
2595
- data: {
2596
- problem: "mrtr_replay_store_unavailable",
2597
- recovery:
2598
- "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2599
- },
2600
- },
2601
- },
2602
- 500,
2603
- { "MCP-Protocol-Version": statelessVersion },
2604
- );
2605
- }
2606
- if (!consumed) {
2607
- return jsonRpcResponse(
2608
- {
2609
- jsonrpc: "2.0",
2610
- id,
2611
- error: {
2612
- code: JSONRPC_INVALID_PARAMS,
2613
- message: "Invalid requestState: replayed",
2614
- data: { reason: "replayed" },
2615
- },
2616
- },
2617
- 400,
2618
- { "MCP-Protocol-Version": statelessVersion },
2619
- );
2620
- }
2621
- retryVerified = true;
2649
+ if (retryOutcome.kind === "replay_store_unavailable") {
2650
+ if (retryOutcome.reason === "consume_failed") {
2651
+ this.log(
2652
+ "[WARN] MRTR replay store unavailable; retry rejected before handler",
2653
+ );
2622
2654
  }
2655
+ return jsonRpcResponse(
2656
+ {
2657
+ jsonrpc: "2.0",
2658
+ id,
2659
+ error: {
2660
+ code: ErrorCode.InternalError,
2661
+ message: "MRTR replay protection is unavailable",
2662
+ data: {
2663
+ problem: "mrtr_replay_store_unavailable",
2664
+ recovery: retryOutcome.reason === "missing"
2665
+ ? "Configure mrtr.signingKey with a working replay store and retry the full interaction."
2666
+ : "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2667
+ },
2668
+ },
2669
+ },
2670
+ 500,
2671
+ { "MCP-Protocol-Version": statelessVersion },
2672
+ );
2673
+ }
2674
+ if (retryOutcome.kind === "replayed") {
2675
+ return jsonRpcResponse(
2676
+ {
2677
+ jsonrpc: "2.0",
2678
+ id,
2679
+ error: {
2680
+ code: JSONRPC_INVALID_PARAMS,
2681
+ message: "Invalid requestState: replayed",
2682
+ data: { reason: "replayed" },
2683
+ },
2684
+ },
2685
+ 400,
2686
+ { "MCP-Protocol-Version": statelessVersion },
2687
+ );
2623
2688
  }
2689
+ const retryVerified = retryOutcome.retryVerified;
2624
2690
 
2625
2691
  try {
2626
2692
  const result = await this.executeToolCall(
@@ -3570,7 +3636,9 @@ export class McpApp {
3570
3636
  * @see {@link MCP_APPS_EXTENSION_ID} for the extension key
3571
3637
  */
3572
3638
  getClientMcpAppsCapability(): McpAppsClientCapability | undefined {
3573
- return getMcpAppsCapability(this.mcpServer.server.getClientCapabilities());
3639
+ return getMcpAppsCapability(
3640
+ this.activeStdioServer?.getClientCapabilities(),
3641
+ );
3574
3642
  }
3575
3643
 
3576
3644
  /**
@@ -3745,12 +3813,14 @@ export class McpApp {
3745
3813
  }
3746
3814
  }
3747
3815
 
3748
- // For stdio mode, send via SDK transport
3749
- try {
3750
- this.mcpServer.server.notification({ method, params });
3751
- } catch {
3752
- // Transport may not support notifications yet (pre-initialized)
3753
- }
3816
+ // For stdio mode, send via the one protocol instance pinned by the era
3817
+ // negotiator. A probe instance may already be closed while its replacement
3818
+ // is being built, so never route through the constructor-time template.
3819
+ const server = this.activeStdioServer;
3820
+ if (server === null) return;
3821
+ void server.notification({ method, params }).catch(() => {
3822
+ // Transport may not support notifications yet (pre-initialized).
3823
+ });
3754
3824
  }
3755
3825
 
3756
3826
  /**
@@ -3788,8 +3858,9 @@ export class McpApp {
3788
3858
  * Apply the spec-2026-07-28 result envelope when — and only when — the peer
3789
3859
  * negotiated that revision.
3790
3860
  *
3791
- * Always applies on the stateless transport, which only accepts 2026-07-28.
3792
- * Stdio mode passes `undefined` and stays on the legacy shape.
3861
+ * This helper applies on the custom stateless HTTP transport, which only
3862
+ * accepts 2026-07-28. Stdio results are neutral here: the official v2 codec
3863
+ * stamps modern responses and leaves a negotiated legacy connection clean.
3793
3864
  *
3794
3865
  * Omitting the envelope for a genuinely legacy peer is safe in the other
3795
3866
  * direction too: the spec instructs clients to read a missing `resultType` as
@@ -3817,6 +3888,104 @@ export class McpApp {
3817
3888
  };
3818
3889
  }
3819
3890
 
3891
+ /**
3892
+ * Validate one MRTR retry delivered through the v2 protocol server.
3893
+ *
3894
+ * The SDK owns era-specific lifting and legacy fulfilment; Casys owns the
3895
+ * integrity bindings and nonce consumption of its sealed requestState.
3896
+ * Protocol errors deliberately escape the tool-error wrapper so clients see
3897
+ * a JSON-RPC error instead of a successful tools/call result with isError.
3898
+ */
3899
+ private async prepareProtocolMrtrRetry(
3900
+ inputResponses: Record<string, unknown> | undefined,
3901
+ requestState: string | undefined,
3902
+ context: {
3903
+ principal: string;
3904
+ method: string;
3905
+ paramsDigest: string;
3906
+ },
3907
+ ): Promise<{
3908
+ inputResponses?: Record<string, unknown>;
3909
+ retryVerified?: boolean;
3910
+ }> {
3911
+ const needsKey = inputResponses !== undefined || requestState !== undefined;
3912
+ let key: CryptoKey | null = null;
3913
+ if (needsKey) {
3914
+ try {
3915
+ key = await this.getMrtrKey();
3916
+ } catch (error) {
3917
+ throw new ProtocolError(
3918
+ ProtocolErrorCode.InternalError,
3919
+ "MRTR signing key is unavailable",
3920
+ {
3921
+ problem: "mrtr_key_unavailable",
3922
+ detail: error instanceof Error ? error.message : String(error),
3923
+ recovery:
3924
+ "Check mrtr.signingKey. The import is retried on the next request, so a transient failure clears itself.",
3925
+ },
3926
+ );
3927
+ }
3928
+ }
3929
+
3930
+ const outcome = await guardMrtrRetry({
3931
+ ...(inputResponses !== undefined ? { inputResponses } : {}),
3932
+ ...(requestState !== undefined ? { requestState } : {}),
3933
+ key,
3934
+ replayStore: this.mrtrReplayStore,
3935
+ bindings: context,
3936
+ });
3937
+
3938
+ if (outcome.kind === "missing_state") {
3939
+ throw new ProtocolError(
3940
+ ProtocolErrorCode.InvalidParams,
3941
+ "inputResponses supplied without the requestState issued with them",
3942
+ {
3943
+ problem: "missing_request_state",
3944
+ recovery:
3945
+ "Echo back the exact requestState string from the InputRequiredResult alongside inputResponses.",
3946
+ },
3947
+ );
3948
+ }
3949
+ if (outcome.kind === "invalid_state") {
3950
+ throw new ProtocolError(
3951
+ ProtocolErrorCode.InvalidParams,
3952
+ `Invalid requestState: ${outcome.reason}`,
3953
+ { reason: outcome.reason },
3954
+ );
3955
+ }
3956
+ if (outcome.kind === "replay_store_unavailable") {
3957
+ if (outcome.reason === "consume_failed") {
3958
+ this.log(
3959
+ "[WARN] MRTR replay store unavailable; retry rejected before handler",
3960
+ );
3961
+ }
3962
+ throw new ProtocolError(
3963
+ ProtocolErrorCode.InternalError,
3964
+ "MRTR replay protection is unavailable",
3965
+ {
3966
+ problem: "mrtr_replay_store_unavailable",
3967
+ recovery: outcome.reason === "missing"
3968
+ ? "Configure mrtr.signingKey with a working replay store and retry the full interaction."
3969
+ : "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
3970
+ },
3971
+ );
3972
+ }
3973
+ if (outcome.kind === "replayed") {
3974
+ throw new ProtocolError(
3975
+ ProtocolErrorCode.InvalidParams,
3976
+ "Invalid requestState: replayed",
3977
+ { reason: "replayed" },
3978
+ );
3979
+ }
3980
+
3981
+ return {
3982
+ ...(inputResponses !== undefined ? { inputResponses } : {}),
3983
+ ...(outcome.retryVerified !== undefined
3984
+ ? { retryVerified: outcome.retryVerified }
3985
+ : {}),
3986
+ };
3987
+ }
3988
+
3820
3989
  /**
3821
3990
  * Resolve the MRTR signing key once, warning if a deployment has none.
3822
3991
  *
package/src/mrtr/mod.ts CHANGED
@@ -22,6 +22,14 @@ export type {
22
22
  } from "./replay-store.js";
23
23
  export { MemoryMrtrReplayStore } from "./replay-store.js";
24
24
 
25
+ // Transport-neutral retry admission: integrity bindings + single-use replay gate.
26
+ export type {
27
+ GuardMrtrRetryInput,
28
+ MrtrRetryBindings,
29
+ MrtrRetryGuardOutcome,
30
+ } from "./retry-guard.js";
31
+ export { guardMrtrRetry } from "./retry-guard.js";
32
+
25
33
  // requestState seal/verify (HMAC-SHA256 integrity protection)
26
34
  export type {
27
35
  RequestStatePayload,
@@ -0,0 +1,110 @@
1
+ /**
2
+ * MRTR retry admission policy.
3
+ *
4
+ * This module owns the transport-independent decision whether a retried
5
+ * request may reach application code. HTTP and stdio adapt its outcomes to
6
+ * their respective error envelopes; neither transport reimplements HMAC
7
+ * verification or nonce consumption.
8
+ *
9
+ * @module lib/server/mrtr/retry-guard
10
+ */
11
+
12
+ import type { MrtrReplayStore } from "./replay-store.js";
13
+ import {
14
+ type RequestStateRejectionReason,
15
+ verifyRequestState,
16
+ } from "./request-state.js";
17
+
18
+ /** Bind a requestState to the retry that is attempting to spend it. */
19
+ export interface MrtrRetryBindings {
20
+ readonly principal: string;
21
+ readonly method: string;
22
+ readonly paramsDigest: string;
23
+ }
24
+
25
+ /** Inputs required to decide whether one MRTR retry is admissible. */
26
+ export interface GuardMrtrRetryInput {
27
+ /** Presence matters; response contents remain untrusted handler input. */
28
+ readonly inputResponses?: Record<string, unknown>;
29
+ /** Attacker-controlled state echoed by the client, when any. */
30
+ readonly requestState?: string;
31
+ /** Null deliberately represents the explicitly unprotected deployment mode. */
32
+ readonly key: CryptoKey | null;
33
+ /** Required only when a signed requestState is presented. */
34
+ readonly replayStore: MrtrReplayStore | null;
35
+ readonly bindings: MrtrRetryBindings;
36
+ }
37
+
38
+ /**
39
+ * Transport-neutral admission outcome.
40
+ *
41
+ * `accepted.retryVerified` is deliberately tri-state: absent for a first leg,
42
+ * false for the configured unprotected mode, and true only after signature,
43
+ * binding and atomic nonce reservation all succeeded.
44
+ */
45
+ export type MrtrRetryGuardOutcome =
46
+ | { readonly kind: "accepted"; readonly retryVerified?: boolean }
47
+ | { readonly kind: "missing_state" }
48
+ | {
49
+ readonly kind: "invalid_state";
50
+ readonly reason: RequestStateRejectionReason;
51
+ }
52
+ | {
53
+ readonly kind: "replay_store_unavailable";
54
+ readonly reason: "missing" | "consume_failed";
55
+ }
56
+ | { readonly kind: "replayed" };
57
+
58
+ /**
59
+ * Decide whether a retried request may enter application code.
60
+ *
61
+ * A signed state is verified and its nonce is atomically reserved before the
62
+ * handler runs. This intentionally gives at-most-once admission, not exactly
63
+ * once completion: a transport adapter must never move consumption after a
64
+ * business side effect.
65
+ */
66
+ export async function guardMrtrRetry(
67
+ input: GuardMrtrRetryInput,
68
+ ): Promise<MrtrRetryGuardOutcome> {
69
+ const hasInputResponses = input.inputResponses !== undefined;
70
+ const { requestState, key } = input;
71
+
72
+ if (hasInputResponses && requestState === undefined && key !== null) {
73
+ return { kind: "missing_state" };
74
+ }
75
+
76
+ if (requestState === undefined) {
77
+ return { kind: "accepted" };
78
+ }
79
+
80
+ if (key === null) {
81
+ return { kind: "accepted", retryVerified: false };
82
+ }
83
+
84
+ const verdict = await verifyRequestState(requestState, key, input.bindings);
85
+ if (!verdict.ok) {
86
+ return { kind: "invalid_state", reason: verdict.reason };
87
+ }
88
+
89
+ if (input.replayStore === null) {
90
+ return { kind: "replay_store_unavailable", reason: "missing" };
91
+ }
92
+
93
+ let consumed: boolean;
94
+ try {
95
+ const result = await input.replayStore.consume(
96
+ verdict.payload.nonce,
97
+ verdict.payload.exp,
98
+ );
99
+ if (result !== true && result !== false) {
100
+ throw new Error("mrtr.replayStore.consume() must return a boolean");
101
+ }
102
+ consumed = result;
103
+ } catch {
104
+ return { kind: "replay_store_unavailable", reason: "consume_failed" };
105
+ }
106
+
107
+ return consumed
108
+ ? { kind: "accepted", retryVerified: true }
109
+ : { kind: "replayed" };
110
+ }
package/src/mrtr/types.ts CHANGED
@@ -62,7 +62,7 @@ export interface InputRequiredSignal {
62
62
  /**
63
63
  * Configuration for the MRTR subsystem in McpAppOptions.
64
64
  *
65
- * Wire this in to McpAppOptions.mrtr before calling startHttp().
65
+ * Wire this in to McpAppOptions.mrtr before calling start() or startHttp().
66
66
  */
67
67
  export interface MrtrOptions {
68
68
  /**
package/src/types.ts CHANGED
@@ -223,9 +223,10 @@ export interface McpAppOptions {
223
223
  * Multi Round-Trip Requests (spec 2026-07-28, SEP-2322).
224
224
  *
225
225
  * Configures how `requestState` is protected when a tool handler asks the
226
- * client for input mid-call. Only consulted on the stateless transport with a
227
- * negotiated `2026-07-28`: MRTR replaces the server-initiated request pattern
228
- * that earlier revisions still use, so it has no meaning on the legacy path.
226
+ * client for input mid-call. Consulted by stateless HTTP and by the v2 stdio
227
+ * serving entry. On a legacy stdio connection the SDK fulfils the embedded
228
+ * requests through its compatibility shim, then re-enters the same verified
229
+ * handler; application code keeps one MRTR contract across both eras.
229
230
  *
230
231
  * Without `signingKey`, `requestState` travels unprotected and the server logs
231
232
  * a warning at startup. That is only acceptable when tampering with it can
@@ -1,110 +0,0 @@
1
- /**
2
- * A real stdio server, started the way a consumer starts one.
3
- *
4
- * Spawned as a subprocess by `stdio-e2e_test.ts`. Kept as a fixture rather than
5
- * written to a temp file at run time so the thing under test is readable and
6
- * versioned: this is exactly the five lines from the README.
7
- */
8
-
9
- import { McpApp } from "../mcp-app.js";
10
- import { MCP_APP_MIME_TYPE } from "../types.js";
11
-
12
- const RESOURCE_URI = "ui://e2e-stdio/lifecycle";
13
- const BATCH_RESOURCES = ["batch-a", "batch-b"].map((name) => ({
14
- uri: `ui://e2e-stdio/${name}`,
15
- name,
16
- }));
17
-
18
- function registerBatch(): string {
19
- app.registerResources(
20
- BATCH_RESOURCES,
21
- new Map(BATCH_RESOURCES.map((resource) => [
22
- resource.uri,
23
- () => ({
24
- uri: resource.uri,
25
- mimeType: "text/plain",
26
- text: resource.name,
27
- }),
28
- ])),
29
- );
30
- return "registered batch";
31
- }
32
-
33
- const app = new McpApp({
34
- name: "e2e-stdio",
35
- version: "9.9.9",
36
- logger: () => {},
37
- instructions: "fixture server",
38
- });
39
-
40
- app.registerTool(
41
- {
42
- name: "echo",
43
- description: "Echo the input",
44
- inputSchema: {
45
- type: "object",
46
- properties: { value: { type: "string" } },
47
- },
48
- },
49
- (args) => args.value ?? "empty",
50
- );
51
-
52
- app.registerResource(
53
- {
54
- uri: RESOURCE_URI,
55
- name: "Lifecycle resource",
56
- mimeType: MCP_APP_MIME_TYPE,
57
- size: 5,
58
- },
59
- () => ({
60
- uri: RESOURCE_URI,
61
- mimeType: MCP_APP_MIME_TYPE,
62
- text: "hello",
63
- _meta: { fixture: "stdio" },
64
- }),
65
- );
66
-
67
- app.registerTool(
68
- {
69
- name: "unregister_lifecycle_resource",
70
- description: "Remove the fixture resource after startup",
71
- inputSchema: { type: "object" },
72
- },
73
- () => app.unregisterResource(RESOURCE_URI) ? "removed" : "absent",
74
- );
75
-
76
- app.registerTool(
77
- {
78
- name: "register_resource_batch",
79
- description: "Register two resources in one post-start batch",
80
- inputSchema: { type: "object" },
81
- },
82
- registerBatch,
83
- );
84
-
85
- app.registerTool(
86
- {
87
- name: "register_duplicate_resource_batch",
88
- description: "Attempt to register the same batch again",
89
- inputSchema: { type: "object" },
90
- },
91
- registerBatch,
92
- );
93
-
94
- app.registerTool(
95
- {
96
- name: "register_second_lifecycle_resource",
97
- description: "Register one resource after the stdio transport starts",
98
- inputSchema: { type: "object" },
99
- },
100
- () => {
101
- const uri = "ui://e2e-stdio/second";
102
- app.registerResource(
103
- { uri, name: "Second lifecycle resource" },
104
- () => ({ uri, mimeType: "text/plain", text: "second" }),
105
- );
106
- return "registered";
107
- },
108
- );
109
-
110
- await app.start();