@modelcontextprotocol/server-everything 0.6.2 → 1.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 +121 -72
- package/dist/docs/architecture.md +44 -0
- package/dist/docs/extension.md +23 -0
- package/dist/docs/features.md +105 -0
- package/dist/docs/how-it-works.md +45 -0
- package/dist/docs/instructions.md +37 -0
- package/dist/docs/startup.md +76 -0
- package/dist/docs/structure.md +212 -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 +60 -0
- package/dist/prompts/simple.js +23 -0
- package/dist/resources/files.js +83 -0
- package/dist/resources/index.js +33 -0
- package/dist/resources/session.js +62 -0
- package/dist/resources/subscriptions.js +144 -0
- package/dist/resources/templates.js +166 -0
- package/dist/server/index.js +95 -0
- package/dist/server/logging.js +70 -0
- package/dist/server/roots.js +70 -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-resource-links.js +68 -0
- package/dist/tools/get-resource-reference.js +81 -0
- package/dist/tools/get-roots-list.js +77 -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 +194 -0
- package/dist/tools/index.js +52 -0
- package/dist/tools/simulate-research-query.js +251 -0
- package/dist/tools/toggle-simulated-logging.js +47 -0
- package/dist/tools/toggle-subscriber-updates.js +50 -0
- package/dist/tools/trigger-elicitation-request-async.js +227 -0
- package/dist/tools/trigger-elicitation-request.js +222 -0
- package/dist/tools/trigger-long-running-operation.js +65 -0
- package/dist/tools/trigger-sampling-request-async.js +174 -0
- package/dist/tools/trigger-sampling-request.js +77 -0
- package/dist/tools/trigger-url-elicitation.js +169 -0
- package/dist/transports/in-memory-event-store.js +44 -0
- package/dist/transports/listen.js +36 -0
- package/dist/transports/sse.js +103 -0
- package/dist/transports/stdio.js +48 -0
- package/dist/transports/streamableHttp.js +240 -0
- package/dist/version.js +35 -0
- package/package.json +32 -13
- package/dist/everything.js +0 -361
- package/dist/sse.js +0 -24
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { ElicitResultSchema, UrlElicitationRequiredError, } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
// Tool input schema
|
|
5
|
+
const TriggerUrlElicitationSchema = z.object({
|
|
6
|
+
url: z.string().url().describe("The URL the user should open"),
|
|
7
|
+
message: z
|
|
8
|
+
.string()
|
|
9
|
+
.default("Please open the link to complete this action.")
|
|
10
|
+
.describe("Message shown to the user before opening the URL"),
|
|
11
|
+
elicitationId: z
|
|
12
|
+
.string()
|
|
13
|
+
.optional()
|
|
14
|
+
.describe("Optional explicit elicitation ID. Defaults to a random UUID."),
|
|
15
|
+
errorPath: z
|
|
16
|
+
.boolean()
|
|
17
|
+
.default(false)
|
|
18
|
+
.describe("Controls which elicitation mechanism is used. " +
|
|
19
|
+
"When false (default), sends an elicitation/create request (request path). " +
|
|
20
|
+
"When true, throws a UrlElicitationRequiredError (MCP error code -32042) so the client handles " +
|
|
21
|
+
"the URL elicitation via the error path rather than waiting for a response. " +
|
|
22
|
+
"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."),
|
|
24
|
+
});
|
|
25
|
+
// Tool configuration
|
|
26
|
+
const name = "trigger-url-elicitation";
|
|
27
|
+
const config = {
|
|
28
|
+
title: "Trigger URL Elicitation Tool",
|
|
29
|
+
description: "Trigger a URL elicitation so the client can direct the user to a browser flow. " +
|
|
30
|
+
"Supports two mechanisms: the request path (elicitation/create, default) which awaits the user's " +
|
|
31
|
+
"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.",
|
|
33
|
+
inputSchema: TriggerUrlElicitationSchema,
|
|
34
|
+
annotations: {
|
|
35
|
+
readOnlyHint: false,
|
|
36
|
+
destructiveHint: false,
|
|
37
|
+
idempotentHint: false,
|
|
38
|
+
openWorldHint: true,
|
|
39
|
+
},
|
|
40
|
+
};
|
|
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
|
+
/**
|
|
65
|
+
* Registers the 'trigger-url-elicitation' tool.
|
|
66
|
+
*
|
|
67
|
+
* This tool only registers when the client advertises URL-mode elicitation
|
|
68
|
+
* capability (clientCapabilities.elicitation.url).
|
|
69
|
+
*
|
|
70
|
+
* Depending on the `errorPath` argument it either:
|
|
71
|
+
* - Sends an `elicitation/create` request and awaits the result (request path), or
|
|
72
|
+
* - Throws a `UrlElicitationRequiredError` (MCP error -32042) carrying a
|
|
73
|
+
* prerequisite elicitation for the client to handle (error path). When the
|
|
74
|
+
* client satisfies the prerequisite and retries the same call, the retry
|
|
75
|
+
* ignores `errorPath` and proceeds via the request path, so the client does
|
|
76
|
+
* not loop on the same error.
|
|
77
|
+
*
|
|
78
|
+
* @param {McpServer} server - The McpServer instance where the tool will be registered.
|
|
79
|
+
*/
|
|
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}`,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
else if (elicitationResult.action === "decline") {
|
|
150
|
+
content.push({
|
|
151
|
+
type: "text",
|
|
152
|
+
text: `❌ User declined to open the URL (Elicitation ID: ${elicitationId}).`,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
else if (elicitationResult.action === "cancel") {
|
|
156
|
+
content.push({
|
|
157
|
+
type: "text",
|
|
158
|
+
text: `⚠️ User cancelled the URL elicitation (Elicitation ID: ${elicitationId}).`,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
// Include raw result for debugging
|
|
162
|
+
content.push({
|
|
163
|
+
type: "text",
|
|
164
|
+
text: `\nRaw result: ${JSON.stringify(elicitationResult, null, 2)}`,
|
|
165
|
+
});
|
|
166
|
+
return { content };
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
};
|
|
@@ -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,103 @@
|
|
|
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
|
+
// `createApp()` builds the Express app without binding a port (#4854), so a
|
|
5
|
+
// test can serve it on a free port and drive it with a real client, and each
|
|
6
|
+
// app has its own session map. `startSseServer()` is what the launcher runs.
|
|
7
|
+
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
8
|
+
import express from "express";
|
|
9
|
+
import { createServer } from "../server/index.js";
|
|
10
|
+
import cors from "cors";
|
|
11
|
+
import { listenOrExit } from "./listen.js";
|
|
12
|
+
/**
|
|
13
|
+
* Answer a request the transport cannot serve with a JSON-RPC error body, as
|
|
14
|
+
* the Streamable HTTP transport does, so the client is not left waiting.
|
|
15
|
+
*/
|
|
16
|
+
function sendError(res, status, message) {
|
|
17
|
+
res.status(status).json({
|
|
18
|
+
jsonrpc: "2.0",
|
|
19
|
+
error: { code: -32000, message },
|
|
20
|
+
id: null,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Build the SSE transport's Express app: CORS, `GET /sse` and `POST /message`,
|
|
25
|
+
* and the map from session id to transport that they share.
|
|
26
|
+
*/
|
|
27
|
+
export function createApp() {
|
|
28
|
+
// Express app with permissive CORS for testing with Inspector direct connect mode
|
|
29
|
+
const app = express();
|
|
30
|
+
app.use(cors({
|
|
31
|
+
origin: "*", // use "*" with caution in production
|
|
32
|
+
methods: "GET,POST",
|
|
33
|
+
preflightContinue: false,
|
|
34
|
+
optionsSuccessStatus: 204,
|
|
35
|
+
}));
|
|
36
|
+
// Map sessionId to transport for each client
|
|
37
|
+
const transports = new Map();
|
|
38
|
+
// Handle GET requests for new SSE streams
|
|
39
|
+
app.get("/sse", async (req, res) => {
|
|
40
|
+
// Session Id should not exist for GET /sse requests: each stream is a new
|
|
41
|
+
// session. Answer one that names a session rather than leaving it hanging
|
|
42
|
+
// (#4981): 409 if that session already has its stream, 404 if it is unknown.
|
|
43
|
+
if (req?.query?.sessionId) {
|
|
44
|
+
const sessionId = String(req.query.sessionId);
|
|
45
|
+
if (transports.has(sessionId)) {
|
|
46
|
+
console.error("Client Reconnecting? This shouldn't happen; when client has a sessionId, GET /sse should not be called again.", sessionId);
|
|
47
|
+
sendError(res, 409, "Conflict: this session already has an SSE stream");
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
console.error(`No transport found for sessionId ${sessionId}`);
|
|
51
|
+
sendError(res, 404, "Session not found");
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
// Create and store transport for the new session
|
|
56
|
+
const { server, cleanup } = createServer();
|
|
57
|
+
const transport = new SSEServerTransport("/message", res);
|
|
58
|
+
transports.set(transport.sessionId, transport);
|
|
59
|
+
// Connect server to transport
|
|
60
|
+
await server.connect(transport);
|
|
61
|
+
const sessionId = transport.sessionId;
|
|
62
|
+
console.error("Client Connected: ", sessionId);
|
|
63
|
+
// Handle close of connection
|
|
64
|
+
server.server.onclose = async () => {
|
|
65
|
+
const sessionId = transport.sessionId;
|
|
66
|
+
console.error("Client Disconnected: ", sessionId);
|
|
67
|
+
transports.delete(sessionId);
|
|
68
|
+
cleanup(sessionId);
|
|
69
|
+
};
|
|
70
|
+
});
|
|
71
|
+
// Handle POST requests for client messages
|
|
72
|
+
app.post("/message", async (req, res) => {
|
|
73
|
+
// Session Id should exist for POST /message requests
|
|
74
|
+
const sessionId = req?.query?.sessionId;
|
|
75
|
+
// Get the transport for this session and use it to handle the request
|
|
76
|
+
const transport = transports.get(sessionId);
|
|
77
|
+
if (transport) {
|
|
78
|
+
console.error("Client Message from", sessionId);
|
|
79
|
+
await transport.handlePostMessage(req, res);
|
|
80
|
+
}
|
|
81
|
+
else if (!sessionId) {
|
|
82
|
+
// Answer rather than leave the request hanging (#4981)
|
|
83
|
+
console.error("No sessionId in POST /message");
|
|
84
|
+
sendError(res, 400, "Bad Request: sessionId query parameter is required");
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
console.error(`No transport found for sessionId ${sessionId}`);
|
|
88
|
+
sendError(res, 404, "Session not found");
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
return app;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Start the SSE server as the launcher does: build the app and bind it to
|
|
95
|
+
* `PORT` (default 3001).
|
|
96
|
+
*/
|
|
97
|
+
export function startSseServer() {
|
|
98
|
+
console.error("Starting SSE server...");
|
|
99
|
+
const app = createApp();
|
|
100
|
+
// Start the express server
|
|
101
|
+
const PORT = process.env.PORT || 3001;
|
|
102
|
+
return listenOrExit(app, PORT, `Server is running on port ${PORT}`);
|
|
103
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The stdio transport manager: one server, connected to the process's own
|
|
3
|
+
// stdin/stdout, closed on SIGINT.
|
|
4
|
+
//
|
|
5
|
+
// It exports its start-up instead of running it at import (#4854), so a test
|
|
6
|
+
// can drive the same code in-process over a pair of streams and call the
|
|
7
|
+
// SIGINT handler directly, while `index.ts` still starts it the way a user
|
|
8
|
+
// launches the binary.
|
|
9
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
10
|
+
import { createServer } from "../server/index.js";
|
|
11
|
+
/**
|
|
12
|
+
* The main method
|
|
13
|
+
* - Initializes the StdioServerTransport, sets up the server,
|
|
14
|
+
* - Handles cleanup on process exit.
|
|
15
|
+
*
|
|
16
|
+
* @param stdin - The stream the server reads messages from (the process's stdin by default).
|
|
17
|
+
* @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.
|
|
19
|
+
*/
|
|
20
|
+
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);
|
|
25
|
+
// Cleanup on exit
|
|
26
|
+
const shutdown = async () => {
|
|
27
|
+
await server.close();
|
|
28
|
+
cleanup();
|
|
29
|
+
process.exit(0);
|
|
30
|
+
};
|
|
31
|
+
process.on("SIGINT", shutdown);
|
|
32
|
+
return { server, shutdown };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
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.
|
|
38
|
+
*/
|
|
39
|
+
export async function startStdioServer(stdin, stdout) {
|
|
40
|
+
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
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
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.
|
|
4
|
+
//
|
|
5
|
+
// `createApp()` builds the Express app without binding a port or installing a
|
|
6
|
+
// signal handler (#4854), so a test can serve it on a free port, drive it with
|
|
7
|
+
// 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";
|
|
11
|
+
import express from "express";
|
|
12
|
+
import { createServer } from "../server/index.js";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import cors from "cors";
|
|
15
|
+
import { listenOrExit } from "./listen.js";
|
|
16
|
+
import { InMemoryEventStore } from "./in-memory-event-store.js";
|
|
17
|
+
/** The most bytes of a refused POST's body read to find its request id. */
|
|
18
|
+
const MAX_ID_BODY_BYTES = 64 * 1024;
|
|
19
|
+
/**
|
|
20
|
+
* The JSON-RPC `id` of a POST's body, or `null` when the body is not a single
|
|
21
|
+
* JSON-RPC request (a notification, a response, a batch, any other JSON,
|
|
22
|
+
* malformed JSON, or larger than `MAX_ID_BODY_BYTES`). Used only for a POST that is refused before the SDK
|
|
23
|
+
* reads its body, so the error can still carry the request's id (#4982).
|
|
24
|
+
*/
|
|
25
|
+
async function readRequestId(req) {
|
|
26
|
+
try {
|
|
27
|
+
const chunks = [];
|
|
28
|
+
let size = 0;
|
|
29
|
+
for await (const chunk of req) {
|
|
30
|
+
size += chunk.length;
|
|
31
|
+
if (size > MAX_ID_BODY_BYTES)
|
|
32
|
+
return null;
|
|
33
|
+
chunks.push(chunk);
|
|
34
|
+
}
|
|
35
|
+
const message = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
36
|
+
return isJSONRPCRequest(message) ? message.id : null;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Answer a request whose `Mcp-Session-Id` this app does not know, or has
|
|
44
|
+
* ended: `404 Not Found`, which the spec makes the client's signal to start a
|
|
45
|
+
* new session (#4982). Same shape as the SDK's own "Session not found".
|
|
46
|
+
*/
|
|
47
|
+
function sessionNotFound(res, id = null) {
|
|
48
|
+
res.status(404).json({
|
|
49
|
+
jsonrpc: "2.0",
|
|
50
|
+
error: { code: -32001, message: "Session not found" },
|
|
51
|
+
id,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Build the Streamable HTTP transport's Express app: CORS, the `/mcp` POST,
|
|
56
|
+
* GET and DELETE routes, the map from session id to transport that they
|
|
57
|
+
* share, and the shutdown handler that walks that map.
|
|
58
|
+
*/
|
|
59
|
+
export function createApp() {
|
|
60
|
+
// Express app with permissive CORS for testing with Inspector direct connect mode
|
|
61
|
+
const app = express();
|
|
62
|
+
app.use(cors({
|
|
63
|
+
origin: "*", // use "*" with caution in production
|
|
64
|
+
methods: "GET,POST,DELETE",
|
|
65
|
+
preflightContinue: false,
|
|
66
|
+
optionsSuccessStatus: 204,
|
|
67
|
+
exposedHeaders: [
|
|
68
|
+
"mcp-session-id",
|
|
69
|
+
"last-event-id",
|
|
70
|
+
"mcp-protocol-version",
|
|
71
|
+
],
|
|
72
|
+
}));
|
|
73
|
+
// Map sessionId to server transport for each client
|
|
74
|
+
const transports = new Map();
|
|
75
|
+
// Handle POST requests for client messages
|
|
76
|
+
app.post("/mcp", async (req, res) => {
|
|
77
|
+
console.log("Received MCP POST request");
|
|
78
|
+
try {
|
|
79
|
+
// Check for existing session ID
|
|
80
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
81
|
+
let transport;
|
|
82
|
+
if (sessionId && transports.has(sessionId)) {
|
|
83
|
+
// Reuse existing transport
|
|
84
|
+
transport = transports.get(sessionId);
|
|
85
|
+
}
|
|
86
|
+
else if (!sessionId) {
|
|
87
|
+
const { server, cleanup } = createServer();
|
|
88
|
+
// New initialization request
|
|
89
|
+
const eventStore = new InMemoryEventStore();
|
|
90
|
+
transport = new StreamableHTTPServerTransport({
|
|
91
|
+
sessionIdGenerator: () => randomUUID(),
|
|
92
|
+
eventStore, // Enable resumability
|
|
93
|
+
onsessioninitialized: (sessionId) => {
|
|
94
|
+
// Store the transport by session ID when a session is initialized
|
|
95
|
+
// This avoids race conditions where requests might come in before the session is stored
|
|
96
|
+
console.log(`Session initialized with ID: ${sessionId}`);
|
|
97
|
+
transports.set(sessionId, transport);
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
// Set up onclose handler to clean up transport when closed
|
|
101
|
+
server.server.onclose = async () => {
|
|
102
|
+
const sid = transport.sessionId;
|
|
103
|
+
if (sid && transports.has(sid)) {
|
|
104
|
+
console.log(`Transport closed for session ${sid}, removing from transports map`);
|
|
105
|
+
transports.delete(sid);
|
|
106
|
+
cleanup(sid);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
// Connect the transport to the MCP server BEFORE handling the request
|
|
110
|
+
// so responses can flow back through the same transport
|
|
111
|
+
await server.connect(transport);
|
|
112
|
+
await transport.handleRequest(req, res);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
// A session ID this app does not know, or has already ended
|
|
117
|
+
sessionNotFound(res, await readRequestId(req));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Handle the request with existing transport - no need to reconnect
|
|
121
|
+
// The existing transport is already connected to the server
|
|
122
|
+
await transport.handleRequest(req, res);
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
console.log("Error handling MCP request:", error);
|
|
126
|
+
if (!res.headersSent) {
|
|
127
|
+
res.status(500).json({
|
|
128
|
+
jsonrpc: "2.0",
|
|
129
|
+
error: {
|
|
130
|
+
code: -32603,
|
|
131
|
+
message: "Internal server error",
|
|
132
|
+
},
|
|
133
|
+
id: req?.body?.id,
|
|
134
|
+
});
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
// Handle GET requests for SSE streams
|
|
140
|
+
app.get("/mcp", async (req, res) => {
|
|
141
|
+
console.log("Received MCP GET request");
|
|
142
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
143
|
+
if (!sessionId) {
|
|
144
|
+
res.status(400).json({
|
|
145
|
+
jsonrpc: "2.0",
|
|
146
|
+
error: {
|
|
147
|
+
code: -32000,
|
|
148
|
+
message: "Bad Request: No valid session ID provided",
|
|
149
|
+
},
|
|
150
|
+
id: req?.body?.id,
|
|
151
|
+
});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (!transports.has(sessionId)) {
|
|
155
|
+
sessionNotFound(res);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
// Check for Last-Event-ID header for resumability
|
|
159
|
+
const lastEventId = req.headers["last-event-id"];
|
|
160
|
+
if (lastEventId) {
|
|
161
|
+
console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`);
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
console.log(`Establishing new SSE stream for session ${sessionId}`);
|
|
165
|
+
}
|
|
166
|
+
const transport = transports.get(sessionId);
|
|
167
|
+
await transport.handleRequest(req, res);
|
|
168
|
+
});
|
|
169
|
+
// Handle DELETE requests for session termination
|
|
170
|
+
app.delete("/mcp", async (req, res) => {
|
|
171
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
172
|
+
if (!sessionId) {
|
|
173
|
+
res.status(400).json({
|
|
174
|
+
jsonrpc: "2.0",
|
|
175
|
+
error: {
|
|
176
|
+
code: -32000,
|
|
177
|
+
message: "Bad Request: No valid session ID provided",
|
|
178
|
+
},
|
|
179
|
+
id: req?.body?.id,
|
|
180
|
+
});
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (!transports.has(sessionId)) {
|
|
184
|
+
sessionNotFound(res);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
console.log(`Received session termination request for session ${sessionId}`);
|
|
188
|
+
try {
|
|
189
|
+
const transport = transports.get(sessionId);
|
|
190
|
+
await transport.handleRequest(req, res);
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
console.log("Error handling session termination:", error);
|
|
194
|
+
if (!res.headersSent) {
|
|
195
|
+
res.status(500).json({
|
|
196
|
+
jsonrpc: "2.0",
|
|
197
|
+
error: {
|
|
198
|
+
code: -32603,
|
|
199
|
+
message: "Error handling session termination",
|
|
200
|
+
},
|
|
201
|
+
id: req?.body?.id,
|
|
202
|
+
});
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
// Handle server shutdown
|
|
208
|
+
const shutdown = async () => {
|
|
209
|
+
console.log("Shutting down server...");
|
|
210
|
+
// Close all active transports to properly clean up resources
|
|
211
|
+
// (a snapshot, since closing a transport removes it from the map)
|
|
212
|
+
for (const [sessionId, transport] of [...transports]) {
|
|
213
|
+
try {
|
|
214
|
+
console.log(`Closing transport for session ${sessionId}`);
|
|
215
|
+
await transport.close();
|
|
216
|
+
transports.delete(sessionId);
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
console.log(`Error closing transport for session ${sessionId}:`, error);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
console.log("Server shutdown complete");
|
|
223
|
+
process.exit(0);
|
|
224
|
+
};
|
|
225
|
+
return { app, shutdown };
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Start the Streamable HTTP server as the launcher does: build the app, bind
|
|
229
|
+
* it to `PORT` (default 3001), and install its shutdown handler for SIGINT.
|
|
230
|
+
*/
|
|
231
|
+
export function startStreamableHttpServer() {
|
|
232
|
+
console.log("Starting Streamable HTTP server...");
|
|
233
|
+
const { app, shutdown } = createApp();
|
|
234
|
+
// Start the server
|
|
235
|
+
const PORT = process.env.PORT || 3001;
|
|
236
|
+
const httpServer = listenOrExit(app, PORT, `MCP Streamable HTTP Server listening on port ${PORT}`);
|
|
237
|
+
// Handle server shutdown
|
|
238
|
+
process.on("SIGINT", shutdown);
|
|
239
|
+
return httpServer;
|
|
240
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The version this server reports in `serverInfo`, read from package.json so
|
|
2
|
+
// it cannot drift from the published version (#4472). The TypeScript servers
|
|
3
|
+
// are versioned by changesets, whose "Version Packages" PR edits only
|
|
4
|
+
// package.json and CHANGELOG.md: a version literal in the source would stay
|
|
5
|
+
// behind at the first bump. Same module as `memory` and `sequentialthinking`.
|
|
6
|
+
import { createRequire } from "node:module";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
/**
|
|
10
|
+
* Resolve this package's version from package.json.
|
|
11
|
+
*
|
|
12
|
+
* Works both from source (`src/everything/`) and from the published layout
|
|
13
|
+
* (`dist/`), where package.json lives one directory up.
|
|
14
|
+
*/
|
|
15
|
+
export function resolvePackageVersion() {
|
|
16
|
+
const require = createRequire(import.meta.url);
|
|
17
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
18
|
+
const candidates = [
|
|
19
|
+
path.join(moduleDir, "package.json"),
|
|
20
|
+
path.join(moduleDir, "..", "package.json"),
|
|
21
|
+
];
|
|
22
|
+
for (const candidate of candidates) {
|
|
23
|
+
try {
|
|
24
|
+
const pkg = require(candidate);
|
|
25
|
+
if (pkg.version) {
|
|
26
|
+
return pkg.version;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// Try the next candidate when running from dist/ or source.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw new Error("Could not locate package.json for server version");
|
|
34
|
+
}
|
|
35
|
+
export const SERVER_VERSION = resolvePackageVersion();
|