@modelcontextprotocol/server-everything 1.0.0 → 2.0.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.
Files changed (42) hide show
  1. package/README.md +35 -20
  2. package/dist/docs/architecture.md +6 -5
  3. package/dist/docs/extension.md +5 -3
  4. package/dist/docs/features.md +65 -71
  5. package/dist/docs/how-it-works.md +31 -16
  6. package/dist/docs/instructions.md +14 -7
  7. package/dist/docs/startup.md +28 -33
  8. package/dist/docs/structure.md +63 -29
  9. package/dist/prompts/args.js +2 -2
  10. package/dist/prompts/completions.js +3 -3
  11. package/dist/prompts/resource.js +3 -2
  12. package/dist/resources/files.js +9 -1
  13. package/dist/resources/index.js +7 -2
  14. package/dist/resources/minted.js +119 -0
  15. package/dist/resources/subscriptions.js +44 -122
  16. package/dist/resources/templates.js +5 -4
  17. package/dist/server/context.js +47 -0
  18. package/dist/server/index.js +113 -55
  19. package/dist/server/logging.js +39 -66
  20. package/dist/server/roots.js +41 -62
  21. package/dist/server/tasks.js +295 -0
  22. package/dist/tools/get-header-params.js +95 -0
  23. package/dist/tools/get-roots-list.js +49 -50
  24. package/dist/tools/gzip-file-as-resource.js +24 -5
  25. package/dist/tools/index.js +72 -14
  26. package/dist/tools/simulate-research-query.js +166 -201
  27. package/dist/tools/toggle-simulated-logging.js +33 -20
  28. package/dist/tools/toggle-subscriber-updates.js +33 -23
  29. package/dist/tools/trigger-elicitation-request-async.js +99 -204
  30. package/dist/tools/trigger-elicitation-request.js +197 -196
  31. package/dist/tools/trigger-list-changed.js +57 -0
  32. package/dist/tools/trigger-log-messages.js +60 -0
  33. package/dist/tools/trigger-long-running-operation.js +3 -3
  34. package/dist/tools/trigger-multi-step-elicitation.js +125 -0
  35. package/dist/tools/trigger-resource-update.js +52 -0
  36. package/dist/tools/trigger-sampling-request-async.js +79 -143
  37. package/dist/tools/trigger-sampling-request.js +51 -45
  38. package/dist/tools/trigger-url-elicitation.js +148 -111
  39. package/dist/transports/sse.js +11 -2
  40. package/dist/transports/stdio.js +42 -22
  41. package/dist/transports/streamableHttp.js +96 -10
  42. package/package.json +10 -3
@@ -29,18 +29,22 @@ src/everything
29
29
  ├── resources
30
30
  │ ├── index.ts
31
31
  │ ├── files.ts
32
+ │ ├── minted.ts
32
33
  │ ├── session.ts
33
34
  │ ├── subscriptions.ts
34
35
  │ └── templates.ts
35
36
  ├── server
36
37
  │ ├── index.ts
38
+ │ ├── context.ts
37
39
  │ ├── logging.ts
38
- │ └── roots.ts
40
+ │ ├── roots.ts
41
+ │ └── tasks.ts
39
42
  ├── tools
40
43
  │ ├── index.ts
41
44
  │ ├── echo.ts
42
45
  │ ├── get-annotated-message.ts
43
46
  │ ├── get-env.ts
47
+ │ ├── get-header-params.ts
44
48
  │ ├── get-resource-links.ts
45
49
  │ ├── get-resource-reference.ts
46
50
  │ ├── get-roots-list.ts
@@ -51,11 +55,15 @@ src/everything
51
55
  │ ├── simulate-research-query.ts
52
56
  │ ├── toggle-simulated-logging.ts
53
57
  │ ├── toggle-subscriber-updates.ts
54
- │ ├── trigger-elicitation-request.ts
55
58
  │ ├── trigger-elicitation-request-async.ts
59
+ │ ├── trigger-elicitation-request.ts
60
+ │ ├── trigger-list-changed.ts
61
+ │ ├── trigger-log-messages.ts
56
62
  │ ├── trigger-long-running-operation.ts
57
- │ ├── trigger-sampling-request.ts
63
+ │ ├── trigger-multi-step-elicitation.ts
64
+ │ ├── trigger-resource-update.ts
58
65
  │ ├── trigger-sampling-request-async.ts
66
+ │ ├── trigger-sampling-request.ts
59
67
  │ └── trigger-url-elicitation.ts
60
68
  └── transports
61
69
  ├── in-memory-event-store.ts
@@ -82,7 +90,7 @@ src/everything
82
90
  - Package metadata and scripts:
83
91
  - `build`: TypeScript compile to `dist/`, copies `docs/` into `dist/` and marks the compiled entry scripts as executable.
84
92
  - `start:stdio`, `start:sse`, `start:streamableHttp`: Run built transports from `dist/`.
85
- - Declares dependencies on `@modelcontextprotocol/sdk`, `express`, `cors`, `zod`, etc.
93
+ - Declares dependencies on the TypeScript SDK v2 packages (`@modelcontextprotocol/server`, `@modelcontextprotocol/node`, `@modelcontextprotocol/server-legacy`), `express`, `cors`, `zod`, etc.
86
94
 
