@casys/mcp-server 0.25.0 → 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/README.md CHANGED
@@ -440,6 +440,54 @@ server.registerResource(
440
440
  );
441
441
  ```
442
442
 
443
+ Handlers return one payload form: `text` (including HTML) **or** `blob` for
444
+ binary content encoded as standard padded base64. Existing text handlers remain
445
+ valid. The framework also checks at runtime that the response URI exactly
446
+ matches the requested URI and that the MIME type is non-empty, which protects
447
+ JavaScript and unchecked TypeScript handlers as well as typed callers.
448
+
449
+ ```typescript
450
+ server.registerResource(
451
+ { uri: "file://reports/latest.pdf", name: "Latest report", size: 184_320 },
452
+ async (uri) => ({
453
+ uri: uri.toString(),
454
+ mimeType: "application/pdf",
455
+ blob: await loadReportAsCanonicalBase64(),
456
+ }),
457
+ );
458
+ ```
459
+
460
+ `size` is optional resource metadata shown in `resources/list`; when present it
461
+ must be a non-negative safe integer and is verified on every read against the
462
+ exact UTF-8 byte length of `text` or decoded byte length of `blob`. Supplying
463
+ `mimeType` in the resource metadata likewise binds every response to that exact
464
+ MIME type. If it is absent, it is absent from `resources/list`; the handler
465
+ still declares the MIME type when it serves the bytes. Resource content may
466
+ include `_meta`. Put `annotations`, `icons`, `title`, and resource `_meta` on
467
+ the `MCPResource` registration, where MCP defines those fields.
468
+
469
+ With `resourceCsp`, CSP injection applies only to the `text` branch of an HTML
470
+ resource. Blobs are never decoded, transformed, or re-encoded.
471
+
472
+ Register resources before `start()` / `startHttp()` to install the resource
473
+ handlers and advertise `resources: { listChanged: true }`. They can then be
474
+ added or removed at any time through `unregisterResource(uri)`, which returns
475
+ `true` only once. For a registry that starts empty and discovers resources
476
+ asynchronously, construct with `expectResources: true`; that mode installs the
477
+ same handlers at construction time:
478
+
479
+ ```typescript
480
+ const app = new McpApp({
481
+ name: "relay",
482
+ version: "1.0.0",
483
+ expectResources: true,
484
+ });
485
+
486
+ // After start(): list/read/templates handlers are already installed.
487
+ app.registerResource(resource, handler);
488
+ app.unregisterResource(resource.uri); // true, then false if called again
489
+ ```
490
+
443
491
  #### Capability negotiation (clients that don't support MCP Apps)
444
492
 
445
493
  Not every MCP client renders UI resources. Clients that do advertise the
@@ -506,11 +554,12 @@ to introspect the protocol target directly.
506
554
  ```typescript
507
555
  const server = new McpApp(options: McpAppOptions);
508
556
 
509
- // Registration (before start)
557
+ // Registration (before start, unless expectResources: true)
510
558
  server.registerTool(tool, handler);
511
559
  server.registerTools(tools, handlers);
512
560
  server.registerResource(resource, handler);
513
561
  server.registerResources(resources, handlers);
562
+ server.unregisterResource(resourceUri); // safe before or after start
514
563
  server.use(middleware);
515
564
 
516
565
  // Transport
