@jadchene/mcp-gateway-service 0.5.0 → 0.6.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 +59 -203
- package/README_zh.md +59 -203
- package/config.example.json +5 -6
- package/dist/config.js +17 -17
- package/dist/gateway-engine.js +7 -78
- package/dist/gateway-server.js +17 -33
- package/dist/http-server.js +37 -153
- package/dist/index.js +4 -0
- package/dist/mcp/client.js +61 -567
- package/dist/mcp/http-client.js +24 -473
- package/dist/mcp/sdk-client.js +270 -0
- package/dist/mcp/server.js +68 -0
- package/dist/mcp/versions.js +4 -0
- package/dist/service-registry.js +3 -2
- package/package.json +27 -16
- package/skills/mcp-gateway/SKILL.md +2 -0
- package/dist/mcp/protocol.js +0 -193
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { Client, ProtocolError, SdkHttpError } from "@modelcontextprotocol/client";
|
|
2
|
+
import { VERSION } from "../version.js";
|
|
3
|
+
import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
|
|
4
|
+
const MAX_RESTART_ATTEMPTS = 3;
|
|
5
|
+
const CONNECT_TIMEOUT_MS = 30_000;
|
|
6
|
+
/**
|
|
7
|
+
* Implements shared MCP SDK v2 client behavior for stdio and HTTP transports.
|
|
8
|
+
*/
|
|
9
|
+
export class SdkMcpClient {
|
|
10
|
+
/**
|
|
11
|
+
* Identifies this client in logs.
|
|
12
|
+
*/
|
|
13
|
+
key;
|
|
14
|
+
service;
|
|
15
|
+
logger;
|
|
16
|
+
transportFactory;
|
|
17
|
+
client = null;
|
|
18
|
+
connecting = null;
|
|
19
|
+
restartAttempts = 0;
|
|
20
|
+
unavailableReason = null;
|
|
21
|
+
tools = new Map();
|
|
22
|
+
/**
|
|
23
|
+
* Creates a reusable SDK-backed downstream client.
|
|
24
|
+
*/
|
|
25
|
+
constructor(service, logger, transportFactory) {
|
|
26
|
+
this.service = structuredClone(service);
|
|
27
|
+
this.key = service.serviceId;
|
|
28
|
+
this.logger = logger;
|
|
29
|
+
this.transportFactory = transportFactory;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Indicates whether recovery attempts have been exhausted.
|
|
33
|
+
*/
|
|
34
|
+
get isUnavailable() {
|
|
35
|
+
return this.unavailableReason !== null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Returns the terminal unavailability reason.
|
|
39
|
+
*/
|
|
40
|
+
get unavailableMessage() {
|
|
41
|
+
return this.unavailableReason;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Returns restart attempts consumed by this lifecycle.
|
|
45
|
+
*/
|
|
46
|
+
get restartCount() {
|
|
47
|
+
return this.restartAttempts;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Checks whether this client can be reused after config reload.
|
|
51
|
+
*/
|
|
52
|
+
matchesConfig(service) {
|
|
53
|
+
return JSON.stringify(this.service) === JSON.stringify(service);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Establishes an SDK connection with the configured era negotiation policy.
|
|
57
|
+
*/
|
|
58
|
+
async ensureConnected() {
|
|
59
|
+
if (this.client) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (this.unavailableReason) {
|
|
63
|
+
throw new Error(this.unavailableReason);
|
|
64
|
+
}
|
|
65
|
+
if (this.connecting) {
|
|
66
|
+
return this.connecting;
|
|
67
|
+
}
|
|
68
|
+
this.connecting = this.connectOnce();
|
|
69
|
+
try {
|
|
70
|
+
await this.connecting;
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
this.connecting = null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Closes the SDK client and clears lifecycle errors.
|
|
78
|
+
*/
|
|
79
|
+
async dispose() {
|
|
80
|
+
this.restartAttempts = 0;
|
|
81
|
+
this.unavailableReason = null;
|
|
82
|
+
await this.disposeConnection();
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Refreshes server identity and the complete tool catalog.
|
|
86
|
+
*/
|
|
87
|
+
async getMetadata() {
|
|
88
|
+
return this.executeWithRecovery(async () => {
|
|
89
|
+
const client = await this.requireClient();
|
|
90
|
+
const tools = await this.requestToolsList(client);
|
|
91
|
+
return {
|
|
92
|
+
protocolVersion: client.getNegotiatedProtocolVersion() ?? null,
|
|
93
|
+
protocolEra: client.getProtocolEra() ?? null,
|
|
94
|
+
serverInfo: toJsonObject(client.getServerVersion()),
|
|
95
|
+
tools,
|
|
96
|
+
refreshedAt: new Date().toISOString()
|
|
97
|
+
};
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Lists the downstream tools using SDK caching and pagination behavior.
|
|
102
|
+
*/
|
|
103
|
+
async listTools() {
|
|
104
|
+
return this.executeWithRecovery(async () => this.requestToolsList(await this.requireClient()));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Calls a downstream tool while preserving cancellation, custom headers, and MRTR state.
|
|
108
|
+
*/
|
|
109
|
+
async callTool(name, args, context = {}) {
|
|
110
|
+
return this.executeWithRecovery(async () => {
|
|
111
|
+
const client = await this.requireClient();
|
|
112
|
+
const params = {
|
|
113
|
+
name,
|
|
114
|
+
arguments: args,
|
|
115
|
+
...(context.inputResponses ? { inputResponses: context.inputResponses } : {}),
|
|
116
|
+
...(context.requestState ? { requestState: context.requestState } : {})
|
|
117
|
+
};
|
|
118
|
+
const result = await client.callTool(params, {
|
|
119
|
+
signal: context.signal,
|
|
120
|
+
allowInputRequired: true,
|
|
121
|
+
toolDefinition: this.tools.get(name)
|
|
122
|
+
});
|
|
123
|
+
return result;
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Connects one fresh SDK client and transport.
|
|
128
|
+
*/
|
|
129
|
+
async connectOnce() {
|
|
130
|
+
await this.connectCandidate(this.transportFactory);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Connects one transport candidate with its own protocol negotiation policy.
|
|
134
|
+
*/
|
|
135
|
+
async connectCandidate(transportFactory) {
|
|
136
|
+
const options = {
|
|
137
|
+
supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS],
|
|
138
|
+
capabilities: {
|
|
139
|
+
elicitation: {
|
|
140
|
+
form: {}
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
versionNegotiation: {
|
|
144
|
+
mode: "auto",
|
|
145
|
+
probe: {
|
|
146
|
+
timeoutMs: 5_000
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
inputRequired: {
|
|
150
|
+
autoFulfill: false,
|
|
151
|
+
maxRounds: 8
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const client = new Client({ name: "mcp-gateway", version: VERSION }, options);
|
|
155
|
+
client.onerror = (error) => {
|
|
156
|
+
this.logger.warn("downstream.sdk_error", {
|
|
157
|
+
serviceId: this.key,
|
|
158
|
+
message: error.message
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
const transport = transportFactory();
|
|
162
|
+
try {
|
|
163
|
+
await client.connect(transport, { timeout: CONNECT_TIMEOUT_MS });
|
|
164
|
+
this.client = client;
|
|
165
|
+
this.logger.info("downstream.connected", {
|
|
166
|
+
serviceId: this.key,
|
|
167
|
+
protocolEra: client.getProtocolEra(),
|
|
168
|
+
protocolVersion: client.getNegotiatedProtocolVersion()
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
await client.close().catch(() => undefined);
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Returns the connected client after awaiting any in-flight connection.
|
|
178
|
+
*/
|
|
179
|
+
async requireClient() {
|
|
180
|
+
await this.ensureConnected();
|
|
181
|
+
if (!this.client) {
|
|
182
|
+
throw new Error(`Downstream service '${this.key}' is not connected.`);
|
|
183
|
+
}
|
|
184
|
+
return this.client;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Fetches and stores full SDK tool definitions without simplifying JSON Schema.
|
|
188
|
+
*/
|
|
189
|
+
async requestToolsList(client) {
|
|
190
|
+
const result = await client.listTools();
|
|
191
|
+
this.tools = new Map(result.tools.map((tool) => [tool.name, tool]));
|
|
192
|
+
return result.tools.map(normalizeToolDefinition);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Retries transport failures while leaving protocol and HTTP client errors untouched.
|
|
196
|
+
*/
|
|
197
|
+
async executeWithRecovery(operation) {
|
|
198
|
+
while (true) {
|
|
199
|
+
if (this.unavailableReason) {
|
|
200
|
+
throw new Error(this.unavailableReason);
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
return await operation();
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
const normalized = normalizeError(error);
|
|
207
|
+
if (isNonRetryable(normalized)) {
|
|
208
|
+
throw normalized;
|
|
209
|
+
}
|
|
210
|
+
await this.disposeConnection();
|
|
211
|
+
if (this.restartAttempts >= MAX_RESTART_ATTEMPTS) {
|
|
212
|
+
this.unavailableReason = `Service '${this.key}' is unavailable after ${MAX_RESTART_ATTEMPTS} restart attempts. Last error: ${normalized.message}`;
|
|
213
|
+
throw new Error(this.unavailableReason);
|
|
214
|
+
}
|
|
215
|
+
this.restartAttempts += 1;
|
|
216
|
+
this.logger.warn("downstream.restart_attempt", {
|
|
217
|
+
serviceId: this.key,
|
|
218
|
+
attempt: this.restartAttempts,
|
|
219
|
+
message: normalized.message
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Closes the active SDK connection and clears derived tool views.
|
|
226
|
+
*/
|
|
227
|
+
async disposeConnection() {
|
|
228
|
+
const client = this.client;
|
|
229
|
+
this.client = null;
|
|
230
|
+
this.tools.clear();
|
|
231
|
+
await client?.close().catch(() => undefined);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Preserves the complete MCP tool definition in the gateway metadata view.
|
|
236
|
+
*/
|
|
237
|
+
function normalizeToolDefinition(tool) {
|
|
238
|
+
return {
|
|
239
|
+
name: tool.name,
|
|
240
|
+
title: tool.title,
|
|
241
|
+
description: tool.description,
|
|
242
|
+
inputSchema: tool.inputSchema,
|
|
243
|
+
outputSchema: tool.outputSchema ?? null,
|
|
244
|
+
annotations: tool.annotations,
|
|
245
|
+
icons: tool.icons,
|
|
246
|
+
execution: tool.execution,
|
|
247
|
+
_meta: tool._meta
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Converts optional SDK identity values to the gateway JSON object type.
|
|
252
|
+
*/
|
|
253
|
+
function toJsonObject(input) {
|
|
254
|
+
return input ?? null;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Prevents protocol and explicit HTTP failures from being disguised as reconnects.
|
|
258
|
+
*/
|
|
259
|
+
function isNonRetryable(error) {
|
|
260
|
+
if (error instanceof ProtocolError) {
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
return error instanceof SdkHttpError && error.status >= 400 && error.status < 500;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Normalizes unknown thrown values into Error instances.
|
|
267
|
+
*/
|
|
268
|
+
function normalizeError(error) {
|
|
269
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
270
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { CLIENT_CAPABILITIES_META_KEY, McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
|
|
2
|
+
import { buildGatewayTools } from "../gateway-engine.js";
|
|
3
|
+
import { VERSION } from "../version.js";
|
|
4
|
+
import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
|
|
5
|
+
/**
|
|
6
|
+
* Creates one SDK server instance with all six stable gateway tools.
|
|
7
|
+
*/
|
|
8
|
+
export function createGatewayMcpServer(engine) {
|
|
9
|
+
const options = {
|
|
10
|
+
supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS],
|
|
11
|
+
capabilities: {
|
|
12
|
+
tools: {
|
|
13
|
+
listChanged: false
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
cacheHints: {
|
|
17
|
+
"server/discover": {
|
|
18
|
+
ttlMs: 60_000,
|
|
19
|
+
cacheScope: "public"
|
|
20
|
+
},
|
|
21
|
+
"tools/list": {
|
|
22
|
+
ttlMs: 300_000,
|
|
23
|
+
cacheScope: "public"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
inputRequired: {
|
|
27
|
+
maxRounds: 8
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const server = new McpServer({ name: "mcp-gateway", version: VERSION }, options);
|
|
31
|
+
for (const tool of buildGatewayTools()) {
|
|
32
|
+
const inputSchema = fromJsonSchema(tool.inputSchema);
|
|
33
|
+
const outputSchema = tool.outputSchema
|
|
34
|
+
? fromJsonSchema(tool.outputSchema)
|
|
35
|
+
: undefined;
|
|
36
|
+
server.registerTool(tool.name, {
|
|
37
|
+
description: tool.description,
|
|
38
|
+
inputSchema,
|
|
39
|
+
...(outputSchema ? { outputSchema } : {})
|
|
40
|
+
}, async (args, context) => {
|
|
41
|
+
const downstreamContext = toDownstreamContext(context, server.server.getClientCapabilities());
|
|
42
|
+
return engine.executeTool(tool.name, args, downstreamContext);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
return server;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Extracts request-scoped MRTR, capability, and cancellation state for the downstream call.
|
|
49
|
+
*/
|
|
50
|
+
function toDownstreamContext(context, mcp2025ClientCapabilities) {
|
|
51
|
+
const envelope = context.mcpReq.envelope;
|
|
52
|
+
const envelopeCapabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
|
|
53
|
+
const clientCapabilities = isRecord(envelopeCapabilities)
|
|
54
|
+
? envelopeCapabilities
|
|
55
|
+
: mcp2025ClientCapabilities;
|
|
56
|
+
return {
|
|
57
|
+
signal: context.mcpReq.signal,
|
|
58
|
+
...(clientCapabilities ? { clientCapabilities } : {}),
|
|
59
|
+
...(context.mcpReq.inputResponses ? { inputResponses: context.mcpReq.inputResponses } : {}),
|
|
60
|
+
...(context.mcpReq.requestState() ? { requestState: context.mcpReq.requestState() } : {})
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Checks whether a value is a plain record.
|
|
65
|
+
*/
|
|
66
|
+
function isRecord(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
68
|
+
}
|
package/dist/service-registry.js
CHANGED
|
@@ -135,7 +135,7 @@ export class ServiceRegistry {
|
|
|
135
135
|
/**
|
|
136
136
|
* Calls one downstream tool using the only configured service process.
|
|
137
137
|
*/
|
|
138
|
-
async callTool(serviceId, toolName, args) {
|
|
138
|
+
async callTool(serviceId, toolName, args, context = {}) {
|
|
139
139
|
const snapshot = this.requireService(serviceId);
|
|
140
140
|
const client = this.clients.get(serviceId);
|
|
141
141
|
if (!client) {
|
|
@@ -143,7 +143,7 @@ export class ServiceRegistry {
|
|
|
143
143
|
}
|
|
144
144
|
const startedAt = Date.now();
|
|
145
145
|
try {
|
|
146
|
-
const result = await client.callTool(toolName, args);
|
|
146
|
+
const result = await client.callTool(toolName, args, context);
|
|
147
147
|
this.markServiceAvailable(serviceId, client.restartCount);
|
|
148
148
|
return {
|
|
149
149
|
result,
|
|
@@ -261,6 +261,7 @@ export class ServiceRegistry {
|
|
|
261
261
|
nextClients.set(service.serviceId, client);
|
|
262
262
|
let metadata = {
|
|
263
263
|
protocolVersion: null,
|
|
264
|
+
protocolEra: null,
|
|
264
265
|
serverInfo: null,
|
|
265
266
|
tools: [],
|
|
266
267
|
refreshedAt: null
|
package/package.json
CHANGED
|
@@ -1,29 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jadchene/mcp-gateway-service",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "A token-efficient MCP gateway that provides one unified entry point for multiple downstream MCP services.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"mcp-gateway-service": "dist/index.js"
|
|
9
9
|
},
|
|
10
|
-
"license": "MIT",
|
|
11
|
-
"author": "jadchene",
|
|
12
|
-
"repository": {
|
|
13
|
-
"type": "git",
|
|
14
|
-
"url": "git+https://github.com/jadchene/mcp-gateway.git"
|
|
15
|
-
},
|
|
16
|
-
"homepage": "https://github.com/jadchene/mcp-gateway#readme",
|
|
17
|
-
"bugs": {
|
|
18
|
-
"url": "https://github.com/jadchene/mcp-gateway/issues"
|
|
19
|
-
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"author": "jadchene",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/jadchene/mcp-gateway.git"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/jadchene/mcp-gateway#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/jadchene/mcp-gateway/issues"
|
|
19
|
+
},
|
|
20
20
|
"scripts": {
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
21
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
22
|
+
"prebuild": "npm run clean",
|
|
23
|
+
"build": "tsc -p tsconfig.build.json",
|
|
24
|
+
"dev": "node --experimental-strip-types src/index.ts",
|
|
25
|
+
"start": "node dist/index.js",
|
|
26
|
+
"pretest": "npm run build",
|
|
27
|
+
"test": "node --test --experimental-strip-types test/**/*.test.ts",
|
|
28
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
29
|
+
"verify": "npm run typecheck && npm test",
|
|
25
30
|
"version": "node dist/index.js --version",
|
|
26
|
-
"
|
|
31
|
+
"prepack": "npm run build",
|
|
27
32
|
"prepublishOnly": "npm run build"
|
|
28
33
|
},
|
|
29
34
|
"files": [
|
|
@@ -48,5 +53,11 @@
|
|
|
48
53
|
"devDependencies": {
|
|
49
54
|
"@types/node": "^24.0.0",
|
|
50
55
|
"typescript": "^5.8.0"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@modelcontextprotocol/client": "2.0.0",
|
|
59
|
+
"@modelcontextprotocol/node": "2.0.0",
|
|
60
|
+
"@modelcontextprotocol/server": "2.0.0",
|
|
61
|
+
"zod": "4.4.3"
|
|
51
62
|
}
|
|
52
63
|
}
|
|
@@ -52,6 +52,8 @@ Operate downstream MCP services through the gateway's fixed, token-efficient dis
|
|
|
52
52
|
- `includeSchema` is optional and defaults to `false`. Keep it false for name-only discovery or broad unfiltered inventories.
|
|
53
53
|
- `gateway_get_tool_schema` requires unique exact, case-sensitive names in `toolName` and returns `schemas`, keyed by requested tool name; each value contains `inputSchema` and `outputSchema`.
|
|
54
54
|
- Stable gateway-owned structured results expose `outputSchema`; `gateway_call_tool` omits a fixed output schema and forwards the downstream result unchanged.
|
|
55
|
+
- `gateway_call_tool` may return an MCP `input_required` continuation. Never auto-approve it; obtain the required user input and retry with the returned opaque `requestState` and matching `inputResponses`.
|
|
56
|
+
- Treat downstream `structuredContent` as arbitrary JSON rather than assuming it is an object.
|
|
55
57
|
|
|
56
58
|
## Token-Efficient Strategy
|
|
57
59
|
|
package/dist/mcp/protocol.js
DELETED
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from "node:events";
|
|
2
|
-
/**
|
|
3
|
-
* Provides a framed MCP stdio message reader compatible with both line-delimited and Content-Length transports.
|
|
4
|
-
*/
|
|
5
|
-
export class McpMessageReader extends EventEmitter {
|
|
6
|
-
/**
|
|
7
|
-
* Stores raw bytes that have not yet formed a complete frame.
|
|
8
|
-
*/
|
|
9
|
-
buffer = Buffer.alloc(0);
|
|
10
|
-
/**
|
|
11
|
-
* Stores the configured framing preference.
|
|
12
|
-
*/
|
|
13
|
-
preferredMode;
|
|
14
|
-
/**
|
|
15
|
-
* Stores the framing mode detected from the incoming stream.
|
|
16
|
-
*/
|
|
17
|
-
detectedMode = null;
|
|
18
|
-
/**
|
|
19
|
-
* Starts reading from the provided stream immediately.
|
|
20
|
-
*/
|
|
21
|
-
constructor(stream, preferredMode = "auto") {
|
|
22
|
-
super();
|
|
23
|
-
this.preferredMode = preferredMode;
|
|
24
|
-
stream.on("data", (chunk) => {
|
|
25
|
-
const next = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
|
|
26
|
-
this.buffer = Buffer.concat([this.buffer, next]);
|
|
27
|
-
this.consumeFrames();
|
|
28
|
-
});
|
|
29
|
-
stream.on("error", (error) => this.emit("error", error));
|
|
30
|
-
stream.on("close", () => this.emit("close"));
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Returns the currently selected framing mode when known.
|
|
34
|
-
*/
|
|
35
|
-
get framingMode() {
|
|
36
|
-
return this.preferredMode === "auto" ? this.detectedMode : this.preferredMode;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Attempts to parse as many complete frames as possible from the current buffer.
|
|
40
|
-
*/
|
|
41
|
-
consumeFrames() {
|
|
42
|
-
while (true) {
|
|
43
|
-
const framingMode = this.resolveFramingMode();
|
|
44
|
-
if (!framingMode) {
|
|
45
|
-
return;
|
|
46
|
-
}
|
|
47
|
-
try {
|
|
48
|
-
const payload = framingMode === "content-length"
|
|
49
|
-
? this.readContentLengthPayload()
|
|
50
|
-
: this.readLinePayload();
|
|
51
|
-
if (payload === null) {
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
const message = JSON.parse(payload);
|
|
55
|
-
this.emit("message", message);
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
this.emit("error", error);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Resolves the framing mode using the configured preference or buffered bytes.
|
|
64
|
-
*/
|
|
65
|
-
resolveFramingMode() {
|
|
66
|
-
if (this.preferredMode !== "auto") {
|
|
67
|
-
return this.preferredMode;
|
|
68
|
-
}
|
|
69
|
-
if (this.detectedMode) {
|
|
70
|
-
return this.detectedMode;
|
|
71
|
-
}
|
|
72
|
-
const sample = this.buffer.toString("utf8");
|
|
73
|
-
const trimmed = sample.trimStart();
|
|
74
|
-
if (trimmed.startsWith("Content-Length:")) {
|
|
75
|
-
this.detectedMode = "content-length";
|
|
76
|
-
return this.detectedMode;
|
|
77
|
-
}
|
|
78
|
-
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
79
|
-
this.detectedMode = "line";
|
|
80
|
-
return this.detectedMode;
|
|
81
|
-
}
|
|
82
|
-
return null;
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Reads one Content-Length framed payload when available.
|
|
86
|
-
*/
|
|
87
|
-
readContentLengthPayload() {
|
|
88
|
-
const headerEnd = this.buffer.indexOf("\r\n\r\n");
|
|
89
|
-
if (headerEnd < 0) {
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
const headerText = this.buffer.subarray(0, headerEnd).toString("utf8");
|
|
93
|
-
const lengthMatch = /Content-Length:\s*(\d+)/i.exec(headerText);
|
|
94
|
-
if (!lengthMatch) {
|
|
95
|
-
throw new Error("Missing Content-Length header.");
|
|
96
|
-
}
|
|
97
|
-
const contentLength = Number(lengthMatch[1]);
|
|
98
|
-
const frameStart = headerEnd + 4;
|
|
99
|
-
const frameEnd = frameStart + contentLength;
|
|
100
|
-
if (this.buffer.length < frameEnd) {
|
|
101
|
-
return null;
|
|
102
|
-
}
|
|
103
|
-
const payload = this.buffer.subarray(frameStart, frameEnd).toString("utf8");
|
|
104
|
-
this.buffer = this.buffer.subarray(frameEnd);
|
|
105
|
-
return payload;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Reads one newline-delimited JSON payload when available.
|
|
109
|
-
*/
|
|
110
|
-
readLinePayload() {
|
|
111
|
-
const lineEnd = this.buffer.indexOf("\n");
|
|
112
|
-
if (lineEnd < 0) {
|
|
113
|
-
return null;
|
|
114
|
-
}
|
|
115
|
-
const payload = this.buffer.toString("utf8", 0, lineEnd).replace(/\r$/, "");
|
|
116
|
-
this.buffer = this.buffer.subarray(lineEnd + 1);
|
|
117
|
-
return payload;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Provides a framed MCP stdio message writer compatible with line-delimited and Content-Length transports.
|
|
122
|
-
*/
|
|
123
|
-
export class McpMessageWriter {
|
|
124
|
-
/**
|
|
125
|
-
* Stores the target writable stream.
|
|
126
|
-
*/
|
|
127
|
-
stream;
|
|
128
|
-
/**
|
|
129
|
-
* Stores the active framing mode used for outbound messages.
|
|
130
|
-
*/
|
|
131
|
-
mode;
|
|
132
|
-
/**
|
|
133
|
-
* Creates a writer bound to one writable stream.
|
|
134
|
-
*/
|
|
135
|
-
constructor(stream, mode = "line") {
|
|
136
|
-
this.stream = stream;
|
|
137
|
-
this.mode = mode;
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Updates the framing mode used for future outbound messages.
|
|
141
|
-
*/
|
|
142
|
-
setFramingMode(mode) {
|
|
143
|
-
this.mode = mode;
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Writes one framed JSON-RPC message to the target stream.
|
|
147
|
-
*/
|
|
148
|
-
write(message) {
|
|
149
|
-
const payload = Buffer.from(JSON.stringify(message), "utf8");
|
|
150
|
-
if (this.mode === "content-length") {
|
|
151
|
-
const header = Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, "utf8");
|
|
152
|
-
this.stream.write(Buffer.concat([header, payload]));
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
this.stream.write(Buffer.concat([payload, Buffer.from("\n", "utf8")]));
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Creates a typed message reader.
|
|
160
|
-
*/
|
|
161
|
-
export function createMessageReader(stream, preferredMode = "auto") {
|
|
162
|
-
return new McpMessageReader(stream, preferredMode);
|
|
163
|
-
}
|
|
164
|
-
/**
|
|
165
|
-
* Creates a typed message writer.
|
|
166
|
-
*/
|
|
167
|
-
export function createMessageWriter(stream, mode = "line") {
|
|
168
|
-
return new McpMessageWriter(stream, mode);
|
|
169
|
-
}
|
|
170
|
-
/**
|
|
171
|
-
* Builds one JSON-RPC success response.
|
|
172
|
-
*/
|
|
173
|
-
export function jsonRpcResult(id, result) {
|
|
174
|
-
return {
|
|
175
|
-
jsonrpc: "2.0",
|
|
176
|
-
id,
|
|
177
|
-
result
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Builds one JSON-RPC error response.
|
|
182
|
-
*/
|
|
183
|
-
export function jsonRpcError(id, code, message, data) {
|
|
184
|
-
return {
|
|
185
|
-
jsonrpc: "2.0",
|
|
186
|
-
id,
|
|
187
|
-
error: {
|
|
188
|
-
code,
|
|
189
|
-
message,
|
|
190
|
-
data
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
}
|