@jadchene/mcp-gateway-service 0.11.1 → 0.11.3

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,4 +1,4 @@
1
- import { Client, ProtocolError, SdkHttpError } from "@modelcontextprotocol/client";
1
+ import { Client, CLIENT_INFO_META_KEY, ProtocolError, SdkHttpError } from "@modelcontextprotocol/client";
2
2
  import { VERSION } from "../version.js";
3
3
  import { FormElicitationBridge } from "./form-elicitation-bridge.js";
4
4
  import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
@@ -90,8 +90,7 @@ export class SdkMcpClient {
90
90
  * Refreshes server identity and the complete tool catalog.
91
91
  */
92
92
  async getMetadata() {
93
- return this.executeWithRecovery(async () => {
94
- const client = await this.requireClient();
93
+ return this.executeWithRecovery(async (client) => {
95
94
  const tools = await this.requestToolsList(client);
96
95
  return {
97
96
  protocolVersion: client.getNegotiatedProtocolVersion() ?? null,
@@ -106,23 +105,27 @@ export class SdkMcpClient {
106
105
  * Lists the downstream tools using SDK caching and pagination behavior.
107
106
  */
108
107
  async listTools() {
109
- return this.executeWithRecovery(async () => this.requestToolsList(await this.requireClient()));
108
+ return this.executeWithRecovery((client) => this.requestToolsList(client));
110
109
  }
111
110
  /**
112
111
  * Calls a downstream tool while preserving cancellation, custom headers, and MRTR state.
113
112
  */
114
113
  async callTool(name, args, context = {}) {
114
+ let client = null;
115
115
  try {
116
- const client = await this.requireClient();
116
+ client = await this.requireClient();
117
+ const callClient = client;
117
118
  const params = {
118
119
  name,
119
120
  arguments: args,
121
+ // 将原始客户端身份随调用传递,由下游自行选择元数据格式。
122
+ ...(context.clientInfo ? { _meta: { [CLIENT_INFO_META_KEY]: structuredClone(context.clientInfo) } } : {}),
120
123
  ...(context.inputResponses ? { inputResponses: context.inputResponses } : {}),
121
124
  ...(context.requestState ? { requestState: context.requestState } : {})
122
125
  };
123
126
  const invoke = async (signal) => {
124
127
  const callSignal = combineWithTimeout(signal, this.service.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS);
125
- const result = await client.callTool(params, {
128
+ const result = await callClient.callTool(params, {
126
129
  signal: callSignal,
127
130
  allowInputRequired: true,
128
131
  toolDefinition: this.tools.get(name)
@@ -130,20 +133,28 @@ export class SdkMcpClient {
130
133
  return result;
131
134
  };
132
135
  if (client.getProtocolEra() === "legacy") {
133
- return this.formElicitationBridge.execute(name, args, context, invoke);
136
+ return await this.formElicitationBridge.execute(name, args, context, invoke);
134
137
  }
135
138
  const result = await invoke(context.signal ?? new AbortController().signal);
136
139
  return result;
137
140
  }
138
141
  catch (error) {
139
142
  const normalized = normalizeError(error);
143
+ if (this.isSessionExpired(normalized, client)) {
144
+ await this.disposeConnection(client);
145
+ throw new Error(`Downstream session expired while calling '${name}'; the gateway did not replay it. The next call will reconnect. ${normalized.message}`, { cause: normalized });
146
+ }
140
147
  if (isNonRetryable(normalized) || context.signal?.aborted) {
141
148
  throw normalized;
142
149
  }
143
- await this.disposeConnection();
150
+ await this.disposeConnection(client);
144
151
  throw new Error(`Downstream tool '${name}' failed; execution status is unknown and the gateway did not replay it. ${normalized.message}`, { cause: normalized });
145
152
  }
146
153
  }
154
+ /** 判断传输层是否明确报告当前会话已失效,默认传输不作此判断。 */
155
+ isSessionExpired(_error, _client) {
156
+ return false;
157
+ }
147
158
  /**
148
159
  * Connects one fresh SDK client and transport.
149
160
  */
@@ -183,6 +194,7 @@ export class SdkMcpClient {
183
194
  message: error.message
184
195
  });
185
196
  };
197
+ client.onclose = () => this.clearConnection(client);
186
198
  const transport = transportFactory();
187
199
  try {
188
200
  await client.connect(transport, { timeout: CONNECT_TIMEOUT_MS });
@@ -223,22 +235,24 @@ export class SdkMcpClient {
223
235
  return result.tools.map(normalizeToolDefinition);
224
236
  }
225
237
  /**
226
- * Retries transport failures while leaving protocol and HTTP client errors untouched.
238
+ * 重试只读元数据请求的传输或会话错误,保留其他协议及 HTTP 错误。
227
239
  */
228
240
  async executeWithRecovery(operation) {
229
241
  while (true) {
230
242
  if (this.unavailableReason) {
231
243
  throw new Error(this.unavailableReason);
232
244
  }
245
+ let client = null;
233
246
  try {
234
- return await operation();
247
+ client = await this.requireClient();
248
+ return await operation(client);
235
249
  }
236
250
  catch (error) {
237
251
  const normalized = normalizeError(error);
238
- if (isNonRetryable(normalized)) {
252
+ if (isNonRetryable(normalized) && !this.isSessionExpired(normalized, client)) {
239
253
  throw normalized;
240
254
  }
241
- await this.disposeConnection();
255
+ await this.disposeConnection(client);
242
256
  if (this.restartAttempts >= MAX_RESTART_ATTEMPTS) {
243
257
  this.unavailableReason = `Service '${this.key}' is unavailable after ${MAX_RESTART_ATTEMPTS} restart attempts. Last error: ${normalized.message}`;
244
258
  throw new Error(this.unavailableReason);
@@ -253,14 +267,26 @@ export class SdkMcpClient {
253
267
  }
254
268
  }
255
269
  /**
256
- * Closes the active SDK connection and clears derived tool views.
270
+ * 关闭失败请求所属的连接,避免旧请求误关闭已经建立的新连接。
257
271
  */
258
- async disposeConnection() {
259
- this.formElicitationBridge.reset(new Error(`Downstream service '${this.key}' connection was closed.`));
272
+ async disposeConnection(expectedClient) {
260
273
  const client = this.client;
274
+ if (expectedClient !== undefined && client !== expectedClient) {
275
+ return;
276
+ }
277
+ if (client) {
278
+ this.clearConnection(client);
279
+ await client.close().catch(() => undefined);
280
+ }
281
+ }
282
+ /** 清理当前连接的派生状态;已替换连接的关闭事件不影响新连接。 */
283
+ clearConnection(client) {
284
+ if (this.client !== client) {
285
+ return;
286
+ }
287
+ this.formElicitationBridge.reset(new Error(`Downstream service '${this.key}' connection was closed.`));
261
288
  this.client = null;
262
289
  this.tools.clear();
263
- await client?.close().catch(() => undefined);
264
290
  }
265
291
  }
266
292
  /**
@@ -1,4 +1,4 @@
1
- import { CLIENT_CAPABILITIES_META_KEY, McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
1
+ import { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
2
2
  import { buildGatewayTools } from "../gateway-engine.js";
3
3
  import { VERSION } from "../version.js";
4
4
  import { SUPPORTED_MCP_PROTOCOL_VERSIONS } from "./versions.js";
@@ -39,7 +39,7 @@ export function createGatewayMcpServer(engine, options = {}) {
39
39
  inputSchema,
40
40
  ...(outputSchema ? { outputSchema } : {})
41
41
  }, async (args, context) => {
42
- const downstreamContext = toDownstreamContext(context, server.server.getClientCapabilities());
42
+ const downstreamContext = toDownstreamContext(context, server.server.getClientCapabilities(), server.server.getClientVersion());
43
43
  return engine.executeTool(tool.name, args, downstreamContext);
44
44
  });
45
45
  }
@@ -48,9 +48,13 @@ export function createGatewayMcpServer(engine, options = {}) {
48
48
  /**
49
49
  * Extracts request-scoped MRTR, capability, and cancellation state for the downstream call.
50
50
  */
51
- function toDownstreamContext(context, mcp2025ClientCapabilities) {
51
+ function toDownstreamContext(context, mcp2025ClientCapabilities, mcp2025ClientInfo) {
52
52
  const envelope = context.mcpReq.envelope;
53
53
  const envelopeCapabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
54
+ const envelopeClientInfo = envelope?.[CLIENT_INFO_META_KEY];
55
+ const clientInfo = context.mcpReq.envelope
56
+ ? (isRecord(envelopeClientInfo) ? envelopeClientInfo : undefined)
57
+ : mcp2025ClientInfo;
54
58
  const clientCapabilities = isRecord(envelopeCapabilities)
55
59
  ? envelopeCapabilities
56
60
  : mcp2025ClientCapabilities;
@@ -60,6 +64,7 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
60
64
  return {
61
65
  signal: context.mcpReq.signal,
62
66
  ...(clientCapabilities ? { clientCapabilities } : {}),
67
+ ...(clientInfo ? { clientInfo } : {}),
63
68
  ...(context.mcpReq.inputResponses ? { inputResponses: context.mcpReq.inputResponses } : {}),
64
69
  ...(context.mcpReq.requestState() ? { requestState: context.mcpReq.requestState() } : {}),
65
70
  ...(!context.mcpReq.envelope
@@ -31,7 +31,7 @@ export class ToolConfirmationInterceptor {
31
31
  /**
32
32
  * Confirms a fresh invocation or resumes a previously approved downstream round.
33
33
  */
34
- async execute(serviceId, toolName, args, context, invoke) {
34
+ async execute(serviceId, toolName, args, context, invoke, decorateConfirmation) {
35
35
  const requestState = context.requestState;
36
36
  if (requestState?.startsWith(APPROVED_STATE_PREFIX)) {
37
37
  const approved = this.consumeState(this.approvedContinuations, requestState, serviceId, toolName, args);
@@ -54,7 +54,7 @@ export class ToolConfirmationInterceptor {
54
54
  }
55
55
  const state = this.createState(serviceId, toolName, args);
56
56
  this.pending.set(state.requestState, state);
57
- return buildConfirmationRequest(state);
57
+ return buildConfirmationRequest(state, decorateConfirmation);
58
58
  }
59
59
  /**
60
60
  * Consumes the upstream answer before invoking the downstream tool.
@@ -137,29 +137,18 @@ export class ToolConfirmationInterceptor {
137
137
  /**
138
138
  * Creates the modern continuation result; the SDK bridges it for legacy clients.
139
139
  */
140
- function buildConfirmationRequest(state) {
140
+ function buildConfirmationRequest(state, decorateConfirmation) {
141
+ const params = {
142
+ mode: "form",
143
+ message: buildConfirmationMessage(state),
144
+ requestedSchema: { type: "object", properties: {}, additionalProperties: false }
145
+ };
141
146
  return {
142
147
  resultType: "input_required",
143
148
  inputRequests: {
144
149
  [CONFIRMATION_RESPONSE_KEY]: {
145
150
  method: "elicitation/create",
146
- params: {
147
- mode: "form",
148
- message: buildConfirmationMessage(state),
149
- requestedSchema: {
150
- type: "object",
151
- properties: {
152
- decision: {
153
- type: "string",
154
- title: "Run this tool call?",
155
- description: "Choose yes to execute the displayed call or no to reject it.",
156
- enum: ["yes", "no"]
157
- }
158
- },
159
- required: ["decision"],
160
- additionalProperties: false
161
- }
162
- }
151
+ params: decorateConfirmation ? decorateConfirmation(params) : params
163
152
  }
164
153
  },
165
154
  requestState: state.requestState
@@ -176,7 +165,7 @@ function buildConfirmationMessage(state) {
176
165
  "Risk: Gateway policy requires explicit confirmation.",
177
166
  "Arguments:",
178
167
  JSON.stringify(state.args, null, 2),
179
- "Choose yes to execute it or no to reject it."
168
+ "Accept to execute this exact call; decline or cancel to leave it unexecuted."
180
169
  ].join("\n");
181
170
  }
182
171
  /**
@@ -187,12 +176,10 @@ function supportsFormElicitation(capabilities) {
187
176
  return isRecord(elicitation) && isRecord(elicitation.form);
188
177
  }
189
178
  /**
190
- * Treats cancel, decline, malformed content, and a no decision as refusal.
179
+ * 仅在用户接受确认请求时执行;拒绝、取消或缺少响应均不执行。
191
180
  */
192
181
  function isConfirmed(response) {
193
- return response?.action === "accept"
194
- && isRecord(response.content)
195
- && response.content.decision === "yes";
182
+ return response?.action === "accept";
196
183
  }
197
184
  /**
198
185
  * Removes the gateway's private confirmation continuation before the first call.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.11.1",
3
+ "version": "0.11.3",
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",
@@ -23,4 +23,4 @@ Use the gateway as the single entry point for downstream MCP services.
23
23
  ## Safety
24
24
 
25
25
  - Treat gateway failures and structured downstream error results as failures.
26
- - Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.
26
+ - Resume an `input_required` result with the returned opaque state and matching input responses.