@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
@@ -1,5 +1,18 @@
1
+ // The `trigger-url-elicitation` tool: directs the user to a URL in the
2
+ // browser (URL-mode elicitation) and reports how the flow ended.
3
+ //
4
+ // The two protocol eras do this differently, so the tool branches on the era
5
+ // its server instance serves (#4852):
6
+ // - 2025-era: the server sends an `elicitation/create` request carrying an
7
+ // `elicitationId` (the request path), or throws a
8
+ // `UrlElicitationRequiredError` (-32042) that the client handles before it
9
+ // retries (the error path).
10
+ // - 2026-07-28: there is no server-to-client request and no -32042 error. The
11
+ // tool returns `input_required` carrying the URL elicitation, and the client
12
+ // retries with the user's answer. The in-band request has no
13
+ // `elicitationId`, and `errorPath` changes nothing.
1
14
  import { randomUUID } from "node:crypto";
2
- import { ElicitResultSchema, UrlElicitationRequiredError, } from "@modelcontextprotocol/sdk/types.js";
15
+ import { inputRequired, inputResponse, UrlElicitationRequiredError, } from "@modelcontextprotocol/server";
3
16
  import { z } from "zod";
4
17
  // Tool input schema
5
18
  const TriggerUrlElicitationSchema = z.object({
@@ -11,7 +24,8 @@ const TriggerUrlElicitationSchema = z.object({
11
24
  elicitationId: z
12
25
  .string()
13
26
  .optional()
14
- .describe("Optional explicit elicitation ID. Defaults to a random UUID."),
27
+ .describe("Optional explicit elicitation ID. Defaults to a random UUID. 2025-era clients only: the " +
28
+ "2026-07-28 in-band request carries no elicitation ID."),
15
29
  errorPath: z
16
30
  .boolean()
17
31
  .default(false)
@@ -20,7 +34,9 @@ const TriggerUrlElicitationSchema = z.object({
20
34
  "When true, throws a UrlElicitationRequiredError (MCP error code -32042) so the client handles " +
21
35
  "the URL elicitation via the error path rather than waiting for a response. " +
22
36
  "To clear the error, satisfy the prerequisite and retry this call with the same arguments; the " +
23
- "retry ignores errorPath and proceeds, so the client does not loop on the same error."),
37
+ "retry ignores errorPath and proceeds, so the client does not loop on the same error. " +
38
+ "2025-era clients only: protocol version 2026-07-28 has no -32042 error, so there both " +
39
+ "settings use the in-band input_required flow."),
24
40
  });
25
41
  // Tool configuration
26
42
  const name = "trigger-url-elicitation";
@@ -29,7 +45,8 @@ const config = {
29
45
  description: "Trigger a URL elicitation so the client can direct the user to a browser flow. " +
30
46
  "Supports two mechanisms: the request path (elicitation/create, default) which awaits the user's " +
31
47
  "response, and the error path (UrlElicitationRequiredError, -32042) which signals the client " +
32
- "to handle URL elicitation via the error response. Set errorPath=true to use the error path.",
48
+ "to handle URL elicitation via the error response. Set errorPath=true to use the error path. " +
49
+ "On protocol version 2026-07-28 the server instead returns the URL elicitation in-band (input_required).",
33
50
  inputSchema: TriggerUrlElicitationSchema,
34
51
  annotations: {
35
52
  readOnlyHint: false,
@@ -38,36 +55,17 @@ const config = {
38
55
  openWorldHint: true,
39
56
  },
40
57
  };
41
- /**
42
- * Tracks requests for which an error-path prerequisite has already been issued,
43
- * keyed by the stable inputs a client resends when it retries the original tool
44
- * call (session + URL + caller-supplied elicitationId).
45
- *
46
- * When the client satisfies the prerequisite and retries the same call, the
47
- * matching entry lets us recognize the retry, ignore `errorPath`, and proceed
48
- * via the request path instead of re-throwing `UrlElicitationRequiredError` —
49
- * which would otherwise loop forever (throw -> client satisfies prerequisite ->
50
- * retry -> throw -> ...).
51
- *
52
- * Demo simplification: entries are only removed on a recognized retry, so a
53
- * client that triggers the error path and never retries leaves its key behind.
54
- * That is acceptable for this reference server; a production implementation
55
- * serving many long-lived sessions should evict entries (e.g. a
56
- * `Map<string, timestamp>` with TTL-based cleanup).
57
- */
58
- const issuedErrorPathElicitations = new Set();
59
- /**
60
- * Test-only helper to reset the module-level error-path state between cases.
61
- * Not part of the tool's public behavior.
62
- */
63
- export const __resetIssuedErrorPathElicitations = () => issuedErrorPathElicitations.clear();
64
58
  /**
65
59
  * Registers the 'trigger-url-elicitation' tool.
66
60
  *
67
- * This tool only registers when the client advertises URL-mode elicitation
68
- * capability (clientCapabilities.elicitation.url).
61
+ * The tool needs a client that supports URL-mode elicitation: on a 2025-era
62
+ * connection the server factory registers it only for a client that declared
63
+ * `elicitation.url`, and on 2026-07-28 the SDK refuses the embedded request
64
+ * (-32021) of a client whose request did not declare it.
69
65
  *
70
- * Depending on the `errorPath` argument it either:
66
+ * On 2026-07-28 it returns the URL elicitation in-band and reports the answer
67
+ * on the retry. On a 2025-era connection, depending on the `errorPath`
68
+ * argument, it either:
71
69
  * - Sends an `elicitation/create` request and awaits the result (request path), or
72
70
  * - Throws a `UrlElicitationRequiredError` (MCP error -32042) carrying a
73
71
  * prerequisite elicitation for the client to handle (error path). When the
@@ -76,94 +74,133 @@ export const __resetIssuedErrorPathElicitations = () => issuedErrorPathElicitati
76
74
  * not loop on the same error.
77
75
  *
78
76
  * @param {McpServer} server - The McpServer instance where the tool will be registered.
77
+ * @param {ServerContext} context - The protocol era the instance serves.
79
78
  */
80
- export const registerTriggerUrlElicitationTool = (server) => {
81
- const clientCapabilities = server.server.getClientCapabilities() || {};
82
- const clientElicitationCapabilities = clientCapabilities.elicitation;
83
- const clientSupportsUrlElicitation = clientElicitationCapabilities?.url !== undefined;
84
- if (clientSupportsUrlElicitation) {
85
- server.registerTool(name, config, async (args, extra) => {
86
- const { url, message, elicitationId: requestedElicitationId, errorPath, } = args;
87
- const elicitationId = requestedElicitationId ?? randomUUID();
88
- const sessionId = extra.sessionId ?? "default";
89
- // Key the one-shot error-path marker on inputs the client resends
90
- // verbatim when it retries the original tool call. A real client retries
91
- // with the *same* arguments and does NOT echo the prerequisite's
92
- // (server-generated) elicitationId, so we must key on stable inputs:
93
- // the session, the requested URL, and the caller-supplied elicitationId
94
- // (if any). Keying on the resolved/random elicitationId would change on
95
- // every call and never match, re-throwing the prerequisite forever.
96
- const errorPathKey = `${sessionId}\u0000${url}\u0000${requestedElicitationId ?? ""}`;
97
- const elicitationParams = {
98
- mode: "url",
99
- url,
100
- message,
101
- elicitationId,
102
- };
103
- // Error path: signal the client via UrlElicitationRequiredError (-32042)
104
- // so it handles a prerequisite URL elicitation before this request can
105
- // proceed. Two things keep the client from looping forever:
106
- //
107
- // 1. The prerequisite points at a *different* URL than the one that
108
- // failed. Reusing the original `url` would make the client complete
109
- // the prerequisite, retry, and hit the same -32042 error endlessly.
110
- // 2. We remember that we issued a prerequisite for this request. When
111
- // the client satisfies it and retries the same call, we recognize
112
- // the retry, *ignore* errorPath, and fall through to the request
113
- // path. Without this, the retry would re-enter the error path and
114
- // re-request the prerequisite URL — another loop.
115
- if (errorPath) {
116
- if (issuedErrorPathElicitations.has(errorPathKey)) {
117
- // Retry of a satisfied prerequisite: clear the one-shot marker and
118
- // ignore errorPath, falling through to the request path below.
119
- issuedErrorPathElicitations.delete(errorPathKey);
120
- }
121
- else {
122
- // Originating call: record that we issued a prerequisite for this
123
- // request, then signal the client via -32042.
124
- issuedErrorPathElicitations.add(errorPathKey);
125
- const prerequisiteElicitation = {
126
- mode: "url",
127
- url: "https://modelcontextprotocol.io",
128
- message: "Open this link to satisfy the prerequisite, then retry the request.",
129
- elicitationId: randomUUID(),
130
- };
131
- throw new UrlElicitationRequiredError([prerequisiteElicitation], "This request requires browser-based authorization.");
132
- }
133
- }
134
- // Request path: send elicitation/create and await the user's response
135
- const elicitationResult = await extra.sendRequest({
136
- method: "elicitation/create",
137
- params: elicitationParams,
138
- }, ElicitResultSchema, { timeout: 10 * 60 * 1000 /* 10 minutes */ });
139
- // Handle different response actions
140
- const content = [];
141
- if (elicitationResult.action === "accept") {
142
- content.push({
143
- type: "text",
144
- text: `✅ User completed the URL elicitation flow.\n` +
145
- `Elicitation ID: ${elicitationId}\n` +
146
- `URL: ${url}`,
79
+ export const registerTriggerUrlElicitationTool = (server, context) => {
80
+ if (context.era === "modern") {
81
+ server.registerTool(name, config, async (args, ctx) => {
82
+ const { url, message } = args;
83
+ const answer = inputResponse(ctx.mcpReq.inputResponses, "url");
84
+ // First round: direct the user to the URL
85
+ if (answer.kind !== "elicit") {
86
+ return inputRequired({
87
+ inputRequests: { url: inputRequired.elicitUrl({ message, url }) },
147
88
  });
148
89
  }
149
- else if (elicitationResult.action === "decline") {
150
- content.push({
151
- type: "text",
152
- text: `❌ User declined to open the URL (Elicitation ID: ${elicitationId}).`,
153
- });
90
+ const text = answer.action === "accept"
91
+ ? `✅ User completed the URL elicitation flow.\nURL: ${url}`
92
+ : answer.action === "decline"
93
+ ? "❌ User declined to open the URL."
94
+ : "⚠️ User cancelled the URL elicitation.";
95
+ return {
96
+ content: [
97
+ { type: "text", text },
98
+ {
99
+ type: "text",
100
+ text: `\nRaw result: ${JSON.stringify({ action: answer.action }, null, 2)}`,
101
+ },
102
+ ],
103
+ };
104
+ });
105
+ return;
106
+ }
107
+ /**
108
+ * Requests for which an error-path prerequisite has already been issued on
109
+ * this connection, keyed by the stable inputs a client resends when it
110
+ * retries the original tool call (URL + caller-supplied elicitationId).
111
+ *
112
+ * When the client satisfies the prerequisite and retries the same call, the
113
+ * matching entry lets us recognize the retry, ignore `errorPath`, and
114
+ * proceed via the request path instead of re-throwing
115
+ * `UrlElicitationRequiredError` — which would otherwise loop forever (throw
116
+ * -> client satisfies prerequisite -> retry -> throw -> ...).
117
+ *
118
+ * The set belongs to this server instance, which serves one connection or
119
+ * session, so it goes away with it (#4852). Entries are removed on a
120
+ * recognized retry; a client that never retries leaves its key until it
121
+ * disconnects.
122
+ */
123
+ const issuedErrorPathElicitations = new Set();
124
+ server.registerTool(name, config, async (args, ctx) => {
125
+ const { url, message, elicitationId: requestedElicitationId, errorPath, } = args;
126
+ const elicitationId = requestedElicitationId ?? randomUUID();
127
+ // Key the one-shot error-path marker on inputs the client resends
128
+ // verbatim when it retries the original tool call. A real client retries
129
+ // with the *same* arguments and does NOT echo the prerequisite's
130
+ // (server-generated) elicitationId, so we must key on stable inputs:
131
+ // the requested URL and the caller-supplied elicitationId (if any).
132
+ // Keying on the resolved/random elicitationId would change on every
133
+ // call and never match, re-throwing the prerequisite forever.
134
+ const errorPathKey = `${url}\u0000${requestedElicitationId ?? ""}`;
135
+ const elicitationParams = {
136
+ mode: "url",
137
+ url,
138
+ message,
139
+ elicitationId,
140
+ };
141
+ // Error path: signal the client via UrlElicitationRequiredError (-32042)
142
+ // so it handles a prerequisite URL elicitation before this request can
143
+ // proceed. Two things keep the client from looping forever:
144
+ //
145
+ // 1. The prerequisite points at a *different* URL than the one that
146
+ // failed. Reusing the original `url` would make the client complete
147
+ // the prerequisite, retry, and hit the same -32042 error endlessly.
148
+ // 2. We remember that we issued a prerequisite for this request. When
149
+ // the client satisfies it and retries the same call, we recognize
150
+ // the retry, *ignore* errorPath, and fall through to the request
151
+ // path. Without this, the retry would re-enter the error path and
152
+ // re-request the prerequisite URL — another loop.
153
+ if (errorPath) {
154
+ if (issuedErrorPathElicitations.has(errorPathKey)) {
155
+ // Retry of a satisfied prerequisite: clear the one-shot marker and
156
+ // ignore errorPath, falling through to the request path below.
157
+ issuedErrorPathElicitations.delete(errorPathKey);
154
158
  }
155
- else if (elicitationResult.action === "cancel") {
156
- content.push({
157
- type: "text",
158
- text: `⚠️ User cancelled the URL elicitation (Elicitation ID: ${elicitationId}).`,
159
- });
159
+ else {
160
+ // Originating call: record that we issued a prerequisite for this
161
+ // request, then signal the client via -32042.
162
+ issuedErrorPathElicitations.add(errorPathKey);
163
+ const prerequisiteElicitation = {
164
+ mode: "url",
165
+ url: "https://modelcontextprotocol.io",
166
+ message: "Open this link to satisfy the prerequisite, then retry the request.",
167
+ elicitationId: randomUUID(),
168
+ };
169
+ throw new UrlElicitationRequiredError([prerequisiteElicitation], "This request requires browser-based authorization.");
160
170
  }
161
- // Include raw result for debugging
171
+ }
172
+ // Request path: send elicitation/create and await the user's response
173
+ const elicitationResult = await ctx.mcpReq.send({
174
+ method: "elicitation/create",
175
+ params: elicitationParams,
176
+ }, { timeout: 10 * 60 * 1000 /* 10 minutes */ });
177
+ // Handle different response actions
178
+ const content = [];
179
+ if (elicitationResult.action === "accept") {
180
+ content.push({
181
+ type: "text",
182
+ text: `✅ User completed the URL elicitation flow.\n` +
183
+ `Elicitation ID: ${elicitationId}\n` +
184
+ `URL: ${url}`,
185
+ });
186
+ }
187
+ else if (elicitationResult.action === "decline") {
162
188
  content.push({
163
189
  type: "text",
164
- text: `\nRaw result: ${JSON.stringify(elicitationResult, null, 2)}`,
190
+ text: `❌ User declined to open the URL (Elicitation ID: ${elicitationId}).`,
165
191
  });
166
- return { content };
192
+ }
193
+ else if (elicitationResult.action === "cancel") {
194
+ content.push({
195
+ type: "text",
196
+ text: `⚠️ User cancelled the URL elicitation (Elicitation ID: ${elicitationId}).`,
197
+ });
198
+ }
199
+ // Include raw result for debugging
200
+ content.push({
201
+ type: "text",
202
+ text: `\nRaw result: ${JSON.stringify(elicitationResult, null, 2)}`,
167
203
  });
168
- }
204
+ return { content };
205
+ });
169
206
  };
@@ -1,10 +1,17 @@
1
1
  // The HTTP+SSE transport manager (deprecated transport; kept working): one
2
2
  // server per `GET /sse` stream, with client messages posted to `/message`.
3
3
  //
4
+ // HTTP+SSE is a 2025-era transport, deprecated since 2025-03-26 and absent
5
+ // from 2026-07-28. The v2 SDK serves it only through the frozen copy in
6
+ // `@modelcontextprotocol/server-legacy/sse` (itself deprecated). It is kept so
7
+ // existing SSE clients keep working, serves the 2025 era only, and is never
8
+ // the default: Streamable HTTP serves both eras (#4852). The launcher warns
9
+ // on start.
10
+ //
4
11
  // `createApp()` builds the Express app without binding a port (#4854), so a
5
12
  // test can serve it on a free port and drive it with a real client, and each
6
13
  // app has its own session map. `startSseServer()` is what the launcher runs.
7
- import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
14
+ import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
8
15
  import express from "express";
9
16
  import { createServer } from "../server/index.js";
10
17
  import cors from "cors";
@@ -65,7 +72,7 @@ export function createApp() {
65
72
  const sessionId = transport.sessionId;
66
73
  console.error("Client Disconnected: ", sessionId);
67
74
  transports.delete(sessionId);
68
- cleanup(sessionId);
75
+ cleanup();
69
76
  };
70
77
  });
71
78
  // Handle POST requests for client messages
@@ -96,6 +103,8 @@ export function createApp() {
96
103
  */
97
104
  export function startSseServer() {
98
105
  console.error("Starting SSE server...");
106
+ console.error("Warning: the HTTP+SSE transport is deprecated and serves 2025-era clients only. " +
107
+ "Use streamableHttp, which serves both 2025-era and 2026-07-28 clients.");
99
108
  const app = createApp();
100
109
  // Start the express server
101
110
  const PORT = process.env.PORT || 3001;
@@ -1,48 +1,68 @@
1
1
  #!/usr/bin/env node
2
- // The stdio transport manager: one server, connected to the process's own
3
- // stdin/stdout, closed on SIGINT.
2
+ // The stdio transport manager: the server factory, served on the process's
3
+ // own stdin/stdout through the SDK's `serveStdio` entry, closed on SIGINT.
4
+ //
5
+ // `serveStdio` lets the client's first message pick the connection's
6
+ // protocol era (#4852): a 2026-07-28 client opens with `server/discover` (or
7
+ // any request carrying the per-request `_meta` envelope) and a 2025-era
8
+ // client with `initialize`. It then builds one server for that era from the
9
+ // factory and pins it to the connection. It may build and discard one more
10
+ // first, to answer a discover probe, so each instance's cleanup runs when that
11
+ // instance closes.
4
12
  //
5
13
  // It exports its start-up instead of running it at import (#4854), so a test
6
14
  // can drive the same code in-process over a pair of streams and call the
7
15
  // SIGINT handler directly, while `index.ts` still starts it the way a user
8
16
  // launches the binary.
9
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
+ import { serveStdio, StdioServerTransport, } from "@modelcontextprotocol/server/stdio";
10
18
  import { createServer } from "../server/index.js";
11
19
  /**
12
20
  * The main method
13
- * - Initializes the StdioServerTransport, sets up the server,
21
+ * - Serves the server factory over a StdioServerTransport,
14
22
  * - Handles cleanup on process exit.
15
23
  *
16
24
  * @param stdin - The stream the server reads messages from (the process's stdin by default).
17
25
  * @param stdout - The stream the server writes messages to (the process's stdout by default).
18
- * @return {Promise<StdioSession>} The connected server and the handler registered for SIGINT.
26
+ * @return {Promise<StdioSession>} The served connection and the handler registered for SIGINT.
19
27
  */
20
28
  export async function main(stdin = process.stdin, stdout = process.stdout) {
21
- const transport = new StdioServerTransport(stdin, stdout);
22
- const { server, cleanup } = createServer();
23
- // Connect transport to server
24
- await server.connect(transport);
29
+ // The cleanups of the instances still open
30
+ const cleanups = new Set();
31
+ const handle = serveStdio(({ era }) => {
32
+ const { server, cleanup } = createServer({ era });
33
+ cleanups.add(cleanup);
34
+ server.server.onclose = () => {
35
+ cleanups.delete(cleanup);
36
+ cleanup();
37
+ };
38
+ return server;
39
+ }, {
40
+ transport: new StdioServerTransport(stdin, stdout),
41
+ // serveStdio reports a transport that fails, including one that cannot
42
+ // start, here rather than by rejecting, so record the failure in the
43
+ // exit status for whatever supervises the process.
44
+ onerror: (error) => {
45
+ console.error("Transport error:", error);
46
+ process.exitCode = 1;
47
+ },
48
+ });
25
49
  // Cleanup on exit
26
50
  const shutdown = async () => {
27
- await server.close();
28
- cleanup();
51
+ await handle.close();
52
+ for (const cleanup of cleanups)
53
+ cleanup();
54
+ cleanups.clear();
29
55
  process.exit(0);
30
56
  };
31
57
  process.on("SIGINT", shutdown);
32
- return { server, shutdown };
58
+ return { handle, shutdown };
33
59
  }
34
60
  /**
35
- * Start the stdio server as the launcher does: announce it on stderr, run
36
- * `main()` (on the process's stdio unless other streams are given), and exit 1
37
- * if it fails.
61
+ * Start the stdio server as the launcher does: announce it on stderr and run
62
+ * `main()` on the process's stdio unless other streams are given. A transport
63
+ * that fails, including one that cannot start, is reported on stderr.
38
64
  */
39
65
  export async function startStdioServer(stdin, stdout) {
40
66
  console.error("Starting default (STDIO) server...");
41
- try {
42
- await main(stdin, stdout);
43
- }
44
- catch (error) {
45
- console.error("Server error:", error);
46
- process.exit(1);
47
- }
67
+ await main(stdin, stdout);
48
68
  }
@@ -1,13 +1,32 @@
1
- // The Streamable HTTP transport manager: one server per session, created on
2
- // the initialize POST to `/mcp`, with GET for the standalone SSE stream and
3
- // DELETE to end the session.
1
+ // The Streamable HTTP transport manager: one `/mcp` endpoint serving both
2
+ // protocol eras (#4852).
3
+ //
4
+ // - 2026-07-28 traffic (a request carrying the per-request `_meta` envelope)
5
+ // goes to the SDK's `createMcpHandler`, which builds a fresh server per
6
+ // request: no sessions, `server/discover` instead of `initialize`, change
7
+ // notifications on `subscriptions/listen` streams published through the
8
+ // handler's bus, and input requests in-band (`input_required`).
9
+ // - 2025-era traffic keeps the sessionful wiring it had: one server per
10
+ // session, created on the initialize POST, with GET for the standalone SSE
11
+ // stream, DELETE to end the session, and an event store for resumability.
12
+ // The SDK's default 2025-era serving is stateless, which would leave no
13
+ // channel for server-to-client requests, so elicitation, sampling and roots
14
+ // would stop working for 2025-era HTTP clients; routing them here keeps them
15
+ // working, the pattern the SDK documents for an existing sessionful
16
+ // deployment.
17
+ //
18
+ // A request with an `Mcp-Session-Id`, a GET and a DELETE are 2025-era by
19
+ // definition, since 2026-07-28 has none of them. A session-less POST is
20
+ // classified by the SDK's own `isLegacyRequest`, from a body parsed once and
21
+ // handed to whichever side serves it.
4
22
  //
5
23
  // `createApp()` builds the Express app without binding a port or installing a
6
24
  // signal handler (#4854), so a test can serve it on a free port, drive it with
7
25
  // a real client, and call its shutdown handler directly; each app has its own
8
- // session map. `startStreamableHttpServer()` is what the launcher runs.
9
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
- import { isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js";
26
+ // session map and its own 2026-07-28 handler. `startStreamableHttpServer()` is
27
+ // what the launcher runs.
28
+ import { createMcpHandler, isJSONRPCRequest, isLegacyRequest, } from "@modelcontextprotocol/server";
29
+ import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest, } from "@modelcontextprotocol/node";
11
30
  import express from "express";
12
31
  import { createServer } from "../server/index.js";
13
32
  import { randomUUID } from "node:crypto";
@@ -51,10 +70,47 @@ function sessionNotFound(res, id = null) {
51
70
  id,
52
71
  });
53
72
  }
73
+ /** The most bytes of a session-less POST body parsed to classify it (4 MiB, the SDK's own bound). */
74
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
75
+ /** Parses a session-less POST's JSON body, to classify it and to serve it. */
76
+ const parseJson = express.json({
77
+ limit: MAX_BODY_BYTES,
78
+ type: () => true,
79
+ // Any JSON value parses, so a primitive body reaches the SDK, which answers
80
+ // it as an invalid request (-32600); -32700 is only for text that is not JSON.
81
+ strict: false,
82
+ });
83
+ /**
84
+ * Answer a session-less POST whose body could not be parsed the way the SDK
85
+ * answers one: a JSON-RPC error with a null id, as 400 (not JSON) or 413 (too
86
+ * large). Anything else goes on to Express's error handling.
87
+ */
88
+ function bodyError(error, _req, res, next) {
89
+ if (error.type === "entity.parse.failed") {
90
+ res.status(400).json({
91
+ jsonrpc: "2.0",
92
+ error: {
93
+ code: -32700,
94
+ message: "Parse error: the request body is not valid JSON",
95
+ },
96
+ id: null,
97
+ });
98
+ }
99
+ else if (error.type === "entity.too.large") {
100
+ res.status(413).json({
101
+ jsonrpc: "2.0",
102
+ error: { code: -32600, message: "Request body too large" },
103
+ id: null,
104
+ });
105
+ }
106
+ else {
107
+ next(error);
108
+ }
109
+ }
54
110
  /**
55
111
  * Build the Streamable HTTP transport's Express app: CORS, the `/mcp` POST,
56
112
  * GET and DELETE routes, the map from session id to transport that they
57
- * share, and the shutdown handler that walks that map.
113
+ * share, the 2026-07-28 handler, and the shutdown handler that closes them.
58
114
  */
59
115
  export function createApp() {
60
116
  // Express app with permissive CORS for testing with Inspector direct connect mode
@@ -70,14 +126,42 @@ export function createApp() {
70
126
  "mcp-protocol-version",
71
127
  ],
72
128
  }));
129
+ // The 2026-07-28 side: a fresh server per request, built for the modern
130
+ // era. Its change notifications go out on the handler's subscription bus,
131
+ // which reaches every open subscriptions/listen stream that asked for them.
132
+ // It refuses 2025-era traffic, which the routes below never send it.
133
+ const modern = createMcpHandler(() => createServer({
134
+ era: "modern",
135
+ publish: {
136
+ toolsChanged: () => modern.notify.toolsChanged(),
137
+ promptsChanged: () => modern.notify.promptsChanged(),
138
+ resourcesChanged: () => modern.notify.resourcesChanged(),
139
+ resourceUpdated: (uri) => modern.notify.resourceUpdated(uri),
140
+ },
141
+ }).server, {
142
+ legacy: "reject",
143
+ onerror: (error) => console.log("Error serving MCP request:", error),
144
+ });
145
+ const serveModern = toNodeHandler(modern);
73
146
  // Map sessionId to server transport for each client
74
147
  const transports = new Map();
148
+ // A session-less POST's body is parsed once, to classify it and serve it.
149
+ // A POST with a session id is a 2025-era session's, and its transport reads
150
+ // the body itself.
151
+ app.post("/mcp", (req, res, next) => req.headers["mcp-session-id"] ? next() : parseJson(req, res, next), bodyError);
75
152
  // Handle POST requests for client messages
76
153
  app.post("/mcp", async (req, res) => {
77
154
  console.log("Received MCP POST request");
78
155
  try {
79
156
  // Check for existing session ID
80
157
  const sessionId = req.headers["mcp-session-id"];
158
+ // A session-less POST that carries the 2026-07-28 envelope is served
159
+ // by the modern handler; everything else stays on the 2025-era path.
160
+ if (!sessionId &&
161
+ !(await isLegacyRequest(await toWebRequest(req, req.body)))) {
162
+ await serveModern(req, res, req.body);
163
+ return;
164
+ }
81
165
  let transport;
82
166
  if (sessionId && transports.has(sessionId)) {
83
167
  // Reuse existing transport
@@ -87,7 +171,7 @@ export function createApp() {
87
171
  const { server, cleanup } = createServer();
88
172
  // New initialization request
89
173
  const eventStore = new InMemoryEventStore();
90
- transport = new StreamableHTTPServerTransport({
174
+ transport = new NodeStreamableHTTPServerTransport({
91
175
  sessionIdGenerator: () => randomUUID(),
92
176
  eventStore, // Enable resumability
93
177
  onsessioninitialized: (sessionId) => {
@@ -103,13 +187,13 @@ export function createApp() {
103
187
  if (sid && transports.has(sid)) {
104
188
  console.log(`Transport closed for session ${sid}, removing from transports map`);
105
189
  transports.delete(sid);
106
- cleanup(sid);
190
+ cleanup();
107
191
  }
108
192
  };
109
193
  // Connect the transport to the MCP server BEFORE handling the request
110
194
  // so responses can flow back through the same transport
111
195
  await server.connect(transport);
112
- await transport.handleRequest(req, res);
196
+ await transport.handleRequest(req, res, req.body);
113
197
  return;
114
198
  }
115
199
  else {
@@ -207,6 +291,8 @@ export function createApp() {
207
291
  // Handle server shutdown
208
292
  const shutdown = async () => {
209
293
  console.log("Shutting down server...");
294
+ // End the 2026-07-28 requests and subscription streams in flight
295
+ await modern.close();
210
296
  // Close all active transports to properly clean up resources
211
297
  // (a snapshot, since closing a transport removes it from the map)
212
298
  for (const [sessionId, transport] of [...transports]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@modelcontextprotocol/server-everything",
3
- "version": "1.0.0",
3
+ "version": "2.0.0",
4
4
  "description": "MCP server that exercises all the features of the MCP protocol",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "mcpName": "io.github.modelcontextprotocol/server-everything",
@@ -12,6 +12,9 @@
12
12
  "url": "https://github.com/modelcontextprotocol/servers.git"
13
13
  },
14
14
  "type": "module",
15
+ "engines": {
16
+ "node": ">=24"
17
+ },
15
18
  "bin": {
16
19
  "mcp-server-everything": "dist/index.js"
17
20
  },
@@ -34,13 +37,17 @@
34
37
  "validate": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm run test"
35
38
  },
36
39
  "dependencies": {
37
- "@modelcontextprotocol/sdk": "^1.31.0",
40
+ "@modelcontextprotocol/node": "^2.1.1",
41
+ "@modelcontextprotocol/server": "^2.3.1",
42
+ "@modelcontextprotocol/server-legacy": "^2.3.1",
38
43
  "cors": "^2.8.5",
39
44
  "express": "^5.2.1",
40
45
  "jszip": "^3.10.1",
41
- "zod": "^4.0.0"
46
+ "zod": "^4.2.0"
42
47
  },
43
48
  "devDependencies": {
49
+ "@modelcontextprotocol/client": "^2.3.1",
50
+ "@modelcontextprotocol/core": "^2.3.1",
44
51
  "@types/cors": "^2.8.19",
45
52
  "@types/express": "^5.0.6",
46
53
  "@vitest/coverage-v8": "^4.1.11",