87
95
  ### `docs/`
88
96
 
@@ -117,64 +125,87 @@ src/everything
117
125
  ### `resources/`
118
126
 
119
127
  - `index.ts`
120
- - `registerResources(server)` orchestrator; delegates to resource factory/registration methods from individual resource files.
128
+ - `registerResources(server, context)` orchestrator; delegates to resource factory/registration methods from individual resource files, adding the minted-resource template on 2026-07-28.
121
129
  - `templates.ts`
122
130
  - Registers two dynamic, template‑driven resources using `ResourceTemplate`:
123
131
  - Text: `demo://resource/dynamic/text/{index}` (MIME: `text/plain`)
124
132
  - Blob: `demo://resource/dynamic/blob/{index}` (MIME: `application/octet-stream`, Base64 payload)
125
- - The `{index}` path variable must be a finite positive integer. Content is generated on demand with a timestamp.
133
+ - The `{index}` path variable must be a finite positive integer; any other is not found (`-32602`). Content is generated on demand with a timestamp.
126
134
  - Exposes helpers `textResource(uri, index)`, `textResourceUri(index)`, `blobResource(uri, index)`, and `blobResourceUri(index)` so other modules can construct and embed dynamic resources directly (e.g., from prompts).
127
135
  - `files.ts`
128
136
  - Registers static file-based resources for each file in the `docs/` folder.
129
137
  - URIs follow the pattern: `demo://resource/static/document/<filename>`.
130
138
  - Serves markdown files as `text/markdown`, `.txt` as `text/plain`, `.json` as `application/json`, others default to `text/plain`.
139
+ - Gives each a one-hour public cache hint for 2026-07-28 reads.
140
+ - `minted.ts`
141
+ - 2026-07-28: stores resources tools create under server-minted URIs (`demo://resource/minted/<id>/<name>`) for ten minutes, process-wide, and serves them through one template.
142
+ - `session.ts`
143
+ - 2025 era: registers resources tools create on the session's server instance (`demo://resource/session/<name>`).
144
+ - `subscriptions.ts`
145
+ - 2025 era: the `resources/subscribe` and `resources/unsubscribe` handlers, and the timed updates `toggle-subscriber-updates` drives.
131
146
 
132
147
  ### `server/`
133
148
 
134
149
  - `index.ts`
135
- - Server factory that creates an `McpServer` with declared capabilities, loads server instructions, and registers tools, prompts, and resources.
136
- - Sets resource subscription handlers via `setSubscriptionHandlers(server)`.
137
- - Exposes `{ server, cleanup }` to the chosen transport. Cleanup stops any running intervals in the server when the transport disconnects.
150
+ - Server factory that creates an `McpServer` for a protocol era (`createServer({ era, publish })`) with declared capabilities, cache hints and the `requestState` verifier, loads server instructions, and registers tools, prompts, and resources for that era.
151
+ - On the 2025 era, sets resource subscription handlers via `setSubscriptionHandlers(server, subscribed)` and registers the capability-gated tools after `initialize`.
152
+ - Exposes `{ server, cleanup }` to the chosen transport. Cleanup stops any running intervals in the server when the connection ends.
153
+ - `context.ts`
154
+ - The per-instance context features receive: the era, the change publisher, the 2025-era subscriptions and a cleanup registry.
138
155
  - `logging.ts`
139
- - Implements simulated logging. Periodically sends randomized log messages at various levels to the connected client session. Started/stopped on demand via a dedicated tool.
156
+ - Implements simulated logging (2025 era). Periodically sends randomized log messages at various levels to the connected client. Started/stopped on demand via a dedicated tool.
157
+ - `roots.ts`
158
+ - 2025 era: syncs the client's roots after `initialize` and on `roots/list_changed`, reporting each answer as a log message.
159
+ - `tasks.ts`
160
+ - 2026-07-28: the server side of the tasks extension (`tasks/get`, `tasks/update`, `tasks/cancel`) and the process-wide task store the task tools create tasks in.
140
161
 
141
162
  ### `tools/`
142
163
 
143
164
  - `index.ts`
144
- - `registerTools(server)` orchestrator; delegates to tool factory/registration methods in individual tool files.
165
+ - Registration orchestrators, by era: `registerTools(server, context)` (both), `registerLegacyTools` and `registerConditionalTools` (2025 era), `registerModernTools` (2026-07-28). Each delegates to the registration methods in individual tool files.
145
166
  - `echo.ts`
146
167
  - Registers an `echo` tool that takes a message and returns `Echo: {message}`.
147
168
  - `get-annotated-message.ts`
