@casys/mcp-server 0.24.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp-app.ts CHANGED
@@ -18,8 +18,11 @@ import {
18
18
  type ClientCapabilities,
19
19
  ErrorCode,
20
20
  type Implementation,
21
+ type JSONRPCRequest,
21
22
  ListResourcesRequestSchema,
23
+ ListResourceTemplatesRequestSchema,
22
24
  ListToolsRequestSchema,
25
+ McpError,
23
26
  type ReadResourceRequest,
24
27
  ReadResourceRequestSchema,
25
28
  } from "@modelcontextprotocol/sdk/types.js";
@@ -65,11 +68,7 @@ import type {
65
68
  StructuredToolResult,
66
69
  ToolHandler,
67
70
  } from "./types.js";
68
- import {
69
- getMcpAppsCapability,
70
- MCP_APP_MIME_TYPE,
71
- MCP_APP_URI_SCHEME,
72
- } from "./types.js";
71
+ import { getMcpAppsCapability, MCP_APP_MIME_TYPE } from "./types.js";
73
72
  import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
74
73
  import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
75
74
  import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
@@ -102,7 +101,12 @@ import {
102
101
  type SubscriptionSink,
103
102
  } from "./subscriptions/subscription-registry.js";
104
103
  import { ServerMetrics } from "./observability/metrics.js";
105
- import { endToolCallSpan, startToolCallSpan } from "./observability/otel.js";
104
+ import type { SpanContext } from "@opentelemetry/api";
105
+ import {
106
+ endToolCallSpan,
107
+ parseTraceParent,
108
+ startToolCallSpan,
109
+ } from "./observability/otel.js";
106
110
  import {
107
111
  BodyTooLargeError,
108
112
  DEFAULT_MAX_BODY_BYTES,
@@ -160,6 +164,16 @@ const STATELESS_SERVER_INFO_KEY = "io.modelcontextprotocol/serverInfo";
160
164
  */
161
165
  const STATELESS_LOG_LEVEL_KEY = "io.modelcontextprotocol/logLevel";
162
166
 
167
+ /**
168
+ * W3C trace context keys in `params._meta` (spec 2026-07-28, SEP-414).
169
+ *
170
+ * Unlike every other per-request field these are NOT namespaced — the revision
171
+ * documents the bare W3C names, so that a `_meta` envelope carries the same
172
+ * key a caller would put in an HTTP header.
173
+ */
174
+ const TRACEPARENT_KEY = "traceparent";
175
+ const TRACESTATE_KEY = "tracestate";
176
+
163
177
  /** Protocol version whose wire format this server implements natively */
164
178
  const SPEC_2026_07_28 = "2026-07-28";
165
179
 
@@ -212,6 +226,34 @@ interface StatelessClientMeta {
212
226
  readonly clientInfo?: Implementation;
213
227
  readonly clientCapabilities?: ClientCapabilities;
214
228
  readonly logLevel?: McpLogLevel;
229
+ /** Caller's W3C trace context, so the tool span joins their trace. */
230
+ readonly traceContext?: SpanContext;
231
+ }
232
+
233
+ /**
234
+ * Read the W3C trace context out of `params._meta` (spec 2026-07-28, SEP-414).
235
+ *
236
+ * A malformed header leaves the span unparented rather than failing the call:
237
+ * losing the trace join is an observability gap, refusing the tool call would
238
+ * be an outage.
239
+ *
240
+ * `baggage` is deliberately NOT read. It is an unbounded, caller-controlled
241
+ * key/value list that routinely carries tenant, user and session identifiers,
242
+ * and the only thing this server could do with it is copy it into spans —
243
+ * exporting whatever a caller put there to the trace backend, with no way to
244
+ * know whether it holds a PII or a secret. Propagating it properly means the
245
+ * OTel baggage API and an explicit allowlist of keys; until there is a use case
246
+ * asking for that, reading it at all is a liability. The key stays reserved by
247
+ * the spec, and this server ignores it.
248
+ */
249
+ function readTraceContext(
250
+ meta: Record<string, unknown>,
251
+ ): { traceContext?: SpanContext } {
252
+ const traceContext = parseTraceParent(
253
+ meta[TRACEPARENT_KEY],
254
+ meta[TRACESTATE_KEY],
255
+ );
256
+ return traceContext ? { traceContext } : {};
215
257
  }
216
258
 
217
259
  /** Valid `io.modelcontextprotocol/logLevel` values (RFC 5424 severities). */
@@ -549,6 +591,9 @@ export class McpApp {
549
591
  {
550
592
  capabilities: {
551
593
  tools: {},
594
+ ...(options.expectResources
595
+ ? { resources: { listChanged: true } }
596
+ : {}),
552
597
  },
553
598
  instructions: options.instructions,
554
599
  },
@@ -584,7 +629,7 @@ export class McpApp {
584
629
  }
585
630
 
586
631
  /**
587
- * Pre-install resources/list and resources/read handlers on the low-level
632
+ * Pre-install the resources handlers on the low-level
588
633
  * SDK Server. This declares the `resources` capability BEFORE transport
589
634
  * connection, allowing dynamic resource registration after start().
590
635
  *
@@ -592,20 +637,24 @@ export class McpApp {
592
637
  * by registerResource() calls (e.g., after async MCP discovery).
593
638
  */
594
639
  private installResourceHandlers(): void {
640
+ if (this.resourceHandlersInstalled) return;
641
+ if (this.started) {
642
+ throw new Error(
643
+ "[McpApp] Cannot install resource handlers after the server starts. " +
644
+ "Set expectResources: true or register resources before start().",
645
+ );
646
+ }
595
647
  const server = this.mcpServer.server;
596
648
 
597
649
  // Declare resources capability before transport connects
598
- server.registerCapabilities({ resources: {} });
650
+ server.registerCapabilities({ resources: { listChanged: true } });
599
651
 
600
652
  // resources/list — returns currently registered resources
601
653
  server.setRequestHandler(ListResourcesRequestSchema, () => {
602
654
  return {
603
- resources: Array.from(this.resources.values()).map((r) => ({
604
- uri: r.resource.uri,
605
- name: r.resource.name,
606
- description: r.resource.description,
607
- mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
608
- })),
655
+ resources: Array.from(this.resources.values()).map((r) =>
656
+ this.toResourceListing(r.resource)
657
+ ),
609
658
  };
610
659
  });
611
660
 
@@ -616,12 +665,18 @@ export class McpApp {
616
665
  const uri = request.params.uri;
617
666
  const info = this.resources.get(uri);
618
667
  if (!info) {
619
- throw new Error(`Resource not found: ${uri}`);
668
+ throw new McpError(
669
+ ErrorCode.InvalidParams,
670
+ `Resource not found: ${uri}`,
671
+ );
620
672
  }
621
673
 
622
674
  try {
623
- const content = await info.handler(new URL(uri));
624
- const finalContent = this.applyResourceCsp(content);
675
+ const finalContent = await this.readResourceForProtocol(
676
+ uri,
677
+ info.resource,
678
+ info.handler,
679
+ );
625
680
  return { contents: [finalContent] };
626
681
  } catch (error) {
627
682
  this.log(
@@ -634,8 +689,15 @@ export class McpApp {
634
689
  },
635
690
  );
636
691
 
692
+ // We currently expose concrete resources only. An explicit empty template
693
+ // list is nevertheless required once the resources capability exists:
694
+ // clients are entitled to ask which URI templates can be expanded.
695
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
696
+ resourceTemplates: [],
697
+ }));
698
+
637
699
  this.resourceHandlersInstalled = true;
638
- this.log("Resources capability pre-declared (expectResources: true)");
700
+ this.resourceLog("Resources capability installed");
639
701
  }
640
702
 
641
703
  /**
@@ -661,9 +723,31 @@ export class McpApp {
661
723
  const toolName = request.params.name;
662
724
  const args = request.params.arguments || {};
663
725
 
726
+ // Per-request `_meta` is transport-independent. Trace context matters
727
+ // here because a local server is exactly where a detached span is
728
+ // hardest to correlate back to the host that caused it; `logLevel` is
729
+ // read for the same reason it is on HTTP — the spec makes it
730
+ // 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
+ }
739
+ : undefined;
740
+
664
741
  let result: unknown;
665
742
  try {
666
- result = await this.executeToolCall(toolName, args);
743
+ result = await this.executeToolCall(
744
+ toolName,
745
+ args,
746
+ undefined,
747
+ undefined,
748
+ undefined,
749
+ clientMeta,
750
+ );
667
751
  } catch (error) {
668
752
  return this.handleToolError(error, toolName);
669
753
  }
@@ -673,6 +757,66 @@ export class McpApp {
673
757
  return this.buildToolCallResult(toolName, result);
674
758
  },
675
759
  );
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
+ }
788
+
789
+ /**
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.
795
+ *
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.
804
+ */
805
+ private buildDiscoverResult(): Record<string, unknown> {
806
+ return this.stampResult(
807
+ this.withCacheHints({
808
+ supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
809
+ capabilities: this.buildServerCapabilities(),
810
+ serverInfo: {
811
+ name: this.options.name,
812
+ version: this.options.version,
813
+ },
814
+ ...(this.options.instructions
815
+ ? { instructions: this.options.instructions }
816
+ : {}),
817
+ }, SPEC_2026_07_28),
818
+ SPEC_2026_07_28,
819
+ );
676
820
  }
677
821
 
678
822
  /**
@@ -1008,12 +1152,16 @@ export class McpApp {
1008
1152
  };
1009
1153
 
1010
1154
  // OTel span + metrics
1011
- const span = startToolCallSpan(toolName, {
1012
- "mcp.tool.name": toolName,
1013
- "mcp.server.name": this.options.name,
1014
- "mcp.transport": request ? "http" : "stdio",
1015
- "mcp.session.id": sessionId,
1016
- });
1155
+ const span = startToolCallSpan(
1156
+ toolName,
1157
+ {
1158
+ "mcp.tool.name": toolName,
1159
+ "mcp.server.name": this.options.name,
1160
+ "mcp.transport": request ? "http" : "stdio",
1161
+ "mcp.session.id": sessionId,
1162
+ },
1163
+ clientMeta?.traceContext,
1164
+ );
1017
1165
 
1018
1166
  // Update gauges before execution
1019
1167
  const queueMetrics = this.requestQueue.getMetrics();
@@ -1043,32 +1191,260 @@ export class McpApp {
1043
1191
  // Resource Registration (MCP Apps SEP-1865)
1044
1192
  // ============================================
1045
1193
 
1046
- /**
1047
- * Validate resource URI scheme
1048
- * Logs warning if not using ui:// scheme (MCP Apps standard)
1049
- */
1050
1194
  /**
1051
1195
  * Apply CSP meta tag injection to HTML resource content (if configured).
1052
- * Only transforms HTML content (checks mimeType); non-HTML passes through.
1196
+ * Only transforms text HTML content; blob responses pass through unchanged.
1053
1197
  */
1054
- private applyResourceCsp(
1055
- content: import("./types.js").ResourceContent,
1056
- ): import("./types.js").ResourceContent {
1198
+ private applyResourceCsp(content: ResourceContent): ResourceContent {
1057
1199
  if (!this.options.resourceCsp) return content;
1058
- if (!content.mimeType?.includes("text/html")) return content;
1200
+ const mediaType = content.mimeType.split(";", 1)[0].trim().toLowerCase();
1201
+ if (
1202
+ !this.isTextResourceContent(content) ||
1203
+ mediaType !== "text/html"
1204
+ ) {
1205
+ return content;
1206
+ }
1059
1207
 
1060
1208
  const cspValue = buildCspHeader(this.options.resourceCsp);
1061
1209
  return {
1062
1210
  ...content,
1063
- text: injectCspMetaTag(content.text ?? "", cspValue),
1211
+ text: injectCspMetaTag(content.text, cspValue),
1064
1212
  };
1065
1213
  }
1066
1214
 
1215
+ private isTextResourceContent(
1216
+ content: ResourceContent,
1217
+ ): content is Extract<ResourceContent, { text: string }> {
1218
+ return "text" in content;
1219
+ }
1220
+
1221
+ /** Standard padded base64 with zero pad bits, without whitespace or URL-safe substitutions. */
1222
+ private isCanonicalBase64(blob: string): boolean {
1223
+ try {
1224
+ // `atob` accepts several equivalent spellings. Re-encoding is what
1225
+ // rejects omitted padding, whitespace, URL-safe alphabets, and non-zero
1226
+ // pad bits such as `/x==` (whose canonical form is `/w==`). Both APIs are
1227
+ // Web-standard globals available in Deno and supported Node runtimes.
1228
+ return btoa(atob(blob)) === blob;
1229
+ } catch {
1230
+ return false;
1231
+ }
1232
+ }
1233
+
1234
+ /**
1235
+ * Validate an untrusted handler result at the API boundary.
1236
+ *
1237
+ * TypeScript callers get the discriminated `ResourceContent` union at compile
1238
+ * time. This check closes the equivalent JavaScript, `any`, and unchecked
1239
+ * TypeScript paths before a malformed result reaches an MCP client.
1240
+ */
1241
+ private validateResourceContent(
1242
+ requestedUri: string,
1243
+ candidate: unknown,
1244
+ resource: MCPResource,
1245
+ ): ResourceContent {
1246
+ if (!isRecord(candidate)) {
1247
+ throw new Error("[McpApp] Resource handler must return an object");
1248
+ }
1249
+
1250
+ const hasText = Object.prototype.hasOwnProperty.call(candidate, "text");
1251
+ const hasBlob = Object.prototype.hasOwnProperty.call(candidate, "blob");
1252
+ if (hasText === hasBlob) {
1253
+ throw new Error(
1254
+ "[McpApp] Resource content must contain exactly one of text or blob",
1255
+ );
1256
+ }
1257
+ if (candidate.uri !== requestedUri) {
1258
+ throw new Error(
1259
+ `[McpApp] Resource content URI must match requested URI: ${requestedUri}`,
1260
+ );
1261
+ }
1262
+ if (Object.prototype.hasOwnProperty.call(candidate, "annotations")) {
1263
+ throw new Error(
1264
+ "[McpApp] Resource content annotations are not a ResourceContents field; put annotations on MCPResource metadata",
1265
+ );
1266
+ }
1267
+ if (candidate._meta !== undefined && !isRecord(candidate._meta)) {
1268
+ throw new Error(
1269
+ "[McpApp] Resource content _meta must be an object when supplied",
1270
+ );
1271
+ }
1272
+ if (
1273
+ typeof candidate.mimeType !== "string" ||
1274
+ candidate.mimeType.trim().length === 0
1275
+ ) {
1276
+ throw new Error(
1277
+ "[McpApp] Resource content mimeType must be a non-empty string",
1278
+ );
1279
+ }
1280
+ if (hasText && typeof candidate.text !== "string") {
1281
+ throw new Error("[McpApp] Resource content text must be a string");
1282
+ }
1283
+ if (hasBlob) {
1284
+ if (typeof candidate.blob !== "string") {
1285
+ throw new Error("[McpApp] Resource content blob must be a string");
1286
+ }
1287
+ if (!this.isCanonicalBase64(candidate.blob)) {
1288
+ throw new Error(
1289
+ "[McpApp] Resource content blob must be canonical standard base64",
1290
+ );
1291
+ }
1292
+ }
1293
+
1294
+ if (
1295
+ resource.mimeType !== undefined &&
1296
+ candidate.mimeType !== resource.mimeType
1297
+ ) {
1298
+ throw new Error(
1299
+ `[McpApp] Resource content mimeType must match registered metadata: ${resource.mimeType}`,
1300
+ );
1301
+ }
1302
+ if (resource.size !== undefined) {
1303
+ const actualSize = hasText
1304
+ ? new TextEncoder().encode(candidate.text as string).byteLength
1305
+ : atob(candidate.blob as string).length;
1306
+ if (actualSize !== resource.size) {
1307
+ throw new Error(
1308
+ `[McpApp] Resource content size must match registered metadata: expected ${resource.size}, got ${actualSize}`,
1309
+ );
1310
+ }
1311
+ }
1312
+
1313
+ // Do not forward arbitrary JavaScript fields to the wire. In particular,
1314
+ // annotations belong to Resource, not ResourceContents in the MCP schema.
1315
+ return hasText
1316
+ ? {
1317
+ uri: requestedUri,
1318
+ mimeType: candidate.mimeType,
1319
+ text: candidate.text as string,
1320
+ ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1321
+ }
1322
+ : {
1323
+ uri: requestedUri,
1324
+ mimeType: candidate.mimeType,
1325
+ blob: candidate.blob as string,
1326
+ ...(candidate._meta !== undefined ? { _meta: candidate._meta } : {}),
1327
+ };
1328
+ }
1329
+
1330
+ /** Run, validate, and CSP-harden a handler for a protocol response. */
1331
+ private async readResourceForProtocol(
1332
+ requestedUri: string,
1333
+ resource: MCPResource,
1334
+ handler: ResourceHandler,
1335
+ ): Promise<ResourceContent> {
1336
+ const content = this.validateResourceContent(
1337
+ requestedUri,
1338
+ await handler(new URL(requestedUri)),
1339
+ resource,
1340
+ );
1341
+ // Size attests the bytes delivered to the client. CSP injection changes a
1342
+ // text body, so validate the served representation too rather than only
1343
+ // the handler's pre-injection value.
1344
+ return this.validateResourceContent(
1345
+ requestedUri,
1346
+ this.applyResourceCsp(content),
1347
+ resource,
1348
+ );
1349
+ }
1350
+
1351
+ /** Convert public metadata into the exact wire listing shape. */
1352
+ private toResourceListing(resource: MCPResource): Record<string, unknown> {
1353
+ return {
1354
+ uri: resource.uri,
1355
+ name: resource.name,
1356
+ ...(resource.title !== undefined ? { title: resource.title } : {}),
1357
+ ...(resource.description !== undefined
1358
+ ? { description: resource.description }
1359
+ : {}),
1360
+ ...(resource.mimeType !== undefined
1361
+ ? { mimeType: resource.mimeType }
1362
+ : {}),
1363
+ ...(resource.size !== undefined ? { size: resource.size } : {}),
1364
+ ...(resource.icons !== undefined ? { icons: resource.icons } : {}),
1365
+ ...(resource.annotations !== undefined
1366
+ ? { annotations: resource.annotations }
1367
+ : {}),
1368
+ ...(resource._meta !== undefined ? { _meta: resource._meta } : {}),
1369
+ };
1370
+ }
1371
+
1372
+ /** Fail early rather than publishing a metadata value clients must ignore. */
1373
+ private validateResourceMetadata(resource: MCPResource): void {
1374
+ this.validateResourceUri(resource.uri);
1375
+ if (typeof resource.name !== "string" || resource.name.length === 0) {
1376
+ throw new Error("[McpApp] Resource name must be a non-empty string");
1377
+ }
1378
+ if (
1379
+ resource.mimeType !== undefined &&
1380
+ (typeof resource.mimeType !== "string" ||
1381
+ resource.mimeType.trim().length === 0)
1382
+ ) {
1383
+ throw new Error(
1384
+ "[McpApp] Resource mimeType must be a non-empty string when supplied",
1385
+ );
1386
+ }
1387
+ if (
1388
+ resource.size !== undefined &&
1389
+ (!Number.isSafeInteger(resource.size) || resource.size < 0)
1390
+ ) {
1391
+ throw new Error(
1392
+ `[McpApp] Resource size must be a non-negative safe integer (got ${resource.size})`,
1393
+ );
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Resources are keyed by their wire URI, so accepting a spelling which URL
1399
+ * canonicalisation changes would make list/read/handler identity ambiguous.
1400
+ * Refuse it at registration instead of silently normalising a caller-owned
1401
+ * identifier. Non-`ui:` schemes are valid MCP resources and remain allowed.
1402
+ */
1067
1403
  private validateResourceUri(uri: string): void {
1068
- if (!uri.startsWith(MCP_APP_URI_SCHEME)) {
1069
- this.log(
1070
- `[WARN] Resource URI "${uri}" does not use ${MCP_APP_URI_SCHEME} scheme. ` +
1071
- `MCP Apps standard requires ui:// URIs.`,
1404
+ if (typeof uri !== "string" || uri.length === 0) {
1405
+ throw new Error("[McpApp] Resource URI must be a non-empty string");
1406
+ }
1407
+ let canonical: string;
1408
+ try {
1409
+ canonical = new URL(uri).toString();
1410
+ } catch {
1411
+ throw new Error(`[McpApp] Resource URI must be an absolute URI: ${uri}`);
1412
+ }
1413
+ if (canonical !== uri) {
1414
+ throw new Error(
1415
+ `[McpApp] Resource URI must be canonical: received ${uri}, canonical form is ${canonical}`,
1416
+ );
1417
+ }
1418
+ }
1419
+
1420
+ /** A consumer logger is observability, never a resource-commit dependency. */
1421
+ private resourceLog(message: string): void {
1422
+ try {
1423
+ this.log(message);
1424
+ } catch {
1425
+ // Deliberately ignored: a throwing logger must not contradict a committed
1426
+ // resource mutation or make a retry appear necessary.
1427
+ }
1428
+ }
1429
+
1430
+ /**
1431
+ * Publish the one post-commit list-changed projection for a mutation.
1432
+ * It is best-effort by design: registry state is authoritative and callers
1433
+ * must not receive a false failure after it changes.
1434
+ */
1435
+ private notifyResourceListChanged(): void {
1436
+ 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) {
1444
+ this.resourceLog(
1445
+ `[WARN] Resource list changed notification was not delivered: ${
1446
+ error instanceof Error ? error.message : String(error)
1447
+ }`,
1072
1448
  );
1073
1449
  }
1074
1450
  }
@@ -1093,8 +1469,11 @@ export class McpApp {
1093
1469
  * ```
1094
1470
  */
1095
1471
  registerResource(resource: MCPResource, handler: ResourceHandler): void {
1096
- // Validate URI scheme
1097
- this.validateResourceUri(resource.uri);
1472
+ this.validateResourceMetadata(resource);
1473
+
1474
+ if (typeof handler !== "function") {
1475
+ throw new Error("[McpApp] Resource handler must be a function");
1476
+ }
1098
1477
 
1099
1478
  // Check for duplicate
1100
1479
  if (this.resources.has(resource.uri)) {
@@ -1103,41 +1482,40 @@ export class McpApp {
1103
1482
  );
1104
1483
  }
1105
1484
 
1106
- if (this.resourceHandlersInstalled) {
1107
- // expectResources mode: handlers are already installed on the low-level
1108
- // server. Just add to our internal registry — the handlers read from
1109
- // this.resources dynamically.
1110
- this.resources.set(resource.uri, { resource, handler });
1111
- } else {
1112
- // Standard mode: register via SDK (must be called before start())
1113
- this.mcpServer.registerResource(
1114
- resource.name,
1115
- resource.uri,
1116
- {
1117
- description: resource.description,
1118
- mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,
1119
- },
1120
- async (uri: URL) => {
1121
- try {
1122
- const content = await handler(uri);
1123
- const finalContent = this.applyResourceCsp(content);
1124
- return { contents: [finalContent] };
1125
- } catch (error) {
1126
- this.log(
1127
- `[ERROR] Resource handler failed for ${uri}: ${
1128
- error instanceof Error ? error.message : String(error)
1129
- }`,
1130
- );
1131
- throw error;
1132
- }
1133
- },
1134
- );
1135
-
1136
- // Track in our registry
1137
- this.resources.set(resource.uri, { resource, handler });
1485
+ // Static registrations lazily install the single low-level handler set.
1486
+ // Once a transport starts, handler installation would be too late, so a
1487
+ // deployment that needs late discovery must opt in with expectResources.
1488
+ if (!this.resourceHandlersInstalled) {
1489
+ if (this.started) {
1490
+ throw new Error(
1491
+ "[McpApp] Cannot register a resource after start without expectResources: true.",
1492
+ );
1493
+ }
1494
+ this.installResourceHandlers();
1138
1495
  }
1139
1496
 
1140
- this.log(`Registered resource: ${resource.name} (${resource.uri})`);
1497
+ // The Map is the only registry. It commits atomically and has no secondary
1498
+ // SDK entry which could survive a failed rollback as a ghost resource.
1499
+ this.resources.set(resource.uri, { resource, handler });
1500
+ this.resourceLog(`Registered resource: ${resource.name} (${resource.uri})`);
1501
+ this.notifyResourceListChanged();
1502
+ }
1503
+
1504
+ /**
1505
+ * Remove a resource from this server.
1506
+ *
1507
+ * It is safe before or after either transport starts once resources are
1508
+ * installed. Returns `false` when no such URI is present, so callers can make
1509
+ * idempotent cleanup calls without catching an error.
1510
+ */
1511
+ unregisterResource(uri: string): boolean {
1512
+ const info = this.resources.get(uri);
1513
+ if (!info) return false;
1514
+
1515
+ this.resources.delete(uri);
1516
+ this.resourceLog(`Unregistered resource: ${uri}`);
1517
+ this.notifyResourceListChanged();
1518
+ return true;
1141
1519
  }
1142
1520
 
1143
1521
  /**
@@ -1151,6 +1529,8 @@ export class McpApp {
1151
1529
  resources: MCPResource[],
1152
1530
  handlers: Map<string, ResourceHandler>,
1153
1531
  ): void {
1532
+ // No mutation means no capability installation and no notification.
1533
+ if (resources.length === 0) return;
1154
1534
  // Validate all handlers exist BEFORE registering any (fail-fast)
1155
1535
  const missingHandlers: string[] = [];
1156
1536
  for (const resource of resources) {
@@ -1181,19 +1561,50 @@ export class McpApp {
1181
1561
  );
1182
1562
  }
1183
1563
 
1184
- // All validations passed, register resources
1564
+ // A duplicate inside this batch would otherwise fail only when the second
1565
+ // registration is attempted, after the first has been made visible.
1566
+ const seenUris = new Set<string>();
1567
+ const repeatedUris = resources
1568
+ .map((resource) => resource.uri)
1569
+ .filter((uri) => {
1570
+ if (seenUris.has(uri)) return true;
1571
+ seenUris.add(uri);
1572
+ return false;
1573
+ });
1574
+ if (repeatedUris.length > 0) {
1575
+ throw new Error(
1576
+ `[McpApp] Resources are repeated in this batch:\n` +
1577
+ repeatedUris.map((uri) => ` - ${uri}`).join("\n"),
1578
+ );
1579
+ }
1580
+
1185
1581
  for (const resource of resources) {
1186
- const handler = handlers.get(resource.uri);
1187
- if (!handler) {
1188
- // Should never happen after validation, but defensive check
1582
+ this.validateResourceMetadata(resource);
1583
+ if (typeof handlers.get(resource.uri) !== "function") {
1189
1584
  throw new Error(
1190
- `[McpApp] Handler disappeared for ${resource.uri}`,
1585
+ `[McpApp] Resource handler must be a function: ${resource.uri}`,
1191
1586
  );
1192
1587
  }
1193
- this.registerResource(resource, handler);
1194
1588
  }
1195
-
1196
- this.log(`Registered ${resources.length} resources`);
1589
+ if (!this.resourceHandlersInstalled) {
1590
+ if (this.started) {
1591
+ throw new Error(
1592
+ "[McpApp] Cannot register resources after start without expectResources: true.",
1593
+ );
1594
+ }
1595
+ this.installResourceHandlers();
1596
+ }
1597
+ // All validation and the one possible handler-install side effect happened
1598
+ // before this point. A Map update cannot partially fail, so the batch gets
1599
+ // one commit and one notification (or neither on validation failure).
1600
+ for (const resource of resources) {
1601
+ this.resources.set(resource.uri, {
1602
+ resource,
1603
+ handler: handlers.get(resource.uri)!,
1604
+ });
1605
+ }
1606
+ this.resourceLog(`Registered ${resources.length} resources`);
1607
+ if (resources.length > 0) this.notifyResourceListChanged();
1197
1608
  }
1198
1609
 
1199
1610
  /**
@@ -1257,13 +1668,13 @@ export class McpApp {
1257
1668
  },
1258
1669
  async () => {
1259
1670
  const html = await Promise.resolve(readFile(currentDistPath));
1260
- const content: import("./types.js").ResourceContent = {
1671
+ const content: ResourceContent = {
1261
1672
  uri: resourceUri,
1262
1673
  mimeType: MCP_APP_MIME_TYPE,
1263
1674
  text: html,
1264
1675
  };
1265
1676
  if (config.csp) {
1266
- (content as unknown as Record<string, unknown>)._meta = {
1677
+ content._meta = {
1267
1678
  ui: { csp: config.csp },
1268
1679
  };
1269
1680
  }
@@ -1927,20 +2338,7 @@ export class McpApp {
1927
2338
  return c.json({
1928
2339
  jsonrpc: "2.0",
1929
2340
  id,
1930
- result: this.stampResult(
1931
- this.withCacheHints({
1932
- supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1933
- capabilities: this.buildServerCapabilities(),
1934
- serverInfo: {
1935
- name: this.options.name,
1936
- version: this.options.version,
1937
- },
1938
- ...(this.options.instructions
1939
- ? { instructions: this.options.instructions }
1940
- : {}),
1941
- }, statelessVersion),
1942
- statelessVersion,
1943
- ),
2341
+ result: this.buildDiscoverResult(),
1944
2342
  });
1945
2343
  }
1946
2344
 
@@ -2005,6 +2403,7 @@ export class McpApp {
2005
2403
  STATELESS_CLIENT_CAPABILITIES_KEY
2006
2404
  ] as ClientCapabilities | undefined,
2007
2405
  logLevel: readLogLevel(params["_meta"]),
2406
+ ...readTraceContext(params["_meta"]),
2008
2407
  }
2009
2408
  : undefined;
2010
2409
 
@@ -2494,18 +2893,28 @@ export class McpApp {
2494
2893
  id,
2495
2894
  result: this.stampResult(
2496
2895
  this.withCacheHints({
2497
- resources: Array.from(this.resources.values()).map((r) => ({
2498
- uri: r.resource.uri,
2499
- name: r.resource.name,
2500
- description: r.resource.description,
2501
- mimeType: r.resource.mimeType ?? MCP_APP_MIME_TYPE,
2502
- })),
2896
+ resources: Array.from(this.resources.values()).map((r) =>
2897
+ this.toResourceListing(r.resource)
2898
+ ),
2503
2899
  }, statelessVersion),
2504
2900
  statelessVersion,
2505
2901
  ),
2506
2902
  });
2507
2903
  }
2508
2904
 
2905
+ // Concrete resources only for now. Keep this endpoint explicit rather
2906
+ // than falling through to MethodNotFound once resources are advertised.
2907
+ if (method === "resources/templates/list") {
2908
+ return c.json({
2909
+ jsonrpc: "2.0",
2910
+ id,
2911
+ result: this.stampResult(
2912
+ this.withCacheHints({ resourceTemplates: [] }, statelessVersion),
2913
+ statelessVersion,
2914
+ ),
2915
+ });
2916
+ }
2917
+
2509
2918
  // Resources read
2510
2919
  if (method === "resources/read") {
2511
2920
  // Dispatch by method, not the truthiness of its routing parameter.
@@ -2541,8 +2950,11 @@ export class McpApp {
2541
2950
  }
2542
2951
 
2543
2952
  try {
2544
- const content = await resourceInfo.handler(new URL(uri));
2545
- const finalContent = this.applyResourceCsp(content);
2953
+ const finalContent = await this.readResourceForProtocol(
2954
+ uri,
2955
+ resourceInfo.resource,
2956
+ resourceInfo.handler,
2957
+ );
2546
2958
  return c.json({
2547
2959
  jsonrpc: "2.0",
2548
2960
  id,
@@ -3270,7 +3682,11 @@ export class McpApp {
3270
3682
  async readResourceContent(uri: string): Promise<ResourceContent | null> {
3271
3683
  const entry = this.resources.get(uri);
3272
3684
  if (!entry) return null;
3273
- return await entry.handler(new URL(uri));
3685
+ return this.validateResourceContent(
3686
+ uri,
3687
+ await entry.handler(new URL(uri)),
3688
+ entry.resource,
3689
+ );
3274
3690
  }
3275
3691
 
3276
3692
  /**
@@ -3799,7 +4215,12 @@ export class McpApp {
3799
4215
  // created from it, so advertising and behaviour cannot drift apart.
3800
4216
  return {
3801
4217
  tools: {},
3802
- resources: this.resources.size > 0 ? {} : undefined,
4218
+ // Capability lifetime is defined by installed handlers, not the current
4219
+ // Map size. A dynamic registry may correctly be empty at initialize and
4220
+ // gain resources later; `listChanged` tells clients to refresh then.
4221
+ resources: this.resourceHandlersInstalled
4222
+ ? { listChanged: true }
4223
+ : undefined,
3803
4224
  ...(extensions && Object.keys(extensions).length > 0
3804
4225
  ? { extensions }
3805
4226
  : {}),