@jadchene/mcp-gateway-service 0.4.4 → 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.
@@ -1,5 +1,3 @@
1
- import { jsonRpcError, jsonRpcResult } from "./mcp/protocol.js";
2
- import { VERSION } from "./version.js";
3
1
  /**
4
2
  * Handles MCP JSON-RPC requests independently of the outer transport.
5
3
  */
@@ -8,10 +6,6 @@ export class McpGatewayEngine {
8
6
  * Stores the registry used for metadata lookup and routing.
9
7
  */
10
8
  registry;
11
- /**
12
- * Stores the shared logger instance.
13
- */
14
- logger;
15
9
  /**
16
10
  * Stores the startup barrier that must resolve before gateway tools can use the registry.
17
11
  */
@@ -19,9 +13,8 @@ export class McpGatewayEngine {
19
13
  /**
20
14
  * Creates the transport-neutral gateway engine.
21
15
  */
22
- constructor(registry, logger) {
16
+ constructor(registry, _logger) {
23
17
  this.registry = registry;
24
- this.logger = logger;
25
18
  }
26
19
  /**
27
20
  * Sets the startup barrier used to delay tool handling until the registry is ready.
@@ -30,54 +23,10 @@ export class McpGatewayEngine {
30
23
  this.startupBarrier = barrier;
31
24
  }
32
25
  /**
33
- * Handles one inbound JSON-RPC message and returns a response when the message has an id.
34
- */
35
- async handleMessage(message) {
36
- if (!isJsonRpcRequest(message)) {
37
- return null;
38
- }
39
- return this.handleRequest(message);
40
- }
41
- /**
42
- * Handles one inbound JSON-RPC request.
43
- */
44
- async handleRequest(request) {
45
- try {
46
- if (request.method === "initialize") {
47
- return jsonRpcResult(request.id, this.buildInitializeResult());
48
- }
49
- if (request.method === "ping") {
50
- return jsonRpcResult(request.id, {});
51
- }
52
- if (request.method === "tools/list") {
53
- return jsonRpcResult(request.id, { tools: buildGatewayTools() });
54
- }
55
- if (request.method === "tools/call") {
56
- await this.startupBarrier;
57
- const result = await this.handleToolCall(request);
58
- return jsonRpcResult(request.id, result);
59
- }
60
- if (request.method === "notifications/initialized") {
61
- return null;
62
- }
63
- return jsonRpcError(request.id, -32601, `Unsupported method '${request.method}'.`);
64
- }
65
- catch (error) {
66
- const message = error instanceof Error ? error.message : String(error);
67
- this.logger.error("gateway.request_failed", {
68
- method: request.method,
69
- message
70
- });
71
- return jsonRpcError(request.id, -32000, message);
72
- }
73
- }
74
- /**
75
- * Handles one gateway tool invocation.
26
+ * Executes one registered gateway tool independently of the outer SDK transport.
76
27
  */
77
- async handleToolCall(request) {
78
- const params = toObject(request.params, "The tools/call params must be an object.");
79
- const toolName = requireString(params.name, "The tool name must be a string.");
80
- const args = toObject(params.arguments ?? {}, "The tool arguments must be an object.");
28
+ async executeTool(toolName, args, context = {}) {
29
+ await this.startupBarrier;
81
30
  switch (toolName) {
82
31
  case "gateway_list_services":
83
32
  return successContent({
@@ -92,7 +41,7 @@ export class McpGatewayEngine {
92
41
  case "gateway_manage_service":
93
42
  return this.manageService(args);
94
43
  case "gateway_call_tool":
95
- return this.callDownstreamTool(args);
44
+ return this.callDownstreamTool(args, context);
96
45
  default:
97
46
  throw new Error(`Unknown gateway tool '${toolName}'.`);
98
47
  }
@@ -122,10 +71,11 @@ export class McpGatewayEngine {
122
71
  */
123
72
  listTools(args) {
124
73
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
125
- const toolName = optionalStringArray(args.toolName, "The 'toolName' argument must be a string or string array when provided.");
74
+ const toolName = optionalUniqueNonEmptyStringArray(args.toolName, "The 'toolName' argument must be a unique non-empty string array when provided.");
75
+ const desc = optionalUniqueNonEmptyStringArray(args.desc, "The 'desc' argument must be a unique non-empty string array when provided.");
126
76
  const includeSchema = optionalBoolean(args.includeSchema, "The 'includeSchema' argument must be a boolean when provided.") ?? false;
127
77
  return successContent({
128
- tools: this.registry.listTools(serviceId, toolName).map((tool) => {
78
+ tools: this.registry.listTools(serviceId, toolName, desc).map((tool) => {
129
79
  const summary = {
130
80
  name: tool.name,
131
81
  description: tool.description ?? null
@@ -143,7 +93,7 @@ export class McpGatewayEngine {
143
93
  */
144
94
  getToolSchema(args) {
145
95
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
146
- const toolNames = requireStringArray(args.toolName, "The 'toolName' argument must be a non-empty string or non-empty string array.");
96
+ const toolNames = requireUniqueNonEmptyStringArray(args.toolName, "The 'toolName' argument must be a unique non-empty string array.");
147
97
  const schemas = Object.fromEntries(toolNames.map((toolName) => {
148
98
  const tool = this.registry.getTool(serviceId, toolName);
149
99
  if (!tool) {
@@ -159,11 +109,11 @@ export class McpGatewayEngine {
159
109
  /**
160
110
  * Routes one downstream tool call through the service registry.
161
111
  */
162
- async callDownstreamTool(args) {
112
+ async callDownstreamTool(args, context = {}) {
163
113
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
164
114
  const toolName = requireString(args.toolName, "The 'toolName' argument must be a string.");
165
- const toolArgs = toObject(args.arguments ?? {}, "The 'arguments' field must be an object.");
166
- const call = await this.registry.callTool(serviceId, toolName, toolArgs);
115
+ const toolArgs = toObject(args.arguments, "The 'arguments' field must be an object.");
116
+ const call = await this.registry.callTool(serviceId, toolName, toolArgs, context);
167
117
  return call.result;
168
118
  }
169
119
  /**
@@ -180,114 +130,76 @@ export class McpGatewayEngine {
180
130
  available: result.available
181
131
  });
182
132
  }
183
- /**
184
- * Builds the MCP initialize result advertised by the gateway.
185
- */
186
- buildInitializeResult() {
187
- return {
188
- protocolVersion: "2025-06-18",
189
- capabilities: {
190
- tools: {
191
- listChanged: false
192
- }
193
- },
194
- serverInfo: {
195
- name: "mcp-gateway",
196
- version: VERSION
197
- }
198
- };
199
- }
200
133
  }
201
134
  /**
202
135
  * Builds the fixed gateway tool definitions exposed to all MCP clients.
203
136
  */
204
137
  export function buildGatewayTools() {
138
+ const outputSchemas = buildGatewayOutputSchemas();
205
139
  return [
206
140
  {
207
141
  name: "gateway_list_services",
208
- description: "Lists all MCP services currently managed by the gateway.",
142
+ description: "Lists downstream MCP services with their logical identifiers, descriptions, and current availability.",
209
143
  inputSchema: {
210
144
  type: "object",
211
145
  properties: {},
212
146
  additionalProperties: false
213
- }
147
+ },
148
+ outputSchema: outputSchemas.listServices
214
149
  },
215
150
  {
216
151
  name: "gateway_get_service",
217
- description: "Returns one service summary, runtime state, and metadata cache details.",
152
+ description: "Returns one downstream service's configured identity, availability, recent error and connection time, protocol version, and server information.",
218
153
  inputSchema: objectSchema(["serviceId"], {
219
- serviceId: stringSchema("Logical service identifier.")
220
- })
154
+ serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services.")
155
+ }),
156
+ outputSchema: outputSchemas.getService
221
157
  },
222
158
  {
223
159
  name: "gateway_list_tools",
224
- description: "Lists tools exposed by one downstream service, optionally filtered by name keywords and including their schemas.",
160
+ description: "Lists downstream tools by case-insensitive name or description substring filters and optionally includes each matching schema.",
225
161
  inputSchema: objectSchema(["serviceId"], {
226
- serviceId: stringSchema("Logical service identifier."),
227
- toolName: {
228
- anyOf: [
229
- stringSchema("Optional keyword matched against downstream tool names."),
230
- {
231
- type: "array",
232
- description: "Optional keywords matched against downstream tool names. A tool is returned when any keyword matches.",
233
- items: {
234
- type: "string"
235
- }
236
- }
237
- ]
238
- },
162
+ serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
163
+ toolName: uniqueNonEmptyStringArraySchema("Optional unique name substrings. Matching is case-insensitive; any name or description keyword may match."),
164
+ desc: uniqueNonEmptyStringArraySchema("Optional unique literal description substrings. Matching is case-insensitive and may hit negative guidance, so inspect candidate descriptions. Name and description filters use OR."),
239
165
  includeSchema: {
240
166
  type: "boolean",
241
167
  description: "Includes inputSchema and outputSchema in every returned tool when true. Defaults to false."
242
168
  }
243
- })
169
+ }),
170
+ outputSchema: outputSchemas.listTools
244
171
  },
245
172
  {
246
173
  name: "gateway_get_tool_schema",
247
- description: "Returns input and output schemas for one or more downstream tools, keyed by tool name.",
174
+ description: "Returns schemas for exact, case-sensitive downstream tool names, keyed by name; the whole request fails when any name is unknown.",
248
175
  inputSchema: objectSchema(["serviceId", "toolName"], {
249
- serviceId: stringSchema("Logical service identifier."),
250
- toolName: {
251
- anyOf: [
252
- {
253
- type: "string",
254
- description: "Downstream tool name.",
255
- minLength: 1
256
- },
257
- {
258
- type: "array",
259
- description: "Downstream tool names whose schemas should be returned.",
260
- minItems: 1,
261
- items: {
262
- type: "string",
263
- minLength: 1
264
- }
265
- }
266
- ]
267
- }
268
- })
176
+ serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
177
+ toolName: uniqueNonEmptyStringArraySchema("Unique exact, case-sensitive downstream tool names returned by gateway_list_tools.")
178
+ }),
179
+ outputSchema: outputSchemas.getToolSchema
269
180
  },
270
181
  {
271
182
  name: "gateway_manage_service",
272
- description: "Reconnects one service or updates its enabled state with a compact action.",
183
+ description: "Reconnects a downstream service without changing config, or persistently enables or disables it in the gateway config and reloads the registry.",
273
184
  inputSchema: objectSchema(["serviceId", "action"], {
274
- serviceId: stringSchema("Logical service identifier."),
185
+ serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
275
186
  action: {
276
187
  type: "string",
277
- description: "Management action applied to the service.",
188
+ description: "reconnect refreshes the connection and metadata without changing config; enable and disable persist the enable flag and reload the registry.",
278
189
  enum: ["reconnect", "enable", "disable"]
279
190
  }
280
- })
191
+ }),
192
+ outputSchema: outputSchemas.manageService
281
193
  },
282
194
  {
283
195
  name: "gateway_call_tool",
284
- description: "Calls one downstream tool through the gateway service pool.",
196
+ description: "Calls one exact downstream tool and forwards its result unchanged. The downstream tool may have read or write side effects; inspect its schema and service rules first.",
285
197
  inputSchema: objectSchema(["serviceId", "toolName", "arguments"], {
286
- serviceId: stringSchema("Logical service identifier."),
287
- toolName: stringSchema("Downstream tool name."),
198
+ serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
199
+ toolName: stringSchema("Exact, case-sensitive downstream tool name returned by gateway_list_tools."),
288
200
  arguments: {
289
201
  type: "object",
290
- description: "Arguments passed to the downstream tool."
202
+ description: "Required arguments object built from the downstream inputSchema. Pass an empty object when the tool has no arguments."
291
203
  }
292
204
  })
293
205
  }
@@ -328,13 +240,108 @@ function objectSchema(required, properties) {
328
240
  additionalProperties: false
329
241
  };
330
242
  }
243
+ /**
244
+ * Builds output schemas for gateway tools with stable structured content.
245
+ */
246
+ function buildGatewayOutputSchemas() {
247
+ const nullableString = nullableSchema({ type: "string" });
248
+ const nullableObject = nullableSchema({ type: "object" });
249
+ const nullableToolSchema = nullableSchema({ type: "object" });
250
+ return {
251
+ listServices: objectSchema(["services"], {
252
+ services: {
253
+ type: "array",
254
+ items: objectSchema(["serviceId", "description", "available"], {
255
+ serviceId: { type: "string" },
256
+ description: nullableString,
257
+ available: { type: "boolean" }
258
+ })
259
+ }
260
+ }),
261
+ getService: objectSchema([
262
+ "serviceId",
263
+ "name",
264
+ "description",
265
+ "available",
266
+ "lastError",
267
+ "lastConnectedAt",
268
+ "protocolVersion",
269
+ "serverInfo"
270
+ ], {
271
+ serviceId: { type: "string" },
272
+ name: { type: "string" },
273
+ description: nullableString,
274
+ available: { type: "boolean" },
275
+ lastError: nullableString,
276
+ lastConnectedAt: nullableString,
277
+ protocolVersion: nullableString,
278
+ serverInfo: nullableObject
279
+ }),
280
+ listTools: objectSchema(["tools"], {
281
+ tools: {
282
+ type: "array",
283
+ items: objectSchema(["name", "description"], {
284
+ name: { type: "string" },
285
+ description: nullableString,
286
+ inputSchema: nullableToolSchema,
287
+ outputSchema: nullableToolSchema
288
+ })
289
+ }
290
+ }),
291
+ getToolSchema: objectSchema(["schemas"], {
292
+ schemas: {
293
+ type: "object",
294
+ minProperties: 1,
295
+ additionalProperties: objectSchema(["inputSchema", "outputSchema"], {
296
+ inputSchema: nullableToolSchema,
297
+ outputSchema: nullableToolSchema
298
+ })
299
+ }
300
+ }),
301
+ manageService: objectSchema(["serviceId", "action", "enabled", "available"], {
302
+ serviceId: { type: "string" },
303
+ action: {
304
+ type: "string",
305
+ enum: ["reconnect", "enable", "disable"]
306
+ },
307
+ enabled: { type: "boolean" },
308
+ available: { type: "boolean" }
309
+ })
310
+ };
311
+ }
312
+ /**
313
+ * Builds a schema that accepts the supplied shape or null.
314
+ */
315
+ function nullableSchema(schema) {
316
+ return {
317
+ anyOf: [schema, { type: "null" }]
318
+ };
319
+ }
331
320
  /**
332
321
  * Builds a simple JSON schema string descriptor.
333
322
  */
334
323
  function stringSchema(description) {
335
324
  return {
336
325
  type: "string",
337
- description
326
+ description,
327
+ minLength: 1,
328
+ pattern: "\\S"
329
+ };
330
+ }
331
+ /**
332
+ * Builds a non-empty unique string array descriptor.
333
+ */
334
+ function uniqueNonEmptyStringArraySchema(description) {
335
+ return {
336
+ type: "array",
337
+ description,
338
+ minItems: 1,
339
+ uniqueItems: true,
340
+ items: {
341
+ type: "string",
342
+ minLength: 1,
343
+ pattern: "\\S"
344
+ }
338
345
  };
339
346
  }
340
347
  /**
@@ -356,36 +363,29 @@ function requireString(input, message) {
356
363
  return input;
357
364
  }
358
365
  /**
359
- * Returns optional string keywords, treating blank strings as absent.
366
+ * Returns an optional unique non-empty array of non-empty strings.
360
367
  */
361
- function optionalStringArray(input, message) {
368
+ function optionalUniqueNonEmptyStringArray(input, message) {
362
369
  if (input === undefined || input === null) {
363
370
  return undefined;
364
371
  }
365
- if (typeof input !== "string") {
366
- if (!Array.isArray(input) || input.some((value) => typeof value !== "string")) {
367
- throw new Error(message);
368
- }
369
- const values = input.map((value) => value.trim()).filter((value) => value !== "");
370
- return values.length === 0 ? undefined : values;
372
+ if (!Array.isArray(input)
373
+ || input.length === 0
374
+ || input.some((value) => typeof value !== "string" || value.trim() === "")
375
+ || new Set(input).size !== input.length) {
376
+ throw new Error(message);
371
377
  }
372
- const trimmed = input.trim();
373
- return trimmed === "" ? undefined : trimmed;
378
+ return input;
374
379
  }
375
380
  /**
376
- * Returns one or more required non-empty strings with duplicates removed.
381
+ * Returns a required unique non-empty string array.
377
382
  */
378
- function requireStringArray(input, message) {
379
- if (typeof input === "string") {
380
- if (input.trim() === "") {
381
- throw new Error(message);
382
- }
383
- return [input];
384
- }
385
- if (!Array.isArray(input) || input.length === 0 || input.some((value) => typeof value !== "string" || value.trim() === "")) {
383
+ function requireUniqueNonEmptyStringArray(input, message) {
384
+ const values = optionalUniqueNonEmptyStringArray(input, message);
385
+ if (!values) {
386
386
  throw new Error(message);
387
387
  }
388
- return [...new Set(input)];
388
+ return values;
389
389
  }
390
390
  /**
391
391
  * Returns an optional boolean without coercing other input types.
@@ -408,6 +408,3 @@ function requireServiceAction(input) {
408
408
  }
409
409
  throw new Error("The 'action' argument must be one of 'reconnect', 'enable', or 'disable'.");
410
410
  }
411
- function isJsonRpcRequest(message) {
412
- return "id" in message && "method" in message && typeof message.method === "string";
413
- }
@@ -1,25 +1,13 @@
1
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
1
2
  import { McpGatewayEngine } from "./gateway-engine.js";
2
- import { createMessageReader, createMessageWriter } from "./mcp/protocol.js";
3
+ import { createGatewayMcpServer } from "./mcp/server.js";
3
4
  /**
4
- * Exposes the MCP gateway tools over stdio.
5
+ * Exposes the MCP gateway over stdio through the official SDK v2.
5
6
  */
6
7
  export class GatewayServer {
7
- /**
8
- * Stores the transport-neutral gateway engine.
9
- */
10
8
  engine;
11
- /**
12
- * Stores the shared logger instance.
13
- */
14
9
  logger;
15
- /**
16
- * Stores the stdio message reader bound to the current process.
17
- */
18
- reader = createMessageReader(process.stdin);
19
- /**
20
- * Stores the stdio message writer bound to the current process.
21
- */
22
- writer = createMessageWriter(process.stdout);
10
+ handle = null;
23
11
  /**
24
12
  * Creates the stdio gateway server.
25
13
  */
@@ -34,29 +22,25 @@ export class GatewayServer {
34
22
  this.engine.setStartupBarrier(barrier);
35
23
  }
36
24
  /**
37
- * Starts consuming inbound MCP messages from stdin.
25
+ * Starts the dual-era SDK server on the current process streams.
38
26
  */
39
27
  start() {
40
- this.reader.on("message", (message) => {
41
- const framingMode = this.reader.framingMode;
42
- if (framingMode) {
43
- this.writer.setFramingMode(framingMode);
28
+ if (this.handle) {
29
+ return;
30
+ }
31
+ this.handle = serveStdio(() => createGatewayMcpServer(this.engine), {
32
+ legacy: "serve",
33
+ onerror: (error) => {
34
+ this.logger.error("gateway.protocol_error", { message: error.message });
44
35
  }
45
- void this.handleMessage(message);
46
- });
47
- this.reader.on("error", (error) => {
48
- this.logger.error("gateway.protocol_error", {
49
- message: error instanceof Error ? error.message : String(error)
50
- });
51
36
  });
52
37
  }
53
38
  /**
54
- * Handles one inbound MCP message.
39
+ * Stops the stdio serving entry.
55
40
  */
56
- async handleMessage(message) {
57
- const response = await this.engine.handleMessage(message);
58
- if (response) {
59
- this.writer.write(response);
60
- }
41
+ async stop() {
42
+ const handle = this.handle;
43
+ this.handle = null;
44
+ await handle?.close();
61
45
  }
62
46
  }