148
169
  - Registers a `get-annotated-message` tool which demonstrates content-level annotations. Emits a primary `text` message with content `annotations` (`priority`, `audience`) that vary by `messageType` (`"error" | "success" | "debug"`), and optionally includes an annotated `image` (tiny PNG) when `includeImage` is true. All tools in this server include tool-level annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`).
149
170
  - `get-env.ts`
150
171
  - Registers a `get-env` tool that returns the current process environment variables as formatted JSON text; useful for debugging configuration.
172
+ - `get-header-params.ts`
173
+ - Registers a `get-header-params` tool with JSON Schema 2020-12 input and output schemas whose `region` argument carries `x-mcp-header`; returns the argument and the `Mcp-Param-Region` header it arrived in.
151
174
  - `get-resource-links.ts`
152
175
  - Registers a `get-resource-links` tool that returns an intro `text` block followed by multiple `resource_link` items.
153
176
  - `get-resource-reference.ts`
154
177
  - Registers a `get-resource-reference` tool that returns a reference for a selected dynamic resource.
155
178
  - `get-roots-list.ts`
156
- - Registers a `get-roots-list` tool that returns the last list of roots sent by the client.
179
+ - Registers a `get-roots-list` tool that asks the client for its roots with a multi-round-trip request and lists them.
157
180
  - `gzip-file-as-resource.ts`
158
181
  - Registers a `gzip-file-as-resource` tool that fetches content from a URL or data URI, compresses it, and then either:
159
- - returns a `resource_link` to a session-scoped resource (default), or
160
- - returns an inline `resource` with the gzipped data. The resource will be still discoverable for the duration of the session via `resources/list`.
161
- - Uses `resources/session.ts` to register the gzipped blob as a per-session resource at a URI like `demo://resource/session/<name>` with `mimeType: application/gzip`.
182
+ - returns a `resource_link` (default) to a resource it can read later, or
183
+ - returns an inline `resource` with the gzipped data.
184
+ - The linked resource is a per-session resource at `demo://resource/session/<name>` (`resources/session.ts`) for a 2025-era client, and a minted one at `demo://resource/minted/<id>/<name>` (`resources/minted.ts`) for a 2026-07-28 client, with `mimeType: application/gzip`.
162
185
  - Environment controls:
163
186
  - `GZIP_MAX_FETCH_SIZE` (bytes, default 10 MiB)
164
187
  - `GZIP_MAX_FETCH_TIME_MILLIS` (ms, default 30000)
165
188
  - `GZIP_ALLOWED_DOMAINS` (comma-separated allowlist; empty means all domains allowed)
166
189
  - `simulate-research-query.ts`
167
- - Registers a `simulate-research-query` task-based tool that demonstrates the MCP Tasks feature (SEP-1686). Simulates a multi-stage research operation with progress updates. If the query is marked as ambiguous and the client supports elicitation, it pauses mid-execution to request clarification via `elicitation/create`. Uses `server.experimental.tasks.registerToolTask()` with `execution: { taskSupport: "required" }`.
190
+ - 2026-07-28: registers a `simulate-research-query` tool that runs as a task on the tasks extension, through four timed stages, pausing at `input_required` for a clarification on an ambiguous topic.
168
191
  - `trigger-elicitation-request.ts`
169
- - Registers a `trigger-elicitation-request` tool that sends an `elicitation/create` request to the client/LLM and returns the elicitation result.
170
- - `trigger-url-elicitation.ts`
171
- - Registers a `trigger-url-elicitation` tool that either sends an out-of-band URL-mode `elicitation/create` request (`mode: "url"`) including an `elicitationId` (request path) or throws `UrlElicitationRequiredError` (`-32042`) for client-handled URL elicitation (error path). On the error path the carried prerequisite elicitation points at a different URL than the failing one (`https://modelcontextprotocol.io`), and when the client satisfies it and retries the same call, the retry ignores `errorPath` and proceeds via the request path — so the client does not loop on the same error.
192
+ - Registers a `trigger-elicitation-request` tool that asks for a form with a multi-round-trip request and returns the elicitation result.
172
193
  - `trigger-elicitation-request-async.ts`
173
- - Registers a `trigger-elicitation-request-async` tool that demonstrates bidirectional MCP tasks for elicitation. Sends an elicitation request with task metadata, then polls the client's `tasks/get` endpoint for completion status before fetching the final result.
174
- - `trigger-sampling-request.ts`
175
- - Registers a `trigger-sampling-request` tool that sends a `sampling/createMessage` request to the client/LLM and returns the sampling result.
194
+ - 2026-07-28: registers a `trigger-elicitation-request-async` tool that runs as a task waiting in `input_required` for a form elicitation.
195
+ - `trigger-list-changed.ts`
196
+ - Registers a `trigger-list-changed` tool that publishes a tools, prompts or resources list change.
197
+ - `trigger-log-messages.ts`
198
+ - Registers a `trigger-log-messages` tool that sends one log message per level, filtered by the request's or session's log level.
199
+ - `trigger-multi-step-elicitation.ts`
200
+ - Registers a `trigger-multi-step-elicitation` tool that asks two questions in sequence, carrying the first answer in a signed `requestState`.
201
+ - `trigger-resource-update.ts`
202
+ - Registers a `trigger-resource-update` tool that publishes a `notifications/resources/updated` for a URI.
176
203
  - `trigger-sampling-request-async.ts`