package/mod.ts CHANGED
@@ -66,6 +66,7 @@ export type {
66
66
 
67
67
  // Type exports
68
68
  export type {
69
+ BlobResourceContent,
69
70
  HttpRateLimitContext,
70
71
  HttpRateLimitOptions,
71
72
  HttpServerInstance,
@@ -86,6 +87,7 @@ export type {
86
87
  SamplingParams,
87
88
  SamplingResult,
88
89
  StructuredToolResult,
90
+ TextResourceContent,
89
91
  ToolAnnotations,
90
92
  ToolErrorMapper,
91
93
  ToolHandler,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
package/src/mcp-app.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  type Implementation,
21
21
  type JSONRPCRequest,
22
22
  ListResourcesRequestSchema,
23
+ ListResourceTemplatesRequestSchema,
23
24
  ListToolsRequestSchema,
24
25
  McpError,
25
26
  type ReadResourceRequest,
@@ -67,11 +68,7 @@ import type {
67
68
  StructuredToolResult,
68
69
  ToolHandler,
69
70
  } from "./types.js";
70
- import {
71
- getMcpAppsCapability,
72
- MCP_APP_MIME_TYPE,
73
- MCP_APP_URI_SCHEME,
74
- } from "./types.js";
71
+ import { getMcpAppsCapability, MCP_APP_MIME_TYPE } from "./types.js";
75
72
  import { discoverViewers, resolveViewerDistPath } from "./ui/viewer-utils.js";
76
73
  import type { DiscoverViewersFS } from "./ui/viewer-utils.js";
77
74
  import { buildCspHeader, injectCspMetaTag } from "./security/csp.js";
@@ -594,6 +591,9 @@ export class McpApp {
594
591
  {
595
592
  capabilities: {
596
593
  tools: {},
594
+ ...(options.expectResources
595
+ ? { resources: { listChanged: true } }
596
+ : {}),
597
597
  },
598
598
  instructions: options.instructions,
599
599
  },
@@ -629,7 +629,7 @@ export class McpApp {
629
629
  }
630
630
 
631
631
  /**
632
- * Pre-install resources/list and resources/read handlers on the low-level
632
+ * Pre-install the resources handlers on the low-level
633
633
  * SDK Server. This declares the `resources` capability BEFORE transport
634
634
  * connection, allowing dynamic resource registration after start().
635
635
  *
@@ -637,20 +637,24 @@ export class McpApp {
637
637
  * by registerResource() calls (e.g., after async MCP discovery).
638
638
  */
639
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
+ }
640
647
  const server = this.mcpServer.server;
641
648
 
642
649
  // Declare resources capability before transport connects
643
- server.registerCapabilities({ resources: {} });
650
+ server.registerCapabilities({ resources: { listChanged: true } });
644
651
 
645
652
  // resources/list — returns currently registered resources
646
653
  server.setRequestHandler(ListResourcesRequestSchema, () => {
647
654
  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
- })),
655
+ resources: Array.from(this.resources.values()).map((r) =>
656
+ this.toResourceListing(r.resource)
657
+ ),
654
658
  };
655
659
  });
656
660
 
@@ -661,12 +665,18 @@ export class McpApp {
661
665
  const uri = request.params.uri;
662
666
  const info = this.resources.get(uri);
663
667
  if (!info) {
664
- throw new Error(`Resource not found: ${uri}`);
668
+ throw new McpError(
669
+ ErrorCode.InvalidParams,
670
+ `Resource not found: ${uri}`,
671
+ );
665
672
  }
666
673
 
667
674
  try {
668
- const content = await info.handler(new URL(uri));
669
- const finalContent = this.applyResourceCsp(content);
675
+ const finalContent = await this.readResourceForProtocol(
676
+ uri,
677
+ info.resource,
678
+ info.handler,
679
+ );
670
680
  return { contents: [finalContent] };
671
681
  } catch (error) {
672
682
  this.log(
@@ -679,8 +689,15 @@ export class McpApp {
679
689
  },
680
690
  );
681
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
+
682
699
  this.resourceHandlersInstalled = true;
683
- this.log("Resources capability pre-declared (expectResources: true)");
700
+ this.resourceLog("Resources capability installed");
684
701
  }
685
702
 
686
703
  /**
@@ -1174,32 +1191,260 @@ export class McpApp {
1174
1191
  // Resource Registration (MCP Apps SEP-1865)
1175
1192
  // ============================================
1176
1193
 
1177
- /**
1178
- * Validate resource URI scheme
1179
- * Logs warning if not using ui:// scheme (MCP Apps standard)
1180
- */
1181
1194
  /**
1182
1195
  * Apply CSP meta tag injection to HTML resource content (if configured).
1183
- * Only transforms HTML content (checks mimeType); non-HTML passes through.
1196
+ * Only transforms text HTML content; blob responses pass through unchanged.
1184
1197
  */
1185
- private applyResourceCsp(
1186
- content: import("./types.js").ResourceContent,
1187
- ): import("./types.js").ResourceContent {
1198
+ private applyResourceCsp(content: ResourceContent): ResourceContent {
1188
1199
  if (!this.options.resourceCsp) return content;
1189
- 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
+ }
1190
1207
 
1191
1208
  const cspValue = buildCspHeader(this.options.resourceCsp);
1192
1209
  return {
1193
1210
  ...content,
1194
- text: injectCspMetaTag(content.text ?? "", cspValue),
1211
+ text: injectCspMetaTag(content.text, cspValue),
1195
1212
  };
1196
1213
  }
1197
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
+ */
1198
1403
  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.`,
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
+ }`,
1203
1448
  );
1204
1449
  }
1205
1450
  }
@@ -1224,8 +1469,11 @@ export class McpApp {
1224
1469
  * ```
1225
1470
  */
1226
1471
  registerResource(resource: MCPResource, handler: ResourceHandler): void {
1227
- // Validate URI scheme
1228
- 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
+ }
1229
1477
 
1230
1478
  // Check for duplicate
1231
1479
  if (this.resources.has(resource.uri)) {
@@ -1234,41 +1482,40 @@ export class McpApp {
1234
1482
  );
1235
1483
  }
1236
1484
 
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 });
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();
1269
1495
  }
1270
1496
 
1271
- 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;
1272
1519
  }
1273
1520
 
1274
1521
  /**
@@ -1282,6 +1529,8 @@ export class McpApp {
1282
1529
  resources: MCPResource[],
1283
1530
  handlers: Map<string, ResourceHandler>,
1284
1531
  ): void {
1532
+ // No mutation means no capability installation and no notification.
1533
+ if (resources.length === 0) return;
1285
1534
  // Validate all handlers exist BEFORE registering any (fail-fast)
1286
1535
  const missingHandlers: string[] = [];
1287
1536
  for (const resource of resources) {
@@ -1312,19 +1561,50 @@ export class McpApp {
1312
1561
  );
1313
1562
  }
1314
1563
 
1315
- // 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
+
1316
1581
  for (const resource of resources) {
1317
- const handler = handlers.get(resource.uri);
1318
- if (!handler) {
1319
- // Should never happen after validation, but defensive check
1582
+ this.validateResourceMetadata(resource);
1583
+ if (typeof handlers.get(resource.uri) !== "function") {
1320
1584
  throw new Error(
1321
- `[McpApp] Handler disappeared for ${resource.uri}`,
1585
+ `[McpApp] Resource handler must be a function: ${resource.uri}`,
1322
1586
  );
1323
1587
  }
1324
- this.registerResource(resource, handler);
1325
1588
  }
1326
-
1327
- 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();
1328
1608
  }
1329
1609
 
1330
1610
  /**
@@ -1388,13 +1668,13 @@ export class McpApp {
1388
1668
  },
1389
1669
  async () => {
1390
1670
  const html = await Promise.resolve(readFile(currentDistPath));
1391
- const content: import("./types.js").ResourceContent = {
1671
+ const content: ResourceContent = {
1392
1672
  uri: resourceUri,
1393
1673
  mimeType: MCP_APP_MIME_TYPE,
1394
1674
  text: html,
1395
1675
  };
1396
1676
  if (config.csp) {
1397
- (content as unknown as Record<string, unknown>)._meta = {
1677
+ content._meta = {
1398
1678
  ui: { csp: config.csp },
1399
1679
  };
1400
1680
  }
@@ -2613,18 +2893,28 @@ export class McpApp {
2613
2893
  id,
2614
2894
  result: this.stampResult(
2615
2895
  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
- })),
2896
+ resources: Array.from(this.resources.values()).map((r) =>
2897
+ this.toResourceListing(r.resource)
2898
+ ),
2622
2899
  }, statelessVersion),
2623
2900
  statelessVersion,
2624
2901
  ),
2625
2902
  });
2626
2903
  }
2627
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
+
2628
2918
  // Resources read
2629
2919
  if (method === "resources/read") {
2630
2920
  // Dispatch by method, not the truthiness of its routing parameter.
@@ -2660,8 +2950,11 @@ export class McpApp {
2660
2950
  }
2661
2951
 
2662
2952
  try {
2663
- const content = await resourceInfo.handler(new URL(uri));
2664
- const finalContent = this.applyResourceCsp(content);
2953
+ const finalContent = await this.readResourceForProtocol(
2954
+ uri,
2955
+ resourceInfo.resource,
2956
+ resourceInfo.handler,
2957
+ );
2665
2958
  return c.json({
2666
2959
  jsonrpc: "2.0",
2667
2960
  id,
@@ -3389,7 +3682,11 @@ export class McpApp {
3389
3682
  async readResourceContent(uri: string): Promise<ResourceContent | null> {
3390
3683
  const entry = this.resources.get(uri);
3391
3684
  if (!entry) return null;
3392
- return await entry.handler(new URL(uri));
3685
+ return this.validateResourceContent(
3686
+ uri,
3687
+ await entry.handler(new URL(uri)),
3688
+ entry.resource,
3689
+ );
3393
3690
  }
3394
3691
 
3395
3692
  /**
@@ -3918,7 +4215,12 @@ export class McpApp {
3918
4215
  // created from it, so advertising and behaviour cannot drift apart.
3919
4216
  return {
3920
4217
  tools: {},
3921
- 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,
3922
4224
  ...(extensions && Object.keys(extensions).length > 0
3923
4225
  ? { extensions }
3924
4226
  : {}),
@@ -7,6 +7,28 @@
7
7
  */
8
8
 
9
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
+ }
10
32
 
11
33
  const app = new McpApp({
12
34
  name: "e2e-stdio",
@@ -27,4 +49,62 @@ app.registerTool(
27
49
  (args) => args.value ?? "empty",
28
50
  );
29
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
+
30
110
  await app.start();
package/src/types.ts CHANGED
@@ -325,27 +325,84 @@ export interface MCPResource {
325
325
  /** Description of the resource */
326
326
  description?: string;
327
327
 
328
- /** MIME type. Defaults to MCP_APP_MIME_TYPE if not specified */
328
+ /** Optional display title, distinct from the protocol-required `name`. */
329
+ title?: string;
330
+
331
+ /** Optional visual hints advertised in `resources/list`. */
332
+ icons?: Array<{
333
+ src: string;
334
+ mimeType?: string;
335
+ sizes?: string[];
336
+ theme?: "light" | "dark";
337
+ }>;
338
+
339
+ /** Optional client-facing resource annotations. */
340
+ annotations?: {
341
+ audience?: Array<"user" | "assistant">;
342
+ priority?: number;
343
+ lastModified?: string;
344
+ };
345
+
346
+ /** Optional protocol/extension metadata advertised in `resources/list`. */
347
+ _meta?: Record<string, unknown>;
348
+
349
+ /** MIME type, when known before the resource is read. */
329
350
  mimeType?: string;
351
+
352
+ /**
353
+ * Byte size of the resource when it is known.
354
+ *
355
+ * This is an exact byte-size attestation: when supplied, every read must
356
+ * return exactly this many UTF-8 bytes for `text`, or decoded bytes for
357
+ * `blob`. It is surfaced in `resources/list` so clients can make loading
358
+ * decisions before reading. Must be a non-negative safe integer.
359
+ */
360
+ size?: number;
330
361
  }
331
362
 
332
363
  /**
333
- * Content returned by a resource handler
364
+ * Common fields of every resource response.
334
365
  */
335
- export interface ResourceContent {
336
- /** URI of the resource (should match request) */
366
+ interface ResourceContentBase {
367
+ /** URI of the resource. It must exactly match the URI that was requested. */
337
368
  uri: string;
338
- /** MIME type of the content */
369
+ /** Non-empty MIME type of the content. */
339
370
  mimeType: string;
340
- /** The actual content (HTML for MCP Apps) */
371
+ /** Optional MCP metadata passed through to the protocol response. */
372
+ _meta?: Record<string, unknown>;
373
+ }
374
+
375
+ /** A UTF-8/text resource response. */
376
+ export interface TextResourceContent extends ResourceContentBase {
377
+ /** Text payload, including HTML for MCP Apps. */
341
378
  text: string;
379
+ /** Text and blob payloads are mutually exclusive. */
380
+ blob?: never;
381
+ }
382
+
383
+ /** A binary resource response encoded as canonical standard base64. */
384
+ export interface BlobResourceContent extends ResourceContentBase {
385
+ /** Standard, padded base64 payload. */
386
+ blob: string;
387
+ /** Text and blob payloads are mutually exclusive. */
388
+ text?: never;
342
389
  }
343
390
 
391
+ /**
392
+ * Content returned by a resource handler.
393
+ *
394
+ * Exactly one payload form is allowed: `text` for text/HTML, or `blob` for
395
+ * binary content encoded as canonical standard base64. The framework validates
396
+ * the same XOR contract at runtime before writing the response, which keeps
397
+ * JavaScript consumers and unchecked handler results on the protocol-safe path.
398
+ */
399
+ export type ResourceContent = TextResourceContent | BlobResourceContent;
400
+
344
401
  /**
345
402
  * Resource handler callback
346
403
  *
347
404
  * @param uri - The requested resource URI as URL object
348
- * @returns ResourceContent with uri, mimeType, and text
405
+ * @returns A text or base64-blob ResourceContent whose URI matches `uri`
349
406
  *
350
407
  * @example
351
408
  * ```typescript
@@ -354,6 +411,9 @@ export interface ResourceContent {
354
411
  * mimeType: MCP_APP_MIME_TYPE,
355
412
  * text: "<html>...</html>"
356
413
  * });
414
+ *
415
+ * // For binary content, return `blob` instead of `text`:
416
+ * // { uri: uri.toString(), mimeType: "image/png", blob: "iVBORw0KGgo..." }
357
417
  * ```
358
418
  */
359
419
  export type ResourceHandler = (