@casys/mcp-server 0.25.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/src/mcp-app.ts CHANGED
@@ -4,27 +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
- ListToolsRequestSchema,
24
- McpError,
18
+ type InputRequiredResult,
19
+ type ListResourcesResult,
20
+ type ListToolsResult,
21
+ ProtocolError,
22
+ ProtocolErrorCode,
25
23
  type ReadResourceRequest,
26
- ReadResourceRequestSchema,
27
- } 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";
28
33
  import { Hono } from "hono";
29
34
  import { cors } from "hono/cors";
30
35
  import { RequestQueue } from "./concurrency/request-queue.js";
@@ -67,11 +72,7 @@ import type {
67
72
  StructuredToolResult,
68
73
  ToolHandler,
69
74
  } from "./types.js";
70
- import {
71
- getMcpAppsCapability,
72
- MCP_APP_MIME_TYPE,
73
- MCP_APP_URI_SCHEME,
74
- } from "./types.js";
75
+ import { getMcpAppsCapability, MCP_APP_MIME_TYPE } from "./types.js";
75
76
  import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
76
77
  import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
77
78
  import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
@@ -87,6 +88,7 @@ import {
87
88
  } from "./tasks/mod.js";
88
89
  import {
89
90
  checkInputRequestCapabilities,
91
+ guardMrtrRetry,
90
92
  importStateKey,
91
93
  type InputRequestEntry,
92
94
  type InputRequiredSignal,
@@ -94,7 +96,6 @@ import {
94
96
  type MrtrReplayStore,
95
97
  paramsDigest,
96
98
  sealRequestState,
97
- verifyRequestState,
98
99
  } from "./mrtr/mod.js";
99
100
  import {
100
101
  buildAcknowledgedMessage,
@@ -123,7 +124,11 @@ import {
123
124
  noPrincipalError,
124
125
  taskOwnerKeyFor,
125
126
  } from "./http/request-guards.js";
126
- import { isRecord, jsonRpcResponse } from "./http/wire.js";
127
+ import {
128
+ isRecord,
129
+ jsonRpcResponse,
130
+ MRTR_NO_AUTH_PRINCIPAL,
131
+ } from "./http/wire.js";
127
132
 
128
133
  /**
129
134
  * Tool definition with handler
@@ -426,7 +431,6 @@ export class McpApp {
426
431
  * `initialize` response.
427
432
  */
428
433
  public readonly name: string;
429
- private mcpServer: McpServer;
430
434
  private requestQueue: RequestQueue;
431
435
  private rateLimiter: RateLimiter | null = null;
432
436
  private schemaValidator: SchemaValidator | null = null;
@@ -469,6 +473,12 @@ export class McpApp {
469
473
  */
470
474
  private subscriptions: SubscriptionRegistry | null = null;
471
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
+
472
482
  /**
473
483
  * Imported HMAC key for sealing `requestState`, or `null` when the deployment
474
484
  * configured none.
@@ -585,20 +595,6 @@ export class McpApp {
585
595
  );
586
596
  }
587
597
 
588
- // Create SDK MCP server
589
- this.mcpServer = new McpServer(
590
- {
591
- name: options.name,
592
- version: options.version,
593
- },
594
- {
595
- capabilities: {
596
- tools: {},
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,17 +615,63 @@ 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
  /**
632
- * Pre-install resources/list and resources/read handlers on the low-level
674
+ * Pre-install the resources handlers on the low-level
633
675
  * SDK Server. This declares the `resources` capability BEFORE transport
634
676
  * connection, allowing dynamic resource registration after start().
635
677
  *
@@ -637,36 +679,49 @@ export class McpApp {
637
679
  * by registerResource() calls (e.g., after async MCP discovery).
638
680
  */
639
681
  private installResourceHandlers(): void {
640
- const server = this.mcpServer.server;
682
+ if (this.resourceHandlersInstalled) return;
683
+ if (this.started) {
684
+ throw new Error(
685
+ "[McpApp] Cannot install resource handlers after the server starts. " +
686
+ "Set expectResources: true or register resources before start().",
687
+ );
688
+ }
689
+ this.resourceHandlersInstalled = true;
690
+ }
641
691
 
692
+ /** Install resource handlers on one fresh protocol instance. */
693
+ private installResourceHandlersOn(server: Server): void {
642
694
  // Declare resources capability before transport connects
643
- server.registerCapabilities({ resources: {} });
695
+ server.registerCapabilities({ resources: { listChanged: true } });
644
696
 
645
697
  // resources/list — returns currently registered resources
646
- server.setRequestHandler(ListResourcesRequestSchema, () => {
698
+ server.setRequestHandler("resources/list", () => {
647
699
  return {
648
- resources: Array.from(this.resources.values()).map((r) => ({
649
- uri: r.resource.uri,
650
- name: r.resource.name,
651
- description: r.resource.description,
652
- mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
653
- })),
654
- };
700
+ resources: Array.from(this.resources.values()).map((r) =>
701
+ this.toResourceListing(r.resource)
702
+ ),
703
+ } as unknown as ListResourcesResult;
655
704
  });
656
705
 
657
706
  // resources/read — serve resource content by URI
658
707
  server.setRequestHandler(
659
- ReadResourceRequestSchema,
708
+ "resources/read",
660
709
  async (request: ReadResourceRequest) => {
661
710
  const uri = request.params.uri;
662
711
  const info = this.resources.get(uri);
663
712
  if (!info) {
664
- throw new Error(`Resource not found: ${uri}`);
713
+ throw new ProtocolError(
714
+ ProtocolErrorCode.InvalidParams,
715
+ `Resource not found: ${uri}`,
716
+ );
665
717
  }
666
718
 
667
719
  try {
668
- const content = await info.handler(new URL(uri));
669
- const finalContent = this.applyResourceCsp(content);
720
+ const finalContent = await this.readResourceForProtocol(
721
+ uri,
722
+ info.resource,
723
+ info.handler,
724
+ );
670
725
  return { contents: [finalContent] };
671
726
  } catch (error) {
672
727
  this.log(
@@ -679,30 +734,36 @@ export class McpApp {
679
734
  },
680
735
  );
681
736
 
682
- this.resourceHandlersInstalled = true;
683
- this.log("Resources capability pre-declared (expectResources: true)");
737
+ // We currently expose concrete resources only. An explicit empty template
738
+ // list is nevertheless required once the resources capability exists:
739
+ // clients are entitled to ask which URI templates can be expanded.
740
+ server.setRequestHandler("resources/templates/list", () => ({
741
+ resourceTemplates: [],
742
+ }));
743
+ this.resourceLog("Resources capability installed");
684
744
  }
685
745
 
686
746
  /**
687
747
  * Setup MCP protocol request handlers
688
748
  */
689
- private setupHandlers(): void {
690
- const server = this.mcpServer.server;
691
-
749
+ private setupHandlers(server: Server): void {
692
750
  // Wire up "initialized" notification callback (post-handshake)
693
751
  server.oninitialized = () => {
694
752
  this.initializedCallback?.();
695
753
  };
696
754
 
697
755
  // tools/list handler
698
- server.setRequestHandler(ListToolsRequestSchema, () => {
699
- return { tools: this.buildToolListing() };
756
+ server.setRequestHandler("tools/list", () => {
757
+ return { tools: this.buildToolListing() } as unknown as ListToolsResult;
700
758
  });
701
759
 
702
760
  // tools/call handler (delegates to middleware pipeline)
703
761
  server.setRequestHandler(
704
- CallToolRequestSchema,
705
- async (request: CallToolRequest) => {
762
+ "tools/call",
763
+ async (
764
+ request: CallToolRequest,
765
+ ctx: ServerContext,
766
+ ): Promise<CallToolResult | InputRequiredResult> => {
706
767
  const toolName = request.params.name;
707
768
  const args = request.params.arguments || {};
708
769
 
@@ -711,15 +772,70 @@ export class McpApp {
711
772
  // hardest to correlate back to the host that caused it; `logLevel` is
712
773
  // read for the same reason it is on HTTP — the spec makes it
713
774
  // per-request, and a handler must stay silent without it.
714
- const meta = request.params._meta;
715
- const clientMeta: StatelessClientMeta | undefined = isRecord(meta)
716
- ? {
717
- ...readTraceContext(meta),
718
- ...(readLogLevel(meta) !== undefined
719
- ? { logLevel: readLogLevel(meta) }
720
- : {}),
721
- }
775
+ const meta = isRecord(request.params._meta)
776
+ ? request.params._meta
777
+ : undefined;
778
+ const envelope = isRecord(ctx.mcpReq.envelope)
779
+ ? ctx.mcpReq.envelope
780
+ : undefined;
781
+ const clientInfo = envelope?.[STATELESS_CLIENT_INFO_KEY] as
782
+ | Implementation
783
+ | undefined ?? server.getClientVersion();
784
+ const clientCapabilities = envelope?.[
785
+ STATELESS_CLIENT_CAPABILITIES_KEY
786
+ ] as ClientCapabilities | undefined ??
787
+ server.getClientCapabilities();
788
+ const requestedLogLevel = envelope !== undefined
789
+ ? readLogLevel(envelope)
722
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
+ );
723
839
 
724
840
  let result: unknown;
725
841
  try {
@@ -730,60 +846,52 @@ export class McpApp {
730
846
  undefined,
731
847
  undefined,
732
848
  clientMeta,
849
+ mrtr,
733
850
  );
734
851
  } catch (error) {
735
- 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;
736
876
  }
737
877
 
738
878
  // Serialization errors are framework bugs, not tool errors —
739
879
  // let them propagate
740
- return this.buildToolCallResult(toolName, result);
880
+ return this.buildToolCallResult(
881
+ toolName,
882
+ result,
883
+ ) as unknown as CallToolResult;
741
884
  },
742
885
  );
743
-
744
- // `server/discover` over stdio (spec 2026-07-28, SEP-2575).
745
- //
746
- // The spec makes this RPC a MUST for every server and names stdio as a
747
- // primary use: a client probes it for backward compatibility. That matters
748
- // here precisely because the SDK's stdio handshake still negotiates
749
- // 2025-11-25 — `server/discover` is then the only way for a peer to learn
750
- // this server also speaks 2026-07-28 over HTTP.
751
- //
752
- // Routed through `fallbackRequestHandler` rather than `setRequestHandler`
753
- // because the latter takes a Zod schema, and the method is absent from the
754
- // SDK's type surface. Adding a Zod dependency to declare one schema would
755
- // put a peer dependency in the public API for a single string comparison.
756
- // Every other unknown method keeps its previous answer: MethodNotFound.
757
- server.fallbackRequestHandler = (request: JSONRPCRequest) => {
758
- if (request.method !== "server/discover") {
759
- // Same text the SDK used for an unrouted method. It still reaches the
760
- // wire as "MCP error -32601: Method not found" — `McpError` prefixes
761
- // its own message and a handler cannot raise the code without it. The
762
- // code is unchanged, which is what a peer switches on; the string
763
- // difference is pinned by a test and noted in the changelog. Appending
764
- // the method name on top of that would have been a second, gratuitous
765
- // change to the same field.
766
- throw new McpError(ErrorCode.MethodNotFound, "Method not found");
767
- }
768
- return Promise.resolve(this.buildDiscoverResult());
769
- };
770
886
  }
771
887
 
772
888
  /**
773
- * The `server/discover` result (spec 2026-07-28, SEP-2575).
774
- *
775
- * Single source of truth for both transports. They used to be one inline
776
- * object on the HTTP path; a stdio copy would have been the second place to
777
- * forget `instructions` or a new capability.
889
+ * The stateless HTTP `server/discover` result (spec 2026-07-28, SEP-2575).
778
890
  *
779
- * Always stamped as 2026-07-28 regardless of what the transport negotiated.
780
- * That is deliberate but not free: nothing gates the method, so a peer that
781
- * negotiated `2025-11-25` over stdio can call it and receive an envelope it
782
- * never agreed to. The alternative is worse — stamping the negotiated version
783
- * would make the probe answer "2025" to the client asking whether this server
784
- * speaks 2026, which is the one question it exists to answer. Treat
785
- * `server/discover` as a cross-version exception: its result describes what
786
- * 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.
787
895
  */
788
896
  private buildDiscoverResult(): Record<string, unknown> {
789
897
  return this.stampResult(
@@ -1174,36 +1282,264 @@ export class McpApp {
1174
1282
  // Resource Registration (MCP Apps SEP-1865)
1175
1283
  // ============================================
1176
1284
 
1177
- /**
1178
- * Validate resource URI scheme
1179
- * Logs warning if not using ui:// scheme (MCP Apps standard)
1180
- */
1181
1285
  /**
1182
1286
  * Apply CSP meta tag injection to HTML resource content (if configured).
1183
- * Only transforms HTML content (checks mimeType); non-HTML passes through.
1287
+ * Only transforms text HTML content; blob responses pass through unchanged.
1184
1288
  */
1185
- private applyResourceCsp(
1186
- content: import("./types.js").ResourceContent,
1187
- ): import("./types.js").ResourceContent {
1289
+ private applyResourceCsp(content: ResourceContent): ResourceContent {
1188
1290
  if (!this.options.resourceCsp) return content;
1189
- if (!content.mimeType?.includes("text/html")) return content;
1291
+ const mediaType = content.mimeType.split(";", 1)[0].trim().toLowerCase();
1292
+ if (
1293
+ !this.isTextResourceContent(content) ||
1294
+ mediaType !== "text/html"
1295
+ ) {
1296
+ return content;
1297
+ }
1190
1298
 
1191
1299
  const cspValue = buildCspHeader(this.options.resourceCsp);
1192
1300
  return {
1193
1301
  ...content,
1194
- text: injectCspMetaTag(content.text ?? "", cspValue),
1302
+ text: injectCspMetaTag(content.text, cspValue),
1195
1303
  };
1196
1304
  }
1197
1305
 
1306
+ private isTextResourceContent(
1307
+ content: ResourceContent,
1308
+ ): content is Extract<ResourceContent, { text: string }> {
1309
+ return "text" in content;
1310
+ }
1311
+
1312
+ /** Standard padded base64 with zero pad bits, without whitespace or URL-safe substitutions. */
1313
+ private isCanonicalBase64(blob: string): boolean {
1314
+ try {
1315
+ // `atob` accepts several equivalent spellings. Re-encoding is what
1316
+ // rejects omitted padding, whitespace, URL-safe alphabets, and non-zero
1317
+ // pad bits such as `/x==` (whose canonical form is `/w==`). Both APIs are
1318
+ // Web-standard globals available in Deno and supported Node runtimes.
1319
+ return btoa(atob(blob)) === blob;
1320
+ } catch {
1321
+ return false;
1322
+ }
1323
+ }
1324
+
1325
+ /**
1326
+ * Validate an untrusted handler result at the API boundary.
1327
+ *
1328
+ * TypeScript callers get the discriminated `ResourceContent` union at compile
1329
+ * time. This check closes the equivalent JavaScript, `any`, and unchecked
1330
+ * TypeScript paths before a malformed result reaches an MCP client.
1331
+ */
1332
+ private validateResourceContent(
1333
+ requestedUri: string,
1334
+ candidate: unknown,
1335
+ resource: MCPResource,
1336
+ ): ResourceContent {
1337
+ if (!isRecord(candidate)) {
1338
+ throw new Error("[McpApp] Resource handler must return an object");
1339
+ }
1340
+
1341
+ const hasText = Object.prototype.hasOwnProperty.call(candidate, "text");
1342
+ const hasBlob = Object.prototype.hasOwnProperty.call(candidate, "blob");
1343
+ if (hasText === hasBlob) {
1344
+ throw new Error(
1345
+ "[McpApp] Resource content must contain exactly one of text or blob",
1346
+ );
1347
+ }
1348
+ if (candidate.uri !== requestedUri) {
1349
+ throw new Error(
1350
+ `[McpApp] Resource content URI must match requested URI: ${requestedUri}`,
1351
+ );
1352
+ }
1353
+ if (Object.prototype.hasOwnProperty.call(candidate, "annotations")) {
1354
+ throw new Error(
1355
+ "[McpApp] Resource content annotations are not a ResourceContents field; put annotations on MCPResource metadata",
1356
+ );
1357
+ }
1358
+ if (candidate._meta !== undefined && !isRecord(candidate._meta)) {
1359
+ throw new Error(
1360
+ "[McpApp] Resource content _meta must be an object when supplied",
1361
+ );
1362
+ }
1363
+ if (
1364
+ typeof candidate.mimeType !== "string" ||
1365
+ candidate.mimeType.trim().length === 0
1366
+ ) {
1367
+ throw new Error(
1368
+ "[McpApp] Resource content mimeType must be a non-empty string",
1369
+ );
1370
+ }
1371
+ if (hasText && typeof candidate.text !== "string") {
1372
+ throw new Error("[McpApp] Resource content text must be a string");
1373
+ }
1374
+ if (hasBlob) {
1375
+ if (typeof candidate.blob !== "string") {
1376
+ throw new Error("[McpApp] Resource content blob must be a string");
1377
+ }
1378
+ if (!this.isCanonicalBase64(candidate.blob)) {
1379
+ throw new Error(
1380
+ "[McpApp] Resource content blob must be canonical standard base64",
1381
+ );
1382
+ }
1383
+ }
1384
+
1385
+ if (
1386
+ resource.mimeType !== undefined &&
1387
+ candidate.mimeType !== resource.mimeType
1388
+ ) {
1389
+ throw new Error(
1390
+ `[McpApp] Resource content mimeType must match registered metadata: ${resource.mimeType}`,
1391
+ );
1392
+ }
1393
+ if (resource.size !== undefined) {
1394
+ const actualSize = hasText
1395
+ ? new TextEncoder().encode(candidate.text as string).byteLength
1396
+ : atob(candidate.blob as string).length;
1397
+ if (actualSize !== resource.size) {
1398
+ throw new Error(
1399
+ `[McpApp] Resource content size must match registered metadata: expected ${resource.size}, got ${actualSize}`,
1400
+ );
1401
+ }
1402
+ }
1403
+
1404
+ // Do not forward arbitrary JavaScript fields to the wire. In particular,
1405
+ // annotations belong to Resource, not ResourceContents in the MCP schema.
1406
+ return hasText
1407
+ ? {
1408
+ uri: requestedUri,
1409
+ mimeType: candidate.mimeType,
1410
+ text: candidate.text as string,
1411
+ ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1412
+ }
1413
+ : {
1414
+ uri: requestedUri,
1415
+ mimeType: candidate.mimeType,
1416
+ blob: candidate.blob as string,
1417
+ ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1418
+ };
1419
+ }
1420
+
1421
+ /** Run, validate, and CSP-harden a handler for a protocol response. */
1422
+ private async readResourceForProtocol(
1423
+ requestedUri: string,
1424
+ resource: MCPResource,
1425
+ handler: ResourceHandler,
1426
+ ): Promise<ResourceContent> {
1427
+ const content = this.validateResourceContent(
1428
+ requestedUri,
1429
+ await handler(new URL(requestedUri)),
1430
+ resource,
1431
+ );
1432
+ // Size attests the bytes delivered to the client. CSP injection changes a
1433
+ // text body, so validate the served representation too rather than only
1434
+ // the handler's pre-injection value.
1435
+ return this.validateResourceContent(
1436
+ requestedUri,
1437
+ this.applyResourceCsp(content),
1438
+ resource,
1439
+ );
1440
+ }
1441
+
1442
+ /** Convert public metadata into the exact wire listing shape. */
1443
+ private toResourceListing(resource: MCPResource): Record<string, unknown> {
1444
+ return {
1445
+ uri: resource.uri,
1446
+ name: resource.name,
1447
+ ...(resource.title !== undefined ? { title: resource.title } : {}),
1448
+ ...(resource.description !== undefined
1449
+ ? { description: resource.description }
1450
+ : {}),
1451
+ ...(resource.mimeType !== undefined
1452
+ ? { mimeType: resource.mimeType }
1453
+ : {}),
1454
+ ...(resource.size !== undefined ? { size: resource.size } : {}),
1455
+ ...(resource.icons !== undefined ? { icons: resource.icons } : {}),
1456
+ ...(resource.annotations !== undefined
1457
+ ? { annotations: resource.annotations }
1458
+ : {}),
1459
+ ...(resource._meta !== undefined ? { _meta: resource._meta } : {}),
1460
+ };
1461
+ }
1462
+
1463
+ /** Fail early rather than publishing a metadata value clients must ignore. */
1464
+ private validateResourceMetadata(resource: MCPResource): void {
1465
+ this.validateResourceUri(resource.uri);
1466
+ if (typeof resource.name !== "string" || resource.name.length === 0) {
1467
+ throw new Error("[McpApp] Resource name must be a non-empty string");
1468
+ }
1469
+ if (
1470
+ resource.mimeType !== undefined &&
1471
+ (typeof resource.mimeType !== "string" ||
1472
+ resource.mimeType.trim().length === 0)
1473
+ ) {
1474
+ throw new Error(
1475
+ "[McpApp] Resource mimeType must be a non-empty string when supplied",
1476
+ );
1477
+ }
1478
+ if (
1479
+ resource.size !== undefined &&
1480
+ (!Number.isSafeInteger(resource.size) || resource.size < 0)
1481
+ ) {
1482
+ throw new Error(
1483
+ `[McpApp] Resource size must be a non-negative safe integer (got ${resource.size})`,
1484
+ );
1485
+ }
1486
+ }
1487
+
1488
+ /**
1489
+ * Resources are keyed by their wire URI, so accepting a spelling which URL
1490
+ * canonicalisation changes would make list/read/handler identity ambiguous.
1491
+ * Refuse it at registration instead of silently normalising a caller-owned
1492
+ * identifier. Non-`ui:` schemes are valid MCP resources and remain allowed.
1493
+ */
1198
1494
  private validateResourceUri(uri: string): void {
1199
- if (!uri.startsWith(MCP_APP_URI_SCHEME)) {
1200
- this.log(
1201
- `[WARN] Resource URI "${uri}" does not use ${MCP_APP_URI_SCHEME} scheme. ` +
1202
- `MCP Apps standard requires ui:// URIs.`,
1495
+ if (typeof uri !== "string" || uri.length === 0) {
1496
+ throw new Error("[McpApp] Resource URI must be a non-empty string");
1497
+ }
1498
+ let canonical: string;
1499
+ try {
1500
+ canonical = new URL(uri).toString();
1501
+ } catch {
1502
+ throw new Error(`[McpApp] Resource URI must be an absolute URI: ${uri}`);
1503
+ }
1504
+ if (canonical !== uri) {
1505
+ throw new Error(
1506
+ `[McpApp] Resource URI must be canonical: received ${uri}, canonical form is ${canonical}`,
1203
1507
  );
1204
1508
  }
1205
1509
  }
1206
1510
 
1511
+ /** A consumer logger is observability, never a resource-commit dependency. */
1512
+ private resourceLog(message: string): void {
1513
+ try {
1514
+ this.log(message);
1515
+ } catch {
1516
+ // Deliberately ignored: a throwing logger must not contradict a committed
1517
+ // resource mutation or make a retry appear necessary.
1518
+ }
1519
+ }
1520
+
1521
+ /**
1522
+ * Publish the one post-commit list-changed projection for a mutation.
1523
+ * It is best-effort by design: registry state is authoritative and callers
1524
+ * must not receive a false failure after it changes.
1525
+ */
1526
+ private notifyResourceListChanged(): void {
1527
+ if (!this.started) return;
1528
+ if (this.subscriptions !== null) {
1529
+ this.sendNotification("notifications/resources/list_changed");
1530
+ return;
1531
+ }
1532
+ const server = this.activeStdioServer;
1533
+ if (server === null) return;
1534
+ void server.sendResourceListChanged().catch((error) => {
1535
+ this.resourceLog(
1536
+ `[WARN] Resource list changed notification was not delivered: ${
1537
+ error instanceof Error ? error.message : String(error)
1538
+ }`,
1539
+ );
1540
+ });
1541
+ }
1542
+
1207
1543
  /**
1208
1544
  * Register a single resource
1209
1545
  *
@@ -1224,8 +1560,11 @@ export class McpApp {
1224
1560
  * ```
1225
1561
  */
1226
1562
  registerResource(resource: MCPResource, handler: ResourceHandler): void {
1227
- // Validate URI scheme
1228
- this.validateResourceUri(resource.uri);
1563
+ this.validateResourceMetadata(resource);
1564
+
1565
+ if (typeof handler !== "function") {
1566
+ throw new Error("[McpApp] Resource handler must be a function");
1567
+ }
1229
1568
 
1230
1569
  // Check for duplicate
1231
1570
  if (this.resources.has(resource.uri)) {
@@ -1234,41 +1573,40 @@ export class McpApp {
1234
1573
  );
1235
1574
  }
1236
1575
 
1237
- if (this.resourceHandlersInstalled) {
1238
- // expectResources mode: handlers are already installed on the low-level
1239
- // server. Just add to our internal registry — the handlers read from
1240
- // this.resources dynamically.
1241
- this.resources.set(resource.uri, { resource, handler });
1242
- } else {
1243
- // Standard mode: register via SDK (must be called before start())
1244
- this.mcpServer.registerResource(
1245
- resource.name,
1246
- resource.uri,
1247
- {
1248
- description: resource.description,
1249
- mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,
1250
- },
1251
- async (uri: URL) => {
1252
- try {
1253
- const content = await handler(uri);
1254
- const finalContent = this.applyResourceCsp(content);
1255
- return { contents: [finalContent] };
1256
- } catch (error) {
1257
- this.log(
1258
- `[ERROR] Resource handler failed for ${uri}: ${
1259
- error instanceof Error ? error.message : String(error)
1260
- }`,
1261
- );
1262
- throw error;
1263
- }
1264
- },
1265
- );
1266
-
1267
- // Track in our registry
1268
- this.resources.set(resource.uri, { resource, handler });
1576
+ // Static registrations lazily install the single low-level handler set.
1577
+ // Once a transport starts, handler installation would be too late, so a
1578
+ // deployment that needs late discovery must opt in with expectResources.
1579
+ if (!this.resourceHandlersInstalled) {
1580
+ if (this.started) {
1581
+ throw new Error(
1582
+ "[McpApp] Cannot register a resource after start without expectResources: true.",
1583
+ );
1584
+ }
1585
+ this.installResourceHandlers();
1269
1586
  }
1270
1587
 
1271
- this.log(`Registered resource: ${resource.name} (${resource.uri})`);
1588
+ // The Map is the only registry. It commits atomically and has no secondary
1589
+ // SDK entry which could survive a failed rollback as a ghost resource.
1590
+ this.resources.set(resource.uri, { resource, handler });
1591
+ this.resourceLog(`Registered resource: ${resource.name} (${resource.uri})`);
1592
+ this.notifyResourceListChanged();
1593
+ }
1594
+
1595
+ /**
1596
+ * Remove a resource from this server.
1597
+ *
1598
+ * It is safe before or after either transport starts once resources are
1599
+ * installed. Returns `false` when no such URI is present, so callers can make
1600
+ * idempotent cleanup calls without catching an error.
1601
+ */
1602
+ unregisterResource(uri: string): boolean {
1603
+ const info = this.resources.get(uri);
1604
+ if (!info) return false;
1605
+
1606
+ this.resources.delete(uri);
1607
+ this.resourceLog(`Unregistered resource: ${uri}`);
1608
+ this.notifyResourceListChanged();
1609
+ return true;
1272
1610
  }
1273
1611
 
1274
1612
  /**
@@ -1282,6 +1620,8 @@ export class McpApp {
1282
1620
  resources: MCPResource[],
1283
1621
  handlers: Map<string, ResourceHandler>,
1284
1622
  ): void {
1623
+ // No mutation means no capability installation and no notification.
1624
+ if (resources.length === 0) return;
1285
1625
  // Validate all handlers exist BEFORE registering any (fail-fast)
1286
1626
  const missingHandlers: string[] = [];
1287
1627
  for (const resource of resources) {
@@ -1312,19 +1652,50 @@ export class McpApp {
1312
1652
  );
1313
1653
  }
1314
1654
 
1315
- // All validations passed, register resources
1655
+ // A duplicate inside this batch would otherwise fail only when the second
1656
+ // registration is attempted, after the first has been made visible.
1657
+ const seenUris = new Set<string>();
1658
+ const repeatedUris = resources
1659
+ .map((resource) => resource.uri)
1660
+ .filter((uri) => {
1661
+ if (seenUris.has(uri)) return true;
1662
+ seenUris.add(uri);
1663
+ return false;
1664
+ });
1665
+ if (repeatedUris.length > 0) {
1666
+ throw new Error(
1667
+ `[McpApp] Resources are repeated in this batch:\n` +
1668
+ repeatedUris.map((uri) => ` - ${uri}`).join("\n"),
1669
+ );
1670
+ }
1671
+
1316
1672
  for (const resource of resources) {
1317
- const handler = handlers.get(resource.uri);
1318
- if (!handler) {
1319
- // Should never happen after validation, but defensive check
1673
+ this.validateResourceMetadata(resource);
1674
+ if (typeof handlers.get(resource.uri) !== "function") {
1320
1675
  throw new Error(
1321
- `[McpApp] Handler disappeared for ${resource.uri}`,
1676
+ `[McpApp] Resource handler must be a function: ${resource.uri}`,
1322
1677
  );
1323
1678
  }
1324
- this.registerResource(resource, handler);
1325
1679
  }
1326
-
1327
- this.log(`Registered ${resources.length} resources`);
1680
+ if (!this.resourceHandlersInstalled) {
1681
+ if (this.started) {
1682
+ throw new Error(
1683
+ "[McpApp] Cannot register resources after start without expectResources: true.",
1684
+ );
1685
+ }
1686
+ this.installResourceHandlers();
1687
+ }
1688
+ // All validation and the one possible handler-install side effect happened
1689
+ // before this point. A Map update cannot partially fail, so the batch gets
1690
+ // one commit and one notification (or neither on validation failure).
1691
+ for (const resource of resources) {
1692
+ this.resources.set(resource.uri, {
1693
+ resource,
1694
+ handler: handlers.get(resource.uri)!,
1695
+ });
1696
+ }
1697
+ this.resourceLog(`Registered ${resources.length} resources`);
1698
+ if (resources.length > 0) this.notifyResourceListChanged();
1328
1699
  }
1329
1700
 
1330
1701
  /**
@@ -1388,13 +1759,13 @@ export class McpApp {
1388
1759
  },
1389
1760
  async () => {
1390
1761
  const html = await Promise.resolve(readFile(currentDistPath));
1391
- const content: import("./types.js").ResourceContent = {
1762
+ const content: ResourceContent = {
1392
1763
  uri: resourceUri,
1393
1764
  mimeType: MCP_APP_MIME_TYPE,
1394
1765
  text: html,
1395
1766
  };
1396
1767
  if (config.csp) {
1397
- (content as unknown as Record<string, unknown>)._meta = {
1768
+ content._meta = {
1398
1769
  ui: { csp: config.csp },
1399
1770
  };
1400
1771
  }
@@ -1417,6 +1788,9 @@ export class McpApp {
1417
1788
  /**
1418
1789
  * Start the MCP server with stdio transport
1419
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
1420
1794
  async start(): Promise<void> {
1421
1795
  // Guard FIRST. Resetting before the guard meant a concurrent start() during
1422
1796
  // stop() cleared `stopping` and rebuilt the store on its way to failing with
@@ -1434,8 +1808,20 @@ export class McpApp {
1434
1808
  // Build middleware pipeline before connecting transport
1435
1809
  this.buildPipeline();
1436
1810
 
1437
- const transport = new StdioServerTransport();
1438
- 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
+ });
1439
1825
 
1440
1826
  this.started = true;
1441
1827
 
@@ -1511,7 +1897,12 @@ export class McpApp {
1511
1897
  this.httpServer = null;
1512
1898
  }
1513
1899
 
1514
- 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;
1515
1906
  this.started = false;
1516
1907
 
1517
1908
  this.log("Server stopped");
@@ -2179,8 +2570,6 @@ export class McpApp {
2179
2570
  ? params["requestState"]
2180
2571
  : undefined;
2181
2572
 
2182
- let retryVerified: boolean | undefined;
2183
-
2184
2573
  // A retry carrying answers but no token cannot be verified, and the
2185
2574
  // server always issues a token when it has a key. So this combination
2186
2575
  // is either a confused client or an attempt to inject answers past the
@@ -2198,10 +2587,31 @@ export class McpApp {
2198
2587
  )
2199
2588
  : { key: null as CryptoKey | null };
2200
2589
  if ("error" in guardKey) return guardKey.error;
2201
- if (
2202
- echoedResponses !== undefined && echoedState === undefined &&
2203
- guardKey.key !== null
2204
- ) {
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") {
2205
2615
  return jsonRpcResponse(
2206
2616
  {
2207
2617
  jsonrpc: "2.0",
@@ -2218,129 +2628,65 @@ export class McpApp {
2218
2628
  },
2219
2629
  },
2220
2630
  400,
2631
+ { "MCP-Protocol-Version": statelessVersion },
2632
+ );
2633
+ }
2634
+ if (retryOutcome.kind === "invalid_state") {
2635
+ return jsonRpcResponse(
2221
2636
  {
2222
- "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
+ },
2223
2644
  },
2645
+ 400,
2646
+ { "MCP-Protocol-Version": statelessVersion },
2224
2647
  );
2225
2648
  }
2226
-
2227
- if (echoedState !== undefined) {
2228
- const key = guardKey.key;
2229
- if (key === null) {
2230
- // Unprotected mode: nothing to verify, and the handler is told so
2231
- // rather than being handed a false assurance.
2232
- retryVerified = false;
2233
- } else {
2234
- // On an authenticated server this binds the token to one user, so
2235
- // a token minted for A cannot be spent by B. On an UNAUTHENTICATED
2236
- // server every caller is "anonymous", and the binding protects
2237
- // nothing — correctly so: without auth there is no user boundary to
2238
- // cross, and any caller could invoke the tool directly anyway. The
2239
- // method and argument bindings still apply in both cases.
2240
- const principal = callerPrincipal(httpAuthInfo);
2241
- if (principal === null) {
2242
- return noPrincipalError(
2243
- id,
2244
- statelessVersion,
2245
- );
2246
- }
2247
- const verdict = await verifyRequestState(echoedState, key, {
2248
- principal,
2249
- method: "tools/call",
2250
- paramsDigest: ingressDigest,
2251
- });
2252
- if (!verdict.ok) {
2253
- // Attacker-controlled input that failed its integrity or binding
2254
- // checks. Rejected before the handler runs, and the reason is
2255
- // returned so a legitimate client can recover (e.g. re-elicit
2256
- // after an expiry) rather than guessing.
2257
- return jsonRpcResponse(
2258
- {
2259
- jsonrpc: "2.0",
2260
- id,
2261
- error: {
2262
- code: JSONRPC_INVALID_PARAMS,
2263
- message: `Invalid requestState: ${verdict.reason}`,
2264
- data: { reason: verdict.reason },
2265
- },
2266
- },
2267
- 400,
2268
- );
2269
- }
2270
-
2271
- const replayStore = this.mrtrReplayStore;
2272
- if (replayStore === null) {
2273
- return jsonRpcResponse(
2274
- {
2275
- jsonrpc: "2.0",
2276
- id,
2277
- error: {
2278
- code: ErrorCode.InternalError,
2279
- message: "MRTR replay protection is unavailable",
2280
- data: {
2281
- problem: "mrtr_replay_store_unavailable",
2282
- recovery:
2283
- "Configure mrtr.signingKey with a working replay store and retry the full interaction.",
2284
- },
2285
- },
2286
- },
2287
- 500,
2288
- { "MCP-Protocol-Version": statelessVersion },
2289
- );
2290
- }
2291
-
2292
- let consumed: boolean;
2293
- try {
2294
- const storeResult = await replayStore.consume(
2295
- verdict.payload.nonce,
2296
- verdict.payload.exp,
2297
- );
2298
- if (storeResult !== true && storeResult !== false) {
2299
- throw new Error(
2300
- "mrtr.replayStore.consume() must return a boolean",
2301
- );
2302
- }
2303
- consumed = storeResult;
2304
- } catch {
2305
- this.log(
2306
- "[WARN] MRTR replay store unavailable; retry rejected before handler",
2307
- );
2308
- return jsonRpcResponse(
2309
- {
2310
- jsonrpc: "2.0",
2311
- id,
2312
- error: {
2313
- code: ErrorCode.InternalError,
2314
- message: "MRTR replay protection is unavailable",
2315
- data: {
2316
- problem: "mrtr_replay_store_unavailable",
2317
- recovery:
2318
- "Restore the shared replay store, then restart the interaction to obtain a fresh requestState.",
2319
- },
2320
- },
2321
- },
2322
- 500,
2323
- { "MCP-Protocol-Version": statelessVersion },
2324
- );
2325
- }
2326
- if (!consumed) {
2327
- return jsonRpcResponse(
2328
- {
2329
- jsonrpc: "2.0",
2330
- id,
2331
- error: {
2332
- code: JSONRPC_INVALID_PARAMS,
2333
- message: "Invalid requestState: replayed",
2334
- data: { reason: "replayed" },
2335
- },
2336
- },
2337
- 400,
2338
- { "MCP-Protocol-Version": statelessVersion },
2339
- );
2340
- }
2341
- 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
+ );
2342
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
+ );
2343
2688
  }
2689
+ const retryVerified = retryOutcome.retryVerified;
2344
2690
 
2345
2691
  try {
2346
2692
  const result = await this.executeToolCall(
@@ -2613,18 +2959,28 @@ export class McpApp {
2613
2959
  id,
2614
2960
  result: this.stampResult(
2615
2961
  this.withCacheHints({
2616
- resources: Array.from(this.resources.values()).map((r) => ({
2617
- uri: r.resource.uri,
2618
- name: r.resource.name,
2619
- description: r.resource.description,
2620
- mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
2621
- })),
2962
+ resources: Array.from(this.resources.values()).map((r) =>
2963
+ this.toResourceListing(r.resource)
2964
+ ),
2622
2965
  }, statelessVersion),
2623
2966
  statelessVersion,
2624
2967
  ),
2625
2968
  });
2626
2969
  }
2627
2970
 
2971
+ // Concrete resources only for now. Keep this endpoint explicit rather
2972
+ // than falling through to MethodNotFound once resources are advertised.
2973
+ if (method === "resources/templates/list") {
2974
+ return c.json({
2975
+ jsonrpc: "2.0",
2976
+ id,
2977
+ result: this.stampResult(
2978
+ this.withCacheHints({ resourceTemplates: [] }, statelessVersion),
2979
+ statelessVersion,
2980
+ ),
2981
+ });
2982
+ }
2983
+
2628
2984
  // Resources read
2629
2985
  if (method === "resources/read") {
2630
2986
  // Dispatch by method, not the truthiness of its routing parameter.
@@ -2660,8 +3016,11 @@ export class McpApp {
2660
3016
  }
2661
3017
 
2662
3018
  try {
2663
- const content = await resourceInfo.handler(new URL(uri));
2664
- const finalContent = this.applyResourceCsp(content);
3019
+ const finalContent = await this.readResourceForProtocol(
3020
+ uri,
3021
+ resourceInfo.resource,
3022
+ resourceInfo.handler,
3023
+ );
2665
3024
  return c.json({
2666
3025
  jsonrpc: "2.0",
2667
3026
  id,
@@ -3277,7 +3636,9 @@ export class McpApp {
3277
3636
  * @see {@link MCP_APPS_EXTENSION_ID} for the extension key
3278
3637
  */
3279
3638
  getClientMcpAppsCapability(): McpAppsClientCapability | undefined {
3280
- return getMcpAppsCapability(this.mcpServer.server.getClientCapabilities());
3639
+ return getMcpAppsCapability(
3640
+ this.activeStdioServer?.getClientCapabilities(),
3641
+ );
3281
3642
  }
3282
3643
 
3283
3644
  /**
@@ -3389,7 +3750,11 @@ export class McpApp {
3389
3750
  async readResourceContent(uri: string): Promise<ResourceContent | null> {
3390
3751
  const entry = this.resources.get(uri);
3391
3752
  if (!entry) return null;
3392
- return await entry.handler(new URL(uri));
3753
+ return this.validateResourceContent(
3754
+ uri,
3755
+ await entry.handler(new URL(uri)),
3756
+ entry.resource,
3757
+ );
3393
3758
  }
3394
3759
 
3395
3760
  /**
@@ -3448,12 +3813,14 @@ export class McpApp {
3448
3813
  }
3449
3814
  }
3450
3815
 
3451
- // For stdio mode, send via SDK transport
3452
- try {
3453
- this.mcpServer.server.notification({ method, params });
3454
- } catch {
3455
- // Transport may not support notifications yet (pre-initialized)
3456
- }
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
+ });
3457
3824
  }
3458
3825
 
3459
3826
  /**
@@ -3491,8 +3858,9 @@ export class McpApp {
3491
3858
  * Apply the spec-2026-07-28 result envelope when — and only when — the peer
3492
3859
  * negotiated that revision.
3493
3860
  *
3494
- * Always applies on the stateless transport, which only accepts 2026-07-28.
3495
- * 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.
3496
3864
  *
3497
3865
  * Omitting the envelope for a genuinely legacy peer is safe in the other
3498
3866
  * direction too: the spec instructs clients to read a missing `resultType` as
@@ -3520,6 +3888,104 @@ export class McpApp {
3520
3888
  };
3521
3889
  }
3522
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
+
3523
3989
  /**
3524
3990
  * Resolve the MRTR signing key once, warning if a deployment has none.
3525
3991
  *
@@ -3918,7 +4384,12 @@ export class McpApp {
3918
4384
  // created from it, so advertising and behaviour cannot drift apart.
3919
4385
  return {
3920
4386
  tools: {},
3921
- resources: this.resources.size > 0 ? {} : undefined,
4387
+ // Capability lifetime is defined by installed handlers, not the current
4388
+ // Map size. A dynamic registry may correctly be empty at initialize and
4389
+ // gain resources later; `listChanged` tells clients to refresh then.
4390
+ resources: this.resourceHandlersInstalled
4391
+ ? { listChanged: true }
4392
+ : undefined,
3922
4393
  ...(extensions && Object.keys(extensions).length > 0
3923
4394
  ? { extensions }
3924
4395
  : {}),