177
- - Registers a `trigger-sampling-request-async` tool that demonstrates bidirectional MCP tasks for sampling. Sends a sampling request with task metadata, then polls the client's `tasks/get` endpoint for completion status before fetching the final result.
204
+ - 2026-07-28: registers a `trigger-sampling-request-async` tool that runs as a task waiting in `input_required` for a sampling request.
205
+ - `trigger-url-elicitation.ts`
206
+ - On 2026-07-28, registers a `trigger-url-elicitation` tool that returns its URL elicitation in-band (`input_required`). On the 2025 era, it either sends an out-of-band URL-mode `elicitation/create` request (`mode: "url"`) including an `elicitationId` (request path) or throws `UrlElicitationRequiredError` (`-32042`) for client-handled URL elicitation (error path). On the error path the carried prerequisite elicitation points at a different URL than the failing one (`https://modelcontextprotocol.io`), and when the client satisfies it and retries the same call, the retry ignores `errorPath` and proceeds via the request path — so the client does not loop on the same error.
207
+ - `trigger-sampling-request.ts`
208
+ - Registers a `trigger-sampling-request` tool that asks the client's LLM for a completion with a multi-round-trip request and returns the sampling result.
178
209
  - `get-structured-content.ts`
179
210
  - Registers a `get-structured-content` tool that demonstrates structuredContent block responses.
180
211
  - `get-sum.ts`
@@ -184,9 +215,9 @@ src/everything
184
215
  - `trigger-long-running-operation.ts`
185
216
  - Registers a `trigger-long-running-operation` tool that simulates a long-running task over a specified `duration` (seconds) and number of `steps`; emits `notifications/progress` updates when the client supplies a `progressToken`.
186
217
  - `toggle-simulated-logging.ts`
187
- - Registers a `toggle-simulated-logging` tool, which starts or stops simulated logging for the invoking session.
218
+ - 2025 era: registers a `toggle-simulated-logging` tool, which starts or stops simulated logging for the connection.
188
219
  - `toggle-subscriber-updates.ts`
189
- - Registers a `toggle-subscriber-updates` tool, which starts or stops simulated resource subscription update checks for the invoking session.
220
+ - 2025 era: registers a `toggle-subscriber-updates` tool, which starts or stops simulated resource subscription updates for the connection.
190
221
 
191
222
  ### `transports/`
192
223
 
@@ -196,17 +227,20 @@ src/everything
196
227
  - `listenOrExit(app, port, listeningMessage)`: binds an Express app to its port for both HTTP transports.
197
228
  - Prints the listening message only once the port is bound; on a bind failure (such as a port already in use) prints why and exits non-zero.
198
229
  - `stdio.ts`
199
- - Starts a `StdioServerTransport`, created the server via `createServer()`, and connects it.
200
- - Handles `SIGINT` to close cleanly and calls `cleanup()` to remove any live intervals.
230
+ - Serves `createServer({ era })` over a `StdioServerTransport` with the SDK's `serveStdio`, which picks the connection's era from the client's first message.
231
+ - Runs each instance's `cleanup()` when it closes, and handles `SIGINT` to close cleanly.
201
232
  - `sse.ts`
233
+ - Deprecated; 2025-era clients only. Warns on start.
202
234
  - Express server exposing:
203
235
  - `GET /sse` to establish an SSE connection per session.
204
236
  - `POST /message` for client messages.
205
237
  - Manages multiple connected clients via a transport map.
206
- - Starts an `SSEServerTransport`, created the server via `createServer()`, and connects it to a new transport.
238
+ - Starts an `SSEServerTransport` (from the frozen `@modelcontextprotocol/server-legacy/sse` bridge), created the server via `createServer()`, and connects it to a new transport.
207
239
  - On server disconnect, calls `cleanup()` to remove any live intervals.
208
240
  - `streamableHttp.ts`
209
- - Express server exposing a single `/mcp` endpoint for POST (JSON‑RPC), GET (SSE stream), and DELETE (session termination) using `StreamableHTTPServerTransport`.
241
+ - Express server exposing a single `/mcp` endpoint for both protocol eras.
242
+ - 2026-07-28: a session-less POST carrying the per-request envelope (classified by the SDK's `isLegacyRequest`) is served by `createMcpHandler`, a fresh server per request, publishing change notifications on the handler's bus.
243
+ - 2025 era: POST (JSON‑RPC), GET (SSE stream), and DELETE (session termination) using `NodeStreamableHTTPServerTransport` from `@modelcontextprotocol/node`.
210
244
  - Uses an `InMemoryEventStore` for resumable sessions and tracks transports by `sessionId`.
211
245
  - Answers a request for an unknown or ended `Mcp-Session-Id` with `404 Not Found`, and closes every open session on `SIGINT`.
212
246
  - Connects a fresh server instance on initialization POST and reuses the transport for subsequent requests.
@@ -8,10 +8,10 @@ import { z } from "zod";
8
8
  */
9
9
  export const registerArgumentsPrompt = (server) => {
10
10
  // Prompt arguments
11
- const promptArgsSchema = {
11
+ const promptArgsSchema = z.object({
12
12
  city: z.string().describe("Name of the city"),
13
13
  state: z.string().describe("Name of the state").optional(),
14
- };
14
+ });
15
15
  // Register the prompt
16
16
  server.registerPrompt("args-prompt", {
17
17
  title: "Arguments Prompt",
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
2
+ import { completable } from "@modelcontextprotocol/server";
3
3
  /**
4
4
  * Register a prompt with completable arguments
5
5
  * - Two required arguments, both with completion handlers
@@ -10,7 +10,7 @@ import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
10
10
  */
11
11
  export const registerPromptWithCompletions = (server) => {
12
12
  // Prompt arguments
13
- const promptArgsSchema = {
13
+ const promptArgsSchema = z.object({
14
14
  department: completable(z.string().describe("Choose the department."), (value) => {
15
15
  return ["Engineering", "Sales", "Marketing", "Support"].filter((d) => d.startsWith(value));
16
16
  }),
@@ -32,7 +32,7 @@ export const registerPromptWithCompletions = (server) => {
32
32
  }
33
33
  return [];
34
34
  }),
35
- };
35
+ });
36
36
  // Register the prompt
37
37
  server.registerPrompt("completable-prompt", {
38
38
  title: "Team Management",
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import { resourceTypeCompleter, resourceIdForPromptCompleter, } from "../resources/templates.js";
2
3
  import { textResource, textResourceUri, blobResourceUri, blobResource, RESOURCE_TYPE_BLOB, RESOURCE_TYPE_TEXT, RESOURCE_TYPES, } from "../resources/templates.js";
3
4
  /**
@@ -9,10 +10,10 @@ import { textResource, textResourceUri, blobResourceUri, blobResource, RESOURCE_
9
10
  */
10
11
  export const registerEmbeddedResourcePrompt = (server) => {
11
12
  // Prompt arguments
12
- const promptArgsSchema = {
13
+ const promptArgsSchema = z.object({
13
14
  resourceType: resourceTypeCompleter,
14
15
  resourceId: resourceIdForPromptCompleter,
15
- };
16
+ });
16
17
  // Register the prompt
17
18
  server.registerPrompt("resource-prompt", {
18
19
  title: "Resource Prompt",
@@ -1,6 +1,11 @@
1
1
  import { dirname, join } from "path";
2
2
  import { fileURLToPath } from "url";
3
3
  import { readdirSync, readFileSync, statSync } from "fs";
4
+ /** How long a client or shared cache may keep a static document. */
5
+ export const STATIC_DOCUMENT_CACHE_HINT = {
6
+ ttlMs: 60 * 60_000,
7
+ cacheScope: "public",
8
+ };
4
9
  /**
5
10
  * Register static file resources
6
11
  * - Each file in src/everything/docs is exposed as an individual static resource
@@ -41,7 +46,10 @@ export const registerFileResources = (server) => {
41
46
  const mimeType = getMimeType(name);
42
47
  const description = `Static document file exposed from /docs: ${name}`;
43
48
  // Register file resource
44
- server.registerResource(name, uri, { mimeType, description }, async (uri) => {
49
+ server.registerResource(name, uri,
50
+ // A static document changes only when the server is upgraded, so any
51
+ // cache may keep it for an hour (2026-07-28 clients only; #4852).
52
+ { mimeType, description, cacheHint: STATIC_DOCUMENT_CACHE_HINT }, async (uri) => {
45
53
  const text = readFileSafe(fullPath);
46
54
  return {
47
55
  contents: [
@@ -1,15 +1,20 @@
1
1
  import { registerResourceTemplates } from "./templates.js";
2
2
  import { registerFileResources } from "./files.js";
3
+ import { registerMintedResources } from "./minted.js";
3
4
  import { fileURLToPath } from "url";
4
5
  import { dirname, join } from "path";
5
6
  import { readFileSync } from "fs";
6
7
  /**
7
- * Register the resources with the MCP server.
8
+ * Register the resources with the MCP server. A 2026-07-28 server also serves
9
+ * the resources tools mint for later reading (see minted.ts).
8
10
  * @param server
11
+ * @param context
9
12
  */
10
- export const registerResources = (server) => {
13
+ export const registerResources = (server, context) => {
11
14
  registerResourceTemplates(server);
12
15
  registerFileResources(server);
16
+ if (context.era === "modern")
17
+ registerMintedResources(server);
13
18
  };
14
19
  /**
15
20
  * Reads the server instructions from the corresponding markdown file.
@@ -0,0 +1,119 @@
1
+ // Resources a tool creates for a 2026-07-28 client to read later, served from
2
+ // handles the server mints (#4852).
3
+ //
4
+ // On a 2025-era connection, `gzip-file-as-resource` registers the resource it
5
+ // creates on the server instance serving the client's connection or session
6
+ // (resources/session.ts), and the resource lasts as long as that instance.
7
+ // The 2026-07-28 revision has no sessions, and on its HTTP path every request
8
+ // is served by a fresh instance, so a resource registered on one would be gone
9
+ // before the client could read it. Instead the resource is stored here, under a
10
+ // URI that embeds a random id the server mints, and every 2026-07-28 instance
11
+ // serves the store through one resource template. The id is the handle: a
12
+ // client can read a minted resource only if it was given the URI. Each one
13
+ // expires after ten minutes; an expired or unknown URI reads as not found
14
+ // (-32602).
15
+ import { randomUUID } from "node:crypto";
16
+ import { ResourceNotFoundError, ResourceTemplate, } from "@modelcontextprotocol/server";
17
+ /** How long a minted resource stays readable, in milliseconds. */
18
+ export const MINTED_RESOURCE_TTL_MS = 10 * 60_000;
19
+ /**
20
+ * The most minted resources the process keeps, and the most bytes of content
21
+ * across them. Each one may be as large as the gzip tool's fetch limit, so
22
+ * without a budget a burst of calls could exhaust memory before the TTL frees
23
+ * anything; past it, the oldest are dropped first.
24
+ */
25
+ export const MAX_MINTED_RESOURCES = 100;
26
+ export const MAX_MINTED_BYTES = 64 * 1024 * 1024;
27
+ /** The URI template every minted resource matches. */
28
+ const mintedUriTemplate = "demo://resource/minted/{id}/{name}";
29
+ /** Every live minted resource, by URI, across every server instance. */
30
+ const minted = new Map();
31
+ /** Drop every minted resource past its expiry. */
32
+ function sweep(now) {
33
+ for (const [uri, resource] of minted) {
34
+ if (resource.expiresAt <= now)
35
+ minted.delete(uri);
36
+ }
37
+ }
38
+ /**
39
+ * Drop the oldest minted resources (the map keeps insertion order) until one
40
+ * more of `bytes` fits both budgets.
41
+ */
42
+ function makeRoom(bytes) {
43
+ let total = bytes;
44
+ for (const [uri, resource] of minted)
45
+ total += sizeOf(uri, resource);
46
+ for (const [uri, resource] of minted) {
47
+ if (minted.size < MAX_MINTED_RESOURCES && total <= MAX_MINTED_BYTES)
48
+ break;
49
+ minted.delete(uri);
50
+ total -= sizeOf(uri, resource);
51
+ }
52
+ }
53
+ /** What a stored resource counts against the budget: everything it keeps. */
54
+ function sizeOf(uri, resource) {
55
+ return uri.length + resource.name.length + resource.blob.length;
56
+ }
57
+ /**
58
+ * Store a blob resource under a freshly minted URI, and return a link to it.
59
+ * Throws for a blob larger than `MAX_MINTED_BYTES`.
60
+ *
61
+ * @param name - The resource's name, the last segment of its URI.
62
+ * @param mimeType - Its MIME type.
63
+ * @param blob - Its content, base64-encoded.
64
+ */
65
+ export function mintBlobResource(name, mimeType, blob) {
66
+ // One resource larger than the whole budget is refused outright, rather
67
+ // than evicting everything else and still exceeding the budget.
68
+ const uri = `demo://resource/minted/${randomUUID()}/${encodeURIComponent(name)}`;
69
+ const size = uri.length + name.length + blob.length;
70
+ if (size > MAX_MINTED_BYTES) {
71
+ throw new Error(`Cannot keep ${name} for later reading: its ${size} bytes exceed the ${MAX_MINTED_BYTES}-byte limit for minted resources`);
72
+ }
73
+ const now = Date.now();
74
+ sweep(now);
75
+ makeRoom(size);
76
+ minted.set(uri, {
77
+ name,
78
+ mimeType,
79
+ blob,
80
+ expiresAt: now + MINTED_RESOURCE_TTL_MS,
81
+ });
82
+ return {
83
+ type: "resource_link",
84
+ uri,
85
+ name,
86
+ mimeType,
87
+ description: `Created by a tool call; readable for ${MINTED_RESOURCE_TTL_MS / 60_000} minutes at this URI`,
88
+ };
89
+ }
90
+ /**
91
+ * Register the template that serves minted resources, on a 2026-07-28
92
+ * server. It lists nothing: a minted resource is reached by the URI a tool
93
+ * returned.
94
+ *
95
+ * @param server - The 2026-07-28 server to serve them on.
96
+ */
97
+ export function registerMintedResources(server) {
98
+ server.registerResource("Minted Resource", new ResourceTemplate(mintedUriTemplate, { list: undefined }), {
99
+ description: "A resource a tool created for this client, such as gzip-file-as-resource's output. Readable for ten minutes at the URI the tool returned.",
100
+ }, async (uri) => {
101
+ sweep(Date.now());
102
+ const resource = minted.get(uri.toString());
103
+ if (!resource)
104
+ throw new ResourceNotFoundError(uri.toString());
105
+ return {
106
+ contents: [
107
+ {
108
+ uri: uri.toString(),
109
+ mimeType: resource.mimeType,
110
+ blob: resource.blob,
111
+ },
112
+ ],
113
+ };
114
+ });
115
+ }
116
+ /** Forget every minted resource. For tests. */
117
+ export function clearMintedResources() {
118
+ minted.clear();
119
+ }
@@ -1,144 +1,66 @@
1
- import { SubscribeRequestSchema, UnsubscribeRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
2
- // Track subscriber session id lists by URI
3
- const subscriptions = new Map();
4
- // Interval to send notifications to subscribers
5
- const subsUpdateIntervals = new Map();
1
+ // 2025-era per-resource subscriptions, and the simulated updates
2
+ // `toggle-subscriber-updates` sends for them.
3
+ //
4
+ // `resources/subscribe` and `resources/unsubscribe` exist only on the 2025
5
+ // protocol era. A 2026-07-28 client names the resources it wants updates for
6
+ // in its `subscriptions/listen` filter instead, and the serving entry
7
+ // delivers each `notifications/resources/updated` only to a stream that asked
8
+ // for it (`trigger-resource-update` shows that). The subscribed set belongs to
9
+ // the server instance serving the client's connection or session, so no
10
+ // session map is needed (#4852).
6
11
  /**
7
- * Sets up the subscription and unsubscription handlers for the provided server.
12
+ * Install the `resources/subscribe` and `resources/unsubscribe` handlers on a
13
+ * 2025-era server, recording each subscription in `subscribed`.
8
14
  *
9
- * The function defines two request handlers:
10
- * 1. A `Subscribe` handler that allows clients to subscribe to specific resource URIs.
11
- * 2. An `Unsubscribe` handler that allows clients to unsubscribe from specific resource URIs.
12
- *
13
- * The `Subscribe` handler performs the following actions:
14
- * - Extracts the URI and session ID from the request.
15
- * - Logs a message acknowledging the subscription request.
16
- * - Updates the internal tracking of subscribers for the given URI.
17
- *
18
- * The `Unsubscribe` handler performs the following actions:
19
- * - Extracts the URI and session ID from the request.
20
- * - Logs a message acknowledging the unsubscription request.
21
- * - Removes the subscriber for the specified URI.
15
+ * Each handler acknowledges the request with an info-level log message, then
16
+ * adds the URI to, or removes it from, the set.
22
17
  *
23
18
  * @param {McpServer} server - The server instance to which subscription handlers will be attached.
19
+ * @param {Set<string>} subscribed - The URIs this server's client has subscribed to.
24
20
  */
25
- export const setSubscriptionHandlers = (server) => {
26
- // Set the subscription handler
27
- server.server.setRequestHandler(SubscribeRequestSchema, async (request, extra) => {
28
- // Get the URI to subscribe to
21
+ export const setSubscriptionHandlers = (server, subscribed) => {
22
+ server.server.setRequestHandler("resources/subscribe", async (request) => {
29
23
  const { uri } = request.params;
30
- // Get the session id (can be undefined for stdio)
31
- const sessionId = extra.sessionId;
32
- // Acknowledge the subscribe request
33
24
  await server.sendLoggingMessage({
34
25
  level: "info",
35
- data: `Received Subscribe Resource request for URI: ${uri} ${sessionId ? `from session ${sessionId}` : ""}`,
36
- }, sessionId);
37
- // Get the subscribers for this URI
38
- const subscribers = subscriptions.has(uri)
39
- ? subscriptions.get(uri)
40
- : new Set();
41
- subscribers.add(sessionId);
42
- subscriptions.set(uri, subscribers);
26
+ data: `Received Subscribe Resource request for URI: ${uri}`,
27
+ }, server.server.transport?.sessionId);
28
+ subscribed.add(uri);
43
29
  return {};
44
30
  });
45
- // Set the unsubscription handler
46
- server.server.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => {
47
- // Get the URI to subscribe to
31
+ server.server.setRequestHandler("resources/unsubscribe", async (request) => {
48
32
  const { uri } = request.params;
49
- // Get the session id (can be undefined for stdio)
50
- const sessionId = extra.sessionId;
51
- // Acknowledge the subscribe request
52
33
  await server.sendLoggingMessage({
53
34
  level: "info",
54
- data: `Received Unsubscribe Resource request: ${uri} ${sessionId ? `from session ${sessionId}` : ""}`,
55
- }, sessionId);
56
- // Remove the subscriber
57
- if (subscriptions.has(uri)) {
58
- const subscribers = subscriptions.get(uri);
59
- if (subscribers.has(sessionId))
60
- subscribers.delete(sessionId);
61
- }
35
+ data: `Received Unsubscribe Resource request: ${uri}`,
36
+ }, server.server.transport?.sessionId);
37
+ subscribed.delete(uri);
62
38
  return {};
63
39
  });
64
40
  };
65
41
  /**
66
- * Sends simulated resource update notifications to the subscribed client.
42
+ * Start sending `server`'s client a `notifications/resources/updated` for each
43
+ * resource it has subscribed to, now and then every five seconds.
67
44
  *
68
- * Iterates the URIs in `subscriptions` and emits a
69
- * `notifications/resources/updated` notification for each URI the given
70
- * sessionId is subscribed to.
71
- *
72
- * @param {McpServer} server - The server instance used to send notifications.
73
- * @param {string | undefined} sessionId - The session ID of the client to check for subscriptions.
74
- * @returns {Promise<void>} Resolves once all applicable notifications are sent.
45
+ * @param {McpServer} server - The server whose client receives the updates.
46
+ * @param {Set<string>} subscribed - The URIs that client has subscribed to.
47
+ * @returns {() => void} Stops the updates.
75
48
  */
76
- const sendSimulatedResourceUpdates = async (server, sessionId) => {
77
- // Search all URIs for ones this client is subscribed to
78
- for (const uri of subscriptions.keys()) {
79
- const subscribers = subscriptions.get(uri);
80
- // If this client is subscribed, send the notification
81
- if (subscribers.has(sessionId)) {
82
- await server.server.notification({
83
- method: "notifications/resources/updated",
84
- params: { uri },
85
- });
49
+ export const beginSimulatedResourceUpdates = (server, subscribed) => {
50
+ // Fire-and-forget: this runs on a timer with no caller to await it. A send
51
+ // that fails (e.g. the transport closed before the updates were stopped) is
52
+ // logged rather than left to become an unhandled rejection.
53
+ const send = async () => {
54
+ try {
55
+ for (const uri of [...subscribed]) {
56
+ await server.server.sendResourceUpdated({ uri });
57
+ }
86
58
  }
87
- }
88
- };
89
- /**
90
- * Starts the process of simulating resource updates and sending server notifications
91
- * to the client for the resources they are subscribed to. If the update interval is
92
- * already active, invoking this function will not start another interval.
93
- *
94
- * @param server
95
- * @param sessionId
96
- */
97
- export const beginSimulatedResourceUpdates = (server, sessionId) => {
98
- if (!subsUpdateIntervals.has(sessionId)) {
99
- // Send once immediately, then every 5 seconds. Fire-and-forget: this
100
- // function is synchronous by contract (its callers start a background
101
- // simulation), so neither send can be awaited. A send that fails (e.g. the
102
- // transport closed before the updates were stopped) is logged rather than
103
- // left to become an unhandled rejection.
104
- const send = () => sendSimulatedResourceUpdates(server, sessionId).catch((error) => console.error("Simulated resource update failed:", error));
105
- void send();
106
- // Set the interval to send later resource update notifications to this client
107
- subsUpdateIntervals.set(sessionId, setInterval(() => void send(), 5000));
108
- }
109
- };
110
- /**
111
- * Stops simulated resource updates for a given session.
112
- *
113
- * This function halts any active intervals associated with the provided session ID
114
- * and removes the session's corresponding entries from resource management collections.
115
- * Session ID can be undefined for stdio.
116
- *
117
- * @param {string} [sessionId]
118
- */
119
- export const stopSimulatedResourceUpdates = (sessionId) => {
120
- // Remove active intervals
121
- if (subsUpdateIntervals.has(sessionId)) {
122
- const subsUpdateInterval = subsUpdateIntervals.get(sessionId);
123
- clearInterval(subsUpdateInterval);
124
- subsUpdateIntervals.delete(sessionId);
125
- }
126
- };
127
- /**
128
- * Removes a session from every URI's subscriber set, dropping any URI entry
129
- * that ends up with no remaining subscribers.
130
- *
131
- * A session that disconnects without explicitly unsubscribing otherwise stays
132
- * in `subscriptions` for the life of the process. Call this from the
133
- * transport's `cleanup(sessionId)` when a session ends.
134
- *
135
- * @param {string} [sessionId]
136
- */
137
- export const removeSubscriber = (sessionId) => {
138
- for (const [uri, subscribers] of subscriptions) {
139
- subscribers.delete(sessionId);
140
- if (subscribers.size === 0) {
141
- subscriptions.delete(uri);
59
+ catch (error) {
60
+ console.error("Simulated resource update failed:", error);
142
61
  }
143
- }
62
+ };
63
+ void send();
64
+ const interval = setInterval(() => void send(), 5000);
65
+ return () => clearInterval(interval);
144
66
  };
@@ -1,6 +1,5 @@
1
1
  import { z } from "zod";
2
- import { ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
2
+ import { ResourceNotFoundError, ResourceTemplate, completable, } from "@modelcontextprotocol/server";
4
3
  // Resource types
5
4
  export const RESOURCE_TYPE_TEXT = "Text";
6
5
  export const RESOURCE_TYPE_BLOB = "Blob";
@@ -112,7 +111,9 @@ export const blobResourceUri = (resourceId) => new URL(`${blobUriBase}/${resourc
112
111
  * @param {URL} uri - The URI of the resource (used in the error message).
113
112
  * @param {Record<string, unknown>} variables - Context variables including resourceId.
114
113
  * @returns {number} The parsed and validated resource identifier as a positive integer.
115
- * @throws {Error} If the resourceId is not a finite positive integer.
114
+ * @throws {ResourceNotFoundError} If the resourceId is not a finite positive
115
+ * integer: no such resource exists, which the protocol reports as -32602
116
+ * with the URI in the error's data (#4852).
116
117
  */
117
118
  const parseResourceId = (uri, variables) => {
118
119
  const idxStr = String(variables.resourceId ?? "");
@@ -120,7 +121,7 @@ const parseResourceId = (uri, variables) => {
120
121
  if (Number.isFinite(idx) && Number.isInteger(idx) && idx > 0) {
121
122
  return idx;
122
123
  }
123
- throw new Error(`Unknown resource: ${uri.toString()}`);
124
+ throw new ResourceNotFoundError(uri.toString());
124
125
  };
125
126
  /**
126
127
  * Register resource templates with the MCP server.