@modelcontextprotocol/server-everything 0.6.2 → 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.
- package/README.md +140 -76
- package/dist/docs/architecture.md +45 -0
- package/dist/docs/extension.md +25 -0
- package/dist/docs/features.md +99 -0
- package/dist/docs/how-it-works.md +60 -0
- package/dist/docs/instructions.md +44 -0
- package/dist/docs/startup.md +71 -0
- package/dist/docs/structure.md +246 -0
- package/dist/index.js +73 -16
- package/dist/prompts/args.js +34 -0
- package/dist/prompts/completions.js +52 -0
- package/dist/prompts/index.js +15 -0
- package/dist/prompts/resource.js +61 -0
- package/dist/prompts/simple.js +23 -0
- package/dist/resources/files.js +91 -0
- package/dist/resources/index.js +38 -0
- package/dist/resources/minted.js +119 -0
- package/dist/resources/session.js +62 -0
- package/dist/resources/subscriptions.js +66 -0
- package/dist/resources/templates.js +167 -0
- package/dist/server/context.js +47 -0
- package/dist/server/index.js +153 -0
- package/dist/server/logging.js +43 -0
- package/dist/server/roots.js +49 -0
- package/dist/server/tasks.js +295 -0
- package/dist/tools/echo.js +35 -0
- package/dist/tools/get-annotated-message.js +89 -0
- package/dist/tools/get-env.js +34 -0
- package/dist/tools/get-header-params.js +95 -0
- package/dist/tools/get-resource-links.js +68 -0
- package/dist/tools/get-resource-reference.js +81 -0
- package/dist/tools/get-roots-list.js +76 -0
- package/dist/tools/get-structured-content.js +78 -0
- package/dist/tools/get-sum.js +46 -0
- package/dist/tools/get-tiny-image.js +47 -0
- package/dist/tools/gzip-file-as-resource.js +213 -0
- package/dist/tools/index.js +110 -0
- package/dist/tools/simulate-research-query.js +216 -0
- package/dist/tools/toggle-simulated-logging.js +60 -0
- package/dist/tools/toggle-subscriber-updates.js +60 -0
- package/dist/tools/trigger-elicitation-request-async.js +122 -0
- package/dist/tools/trigger-elicitation-request.js +223 -0
- package/dist/tools/trigger-list-changed.js +57 -0
- package/dist/tools/trigger-log-messages.js +60 -0
- package/dist/tools/trigger-long-running-operation.js +65 -0
- package/dist/tools/trigger-multi-step-elicitation.js +125 -0
- package/dist/tools/trigger-resource-update.js +52 -0
- package/dist/tools/trigger-sampling-request-async.js +110 -0
- package/dist/tools/trigger-sampling-request.js +83 -0
- package/dist/tools/trigger-url-elicitation.js +206 -0
- package/dist/transports/in-memory-event-store.js +44 -0
- package/dist/transports/listen.js +36 -0
- package/dist/transports/sse.js +112 -0
- package/dist/transports/stdio.js +68 -0
- package/dist/transports/streamableHttp.js +326 -0
- package/dist/version.js +35 -0
- package/package.json +39 -13
- package/dist/everything.js +0 -361
- package/dist/sse.js +0 -24
|
@@ -0,0 +1,206 @@
|
|
|
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.
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { inputRequired, inputResponse, UrlElicitationRequiredError, } from "@modelcontextprotocol/server";
|
|
16
|
+
import { z } from "zod";
|
|
17
|
+
// Tool input schema
|
|
18
|
+
const TriggerUrlElicitationSchema = z.object({
|
|
19
|
+
url: z.string().url().describe("The URL the user should open"),
|
|
20
|
+
message: z
|
|
21
|
+
.string()
|
|
22
|
+
.default("Please open the link to complete this action.")
|
|
23
|
+
.describe("Message shown to the user before opening the URL"),
|
|
24
|
+
elicitationId: z
|
|
25
|
+
.string()
|
|
26
|
+
.optional()
|
|
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."),
|
|
29
|
+
errorPath: z
|
|
30
|
+
.boolean()
|
|
31
|
+
.default(false)
|
|
32
|
+
.describe("Controls which elicitation mechanism is used. " +
|
|
33
|
+
"When false (default), sends an elicitation/create request (request path). " +
|
|
34
|
+
"When true, throws a UrlElicitationRequiredError (MCP error code -32042) so the client handles " +
|
|
35
|
+
"the URL elicitation via the error path rather than waiting for a response. " +
|
|
36
|
+
"To clear the error, satisfy the prerequisite and retry this call with the same arguments; the " +
|
|
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."),
|
|
40
|
+
});
|
|
41
|
+
// Tool configuration
|
|
42
|
+
const name = "trigger-url-elicitation";
|
|
43
|
+
const config = {
|
|
44
|
+
title: "Trigger URL Elicitation Tool",
|
|
45
|
+
description: "Trigger a URL elicitation so the client can direct the user to a browser flow. " +
|
|
46
|
+
"Supports two mechanisms: the request path (elicitation/create, default) which awaits the user's " +
|
|
47
|
+
"response, and the error path (UrlElicitationRequiredError, -32042) which signals the client " +
|
|
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).",
|
|
50
|
+
inputSchema: TriggerUrlElicitationSchema,
|
|
51
|
+
annotations: {
|
|
52
|
+
readOnlyHint: false,
|
|
53
|
+
destructiveHint: false,
|
|
54
|
+
idempotentHint: false,
|
|
55
|
+
openWorldHint: true,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Registers the 'trigger-url-elicitation' tool.
|
|
60
|
+
*
|
|
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.
|
|
65
|
+
*
|
|
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:
|
|
69
|
+
* - Sends an `elicitation/create` request and awaits the result (request path), or
|
|
70
|
+
* - Throws a `UrlElicitationRequiredError` (MCP error -32042) carrying a
|
|
71
|
+
* prerequisite elicitation for the client to handle (error path). When the
|
|
72
|
+
* client satisfies the prerequisite and retries the same call, the retry
|
|
73
|
+
* ignores `errorPath` and proceeds via the request path, so the client does
|
|
74
|
+
* not loop on the same error.
|
|
75
|
+
*
|
|
76
|
+
* @param {McpServer} server - The McpServer instance where the tool will be registered.
|
|
77
|
+
* @param {ServerContext} context - The protocol era the instance serves.
|
|
78
|
+
*/
|
|
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 }) },
|
|
88
|
+
});
|
|
89
|
+
}
|
|
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);
|
|
158
|
+
}
|
|
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.");
|
|
170
|
+
}
|
|
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") {
|
|
188
|
+
content.push({
|
|
189
|
+
type: "text",
|
|
190
|
+
text: `❌ User declined to open the URL (Elicitation ID: ${elicitationId}).`,
|
|
191
|
+
});
|
|
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)}`,
|
|
203
|
+
});
|
|
204
|
+
return { content };
|
|
205
|
+
});
|
|
206
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The Streamable HTTP transport's event store, which makes its SSE streams
|
|
2
|
+
// resumable: a client that reconnects with a `Last-Event-ID` is sent the
|
|
3
|
+
// events it missed (#4087).
|
|
4
|
+
//
|
|
5
|
+
// Events are kept per stream, and a replay sends only the later events of the
|
|
6
|
+
// stream the given event belongs to, never another stream's. An unknown event
|
|
7
|
+
// id has no stream: `getStreamIdForEventId` reports that as `undefined`, which
|
|
8
|
+
// is how the SDK learns to refuse the resume before it calls
|
|
9
|
+
// `replayEventsAfter`. In memory and unbounded, so for examples and testing,
|
|
10
|
+
// not production. Split out of `streamableHttp.ts` (from #4099) so it can be
|
|
11
|
+
// tested directly.
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
export class InMemoryEventStore {
|
|
14
|
+
events = new Map();
|
|
15
|
+
async storeEvent(streamId, message) {
|
|
16
|
+
const eventId = randomUUID();
|
|
17
|
+
this.events.set(eventId, { streamId, message });
|
|
18
|
+
return eventId;
|
|
19
|
+
}
|
|
20
|
+
async getStreamIdForEventId(eventId) {
|
|
21
|
+
return this.events.get(eventId)?.streamId;
|
|
22
|
+
}
|
|
23
|
+
async replayEventsAfter(lastEventId, { send, }) {
|
|
24
|
+
const lastEvent = this.events.get(lastEventId);
|
|
25
|
+
if (!lastEvent) {
|
|
26
|
+
// The SDK asks getStreamIdForEventId first and refuses an unknown id, so
|
|
27
|
+
// reaching here is a caller error: there is no stream to return.
|
|
28
|
+
throw new Error(`Unknown event ID: ${lastEventId}`);
|
|
29
|
+
}
|
|
30
|
+
const { streamId } = lastEvent;
|
|
31
|
+
let foundLastEvent = false;
|
|
32
|
+
for (const [eventId, event] of this.events) {
|
|
33
|
+
if (eventId === lastEventId) {
|
|
34
|
+
foundLastEvent = true;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!foundLastEvent || event.streamId !== streamId) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
await send(eventId, event.message);
|
|
41
|
+
}
|
|
42
|
+
return streamId;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Binds an HTTP transport's Express app to its port, and is the one place that
|
|
2
|
+
// decides whether that worked (#4923).
|
|
3
|
+
//
|
|
4
|
+
// Express 5 passes a listen error to the same callback it calls on success, so
|
|
5
|
+
// a callback that ignores its argument prints "running" for a server bound to
|
|
6
|
+
// nothing, and with no `error` listener the process then stays up on no port.
|
|
7
|
+
// Both HTTP transports start through here so neither can report a port it
|
|
8
|
+
// does not hold: the listening line is printed only for a real bind, and a
|
|
9
|
+
// failed one names the port and exits non-zero, which is what lets a launcher
|
|
10
|
+
// (the boot smoke, `npm`) see the failure and retry or report it.
|
|
11
|
+
/**
|
|
12
|
+
* Start `app` on `port`. Prints `listeningMessage` once the port is bound; on a
|
|
13
|
+
* bind failure prints why and exits the process with status 1.
|
|
14
|
+
*/
|
|
15
|
+
export function listenOrExit(app, port, listeningMessage) {
|
|
16
|
+
const server = app.listen(port, (error) => {
|
|
17
|
+
// A failed bind arrives here too; the `error` listener below reports it.
|
|
18
|
+
if (error)
|
|
19
|
+
return;
|
|
20
|
+
console.error(listeningMessage);
|
|
21
|
+
});
|
|
22
|
+
server.on("error", (err) => {
|
|
23
|
+
const code = typeof err === "object" && err !== null && "code" in err
|
|
24
|
+
? err.code
|
|
25
|
+
: undefined;
|
|
26
|
+
if (code === "EADDRINUSE") {
|
|
27
|
+
console.error(`Failed to start: Port ${port} is already in use. Set PORT to a free port or stop the conflicting process.`);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
console.error("HTTP server encountered an error while starting:", err);
|
|
31
|
+
}
|
|
32
|
+
// Ensure a non-zero exit so npm reports the failure instead of silently exiting
|
|
33
|
+
process.exit(1);
|
|
34
|
+
});
|
|
35
|
+
return server;
|
|
36
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// The HTTP+SSE transport manager (deprecated transport; kept working): one
|
|
2
|
+
// server per `GET /sse` stream, with client messages posted to `/message`.
|
|
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
|
+
//
|
|
11
|
+
// `createApp()` builds the Express app without binding a port (#4854), so a
|
|
12
|
+
// test can serve it on a free port and drive it with a real client, and each
|
|
13
|
+
// app has its own session map. `startSseServer()` is what the launcher runs.
|
|
14
|
+
import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
|
|
15
|
+
import express from "express";
|
|
16
|
+
import { createServer } from "../server/index.js";
|
|
17
|
+
import cors from "cors";
|
|
18
|
+
import { listenOrExit } from "./listen.js";
|
|
19
|
+
/**
|
|
20
|
+
* Answer a request the transport cannot serve with a JSON-RPC error body, as
|
|
21
|
+
* the Streamable HTTP transport does, so the client is not left waiting.
|
|
22
|
+
*/
|
|
23
|
+
function sendError(res, status, message) {
|
|
24
|
+
res.status(status).json({
|
|
25
|
+
jsonrpc: "2.0",
|
|
26
|
+
error: { code: -32000, message },
|
|
27
|
+
id: null,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Build the SSE transport's Express app: CORS, `GET /sse` and `POST /message`,
|
|
32
|
+
* and the map from session id to transport that they share.
|
|
33
|
+
*/
|
|
34
|
+
export function createApp() {
|
|
35
|
+
// Express app with permissive CORS for testing with Inspector direct connect mode
|
|
36
|
+
const app = express();
|
|
37
|
+
app.use(cors({
|
|
38
|
+
origin: "*", // use "*" with caution in production
|
|
39
|
+
methods: "GET,POST",
|
|
40
|
+
preflightContinue: false,
|
|
41
|
+
optionsSuccessStatus: 204,
|
|
42
|
+
}));
|
|
43
|
+
// Map sessionId to transport for each client
|
|
44
|
+
const transports = new Map();
|
|
45
|
+
// Handle GET requests for new SSE streams
|
|
46
|
+
app.get("/sse", async (req, res) => {
|
|
47
|
+
// Session Id should not exist for GET /sse requests: each stream is a new
|
|
48
|
+
// session. Answer one that names a session rather than leaving it hanging
|
|
49
|
+
// (#4981): 409 if that session already has its stream, 404 if it is unknown.
|
|
50
|
+
if (req?.query?.sessionId) {
|
|
51
|
+
const sessionId = String(req.query.sessionId);
|
|
52
|
+
if (transports.has(sessionId)) {
|
|
53
|
+
console.error("Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.", sessionId);
|
|
54
|
+
sendError(res, 409, "Conflict: this session already has an SSE stream");
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
console.error(`No transport found for sessionId ${sessionId}`);
|
|
58
|
+
sendError(res, 404, "Session not found");
|
|
59
|
+
}
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// Create and store transport for the new session
|
|
63
|
+
const { server, cleanup } = createServer();
|
|
64
|
+
const transport = new SSEServerTransport("/message", res);
|
|
65
|
+
transports.set(transport.sessionId, transport);
|
|
66
|
+
// Connect server to transport
|
|
67
|
+
await server.connect(transport);
|
|
68
|
+
const sessionId = transport.sessionId;
|
|
69
|
+
console.error("Client Connected: ", sessionId);
|
|
70
|
+
// Handle close of connection
|
|
71
|
+
server.server.onclose = async () => {
|
|
72
|
+
const sessionId = transport.sessionId;
|
|
73
|
+
console.error("Client Disconnected: ", sessionId);
|
|
74
|
+
transports.delete(sessionId);
|
|
75
|
+
cleanup();
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
// Handle POST requests for client messages
|
|
79
|
+
app.post("/message", async (req, res) => {
|
|
80
|
+
// Session Id should exist for POST /message requests
|
|
81
|
+
const sessionId = req?.query?.sessionId;
|
|
82
|
+
// Get the transport for this session and use it to handle the request
|
|
83
|
+
const transport = transports.get(sessionId);
|
|
84
|
+
if (transport) {
|
|
85
|
+
console.error("Client Message from", sessionId);
|
|
86
|
+
await transport.handlePostMessage(req, res);
|
|
87
|
+
}
|
|
88
|
+
else if (!sessionId) {
|
|
89
|
+
// Answer rather than leave the request hanging (#4981)
|
|
90
|
+
console.error("No sessionId in POST /message");
|
|
91
|
+
sendError(res, 400, "Bad Request: sessionId query parameter is required");
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
console.error(`No transport found for sessionId ${sessionId}`);
|
|
95
|
+
sendError(res, 404, "Session not found");
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
return app;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Start the SSE server as the launcher does: build the app and bind it to
|
|
102
|
+
* `PORT` (default 3001).
|
|
103
|
+
*/
|
|
104
|
+
export function startSseServer() {
|
|
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.");
|
|
108
|
+
const app = createApp();
|
|
109
|
+
// Start the express server
|
|
110
|
+
const PORT = process.env.PORT || 3001;
|
|
111
|
+
return listenOrExit(app, PORT, `Server is running on port ${PORT}`);
|
|
112
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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.
|
|
12
|
+
//
|
|
13
|
+
// It exports its start-up instead of running it at import (#4854), so a test
|
|
14
|
+
// can drive the same code in-process over a pair of streams and call the
|
|
15
|
+
// SIGINT handler directly, while `index.ts` still starts it the way a user
|
|
16
|
+
// launches the binary.
|
|
17
|
+
import { serveStdio, StdioServerTransport, } from "@modelcontextprotocol/server/stdio";
|
|
18
|
+
import { createServer } from "../server/index.js";
|
|
19
|
+
/**
|
|
20
|
+
* The main method
|
|
21
|
+
* - Serves the server factory over a StdioServerTransport,
|
|
22
|
+
* - Handles cleanup on process exit.
|
|
23
|
+
*
|
|
24
|
+
* @param stdin - The stream the server reads messages from (the process's stdin by default).
|
|
25
|
+
* @param stdout - The stream the server writes messages to (the process's stdout by default).
|
|
26
|
+
* @return {Promise<StdioSession>} The served connection and the handler registered for SIGINT.
|
|
27
|
+
*/
|
|
28
|
+
export async function main(stdin = process.stdin, stdout = process.stdout) {
|
|
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
|
+
});
|
|
49
|
+
// Cleanup on exit
|
|
50
|
+
const shutdown = async () => {
|
|
51
|
+
await handle.close();
|
|
52
|
+
for (const cleanup of cleanups)
|
|
53
|
+
cleanup();
|
|
54
|
+
cleanups.clear();
|
|
55
|
+
process.exit(0);
|
|
56
|
+
};
|
|
57
|
+
process.on("SIGINT", shutdown);
|
|
58
|
+
return { handle, shutdown };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
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.
|
|
64
|
+
*/
|
|
65
|
+
export async function startStdioServer(stdin, stdout) {
|
|
66
|
+
console.error("Starting default (STDIO) server...");
|
|
67
|
+
await main(stdin, stdout);
|
|
68
|
+
}
|