@jadchene/mcp-gateway-service 0.10.0 → 0.11.2

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 CHANGED
@@ -120,6 +120,7 @@ Stdio remains available when `--http` is enabled.
120
120
  "serviceId": "local-tools",
121
121
  "name": "Local Tools",
122
122
  "confirmationRequiredTools": ["delete_*", "deploy_?"],
123
+ "codexAutoReview": false,
123
124
  "disabledTools": ["internal_*", "legacy_tool"],
124
125
  "transport": {
125
126
  "type": "stdio",
@@ -148,6 +149,7 @@ Stdio remains available when `--http` is enabled.
148
149
  | `enable` | Optional; defaults to `true`. |
149
150
  | `callTimeoutMs` | Optional downstream tool-call timeout; defaults to 120 seconds. |
150
151
  | `confirmationRequiredTools` | Optional unique array of case-sensitive full-name glob patterns. `*` matches zero or more characters and `?` matches one character. The gateway asks the upstream user for form elicitation confirmation before calling a matching tool. |
152
+ | `codexAutoReview` | Optional boolean, defaults to `false`. Set `true` to enable Codex automatic-review metadata for gateway confirmations configured by this service’s `confirmationRequiredTools`. |
151
153
  | `disabledTools` | Optional unique array using the same glob syntax. Matching tools are hidden from tool listing and schema lookup, and calls are rejected before reaching the downstream service. |
152
154
  | `transport.type` | `stdio` or `http`. |
153
155
  | `transport.command` | Required command for a stdio service. |
@@ -168,18 +170,18 @@ The config file is watched for changes. Invalid updates are rejected and the las
168
170
 
169
171
  | Tool | Description |
170
172
  | --- | --- |
171
- | `gateway_list_services` | Searches configured services by identifier or description and can filter by availability. |
173
+ | `gateway_list_services` | Searches enabled services by identifier or description and can filter by availability. |
172
174
  | `gateway_get_service` | Shows one service's connection state, protocol revision, server identity, and recent error. |
173
175
  | `gateway_list_tools` | Searches a service's tools by name or description and can include schemas. |
174
176
  | `gateway_get_tool_schema` | Returns schemas for exact tool names. |
175
177
  | `gateway_manage_service` | Reconnects a service or enables/disables it in the config file. |
176
178
  | `gateway_call_tool` | Calls one downstream tool and returns its MCP result. |
177
179
 
178
- The usual flow is `gateway_list_services` → `gateway_list_tools` → `gateway_get_tool_schema` when needed → `gateway_call_tool`. Pass `{}` to `gateway_call_tool` when the downstream tool has no arguments.
179
-
180
- `gateway_list_services` accepts optional `serviceId` and `desc` string arrays as case-insensitive substring filters. Matches across these two fields use OR. The optional `available` boolean further limits those matches by current availability.
180
+ The usual flow is `gateway_list_services` → `gateway_list_tools` → `gateway_get_tool_schema` when needed → `gateway_call_tool`. Pass `{}` to `gateway_call_tool` when the downstream tool has no arguments.
181
181
 
182
- Calls keep the downstream tool's original side effects and confirmation rules. Tools matching `confirmationRequiredTools` are never invoked until the current MCP session reviews the exact service, tool, and arguments and answers `yes` to the form elicitation; sessions without form elicitation support receive an error. A `no`, decline, or cancel returns an explicit rejection without invoking the downstream tool. An uncertain `gateway_call_tool` failure is never replayed automatically. Enabling or disabling a service with `gateway_manage_service` atomically updates the config file.
182
+ Calls matching `confirmationRequiredTools` show the service, tool, and arguments and require approval in the current MCP session. Clients without form elicitation support cannot invoke them. Calls with uncertain outcomes are not retried automatically.
183
+
184
+ Codex automatic-review integration is disabled by default. Set `"codexAutoReview": true` in the selected `services[]` block to enable approval metadata only for gateway confirmations generated by `confirmationRequiredTools`. Downstream confirmation forms and their `_meta` are forwarded unchanged; downstream automatic-review settings operate independently. Codex uses automatic review when `approvals_reviewer = "auto_review"` is enabled; otherwise, use normal Accept / Decline / Cancel confirmation. Approval remains subject to Codex policy.
183
185
 
184
186
  `disabledTools` takes precedence over `confirmationRequiredTools` when both match. A disabled tool is hidden and rejected immediately without asking for confirmation.
185
187
 
package/README_zh.md CHANGED
@@ -120,6 +120,7 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
120
120
  "serviceId": "local-tools",
121
121
  "name": "Local Tools",
122
122
  "confirmationRequiredTools": ["delete_*", "deploy_?"],
123
+ "codexAutoReview": false,
123
124
  "disabledTools": ["internal_*", "legacy_tool"],
124
125
  "transport": {
125
126
  "type": "stdio",
@@ -148,6 +149,7 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
148
149
  | `enable` | 可选,默认为 `true`。 |
149
150
  | `callTimeoutMs` | 可选,下游工具调用超时;默认 120 秒。 |
150
151
  | `confirmationRequiredTools` | 可选,填写区分大小写的完整工具名 glob 模式;`*` 匹配零个或多个字符,`?` 匹配一个字符。数组项必须唯一且非空,网关在调用匹配的工具前会向上游用户发起表单 elicitation。 |
152
+ | `codexAutoReview` | 可选 boolean,默认 `false`;设为 `true` 仅启用该服务的 `confirmationRequiredTools` 触发的网关自定义确认的 Codex 自动审批元数据。 |
151
153
  | `disabledTools` | 可选,使用相同 glob 语法。匹配的工具不会出现在工具列表和 schema 查询中,调用也会在到达下游服务前被拒绝。 |
152
154
  | `transport.type` | `stdio` 或 `http`。 |
153
155
  | `transport.command` | stdio 服务必填,启动命令。 |
@@ -168,18 +170,18 @@ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
168
170
 
169
171
  | 工具 | 说明 |
170
172
  | --- | --- |
171
- | `gateway_list_services` | 按服务标识或描述搜索已配置服务,并可按可用状态筛选。 |
173
+ | `gateway_list_services` | 按服务标识或描述搜索已启用服务,并可按可用状态筛选。 |
172
174
  | `gateway_get_service` | 查看服务连接状态、协议版本、服务端信息和最近一次错误。 |
173
175
  | `gateway_list_tools` | 按名称或描述搜索服务中的工具,可同时返回 schema。 |
174
176
  | `gateway_get_tool_schema` | 获取准确工具名称对应的 schema。 |
175
177
  | `gateway_manage_service` | 重连服务,或在配置文件中启用、禁用服务。 |
176
178
  | `gateway_call_tool` | 调用一个下游工具并返回 MCP 结果。 |
177
179
 
178
- 通常按 `gateway_list_services` → `gateway_list_tools` → 按需调用 `gateway_get_tool_schema` → `gateway_call_tool` 的顺序使用。下游工具没有参数时,`gateway_call_tool` 的 `arguments` 传 `{}`。
179
-
180
- `gateway_list_services` 可选传入 `serviceId`、`desc` 字符串数组,按不区分大小写的子串匹配,两类文本条件之间为 OR;还可传入 `available` 布尔值,在文本匹配结果上继续按当前可用状态筛选。
180
+ 通常按 `gateway_list_services` → `gateway_list_tools` → 按需调用 `gateway_get_tool_schema` → `gateway_call_tool` 的顺序使用。下游工具没有参数时,`gateway_call_tool` 的 `arguments` 传 `{}`。
181
181
 
182
- 工具调用会保留下游工具原有的副作用和确认规则。匹配 `confirmationRequiredTools` 模式的工具会展示实际服务、工具和完整参数,只有当前 MCP 会话在表单 elicitation 中选择 `yes` 后才会调用;会话不支持表单 elicitation,或用户选择 `no`、拒绝、取消时,网关会返回明确的拒绝结果且不会调用下游工具。状态不确定的 `gateway_call_tool` 失败不会自动重放。通过 `gateway_manage_service` 启用或禁用服务会原子更新配置文件。
182
+ 匹配 `confirmationRequiredTools` 的调用会展示服务、工具和参数,须由当前 MCP 会话确认后才执行;不支持表单确认的客户端无法调用。状态不确定的失败调用不会自动重试。
183
+
184
+ Codex 自动审批扩展默认禁用;在指定服务的 `services[]` 配置块中显式设置 `"codexAutoReview": true`,仅为 `confirmationRequiredTools` 触发的网关自定义确认添加审批元数据。下游确认表单及其 `_meta` 原样透传,下游自动审批配置独立生效。Codex 开启 `approvals_reviewer = "auto_review"` 时自动审查,否则使用正常的 Accept / Decline / Cancel 确认;审批结果仍由 Codex 策略决定。
183
185
 
184
186
  当一个工具同时匹配 `disabledTools` 和 `confirmationRequiredTools` 时,`disabledTools` 优先:工具会被隐藏并直接拒绝,不会发起确认。
185
187
 
@@ -1,45 +1,47 @@
1
- {
2
- "logging": {
3
- "enable": false,
4
- "path": "./logs/mcp-gateway.log",
5
- "maxBytes": 10485760
6
- },
7
- "services": [
8
- {
9
- "serviceId": "demo-echo",
10
- "enable": false,
11
- "name": "Demo Echo Service",
12
- "description": "Sample echo MCP service.",
13
- "callTimeoutMs": 120000,
14
- "confirmationRequiredTools": [
15
- "echo*"
16
- ],
17
- "disabledTools": [
18
- "echo_debug*"
19
- ],
20
- "transport": {
21
- "type": "stdio",
22
- "command": "node",
23
- "args": [
24
- "--experimental-strip-types",
25
- "examples/echo-service.ts"
26
- ],
27
- "inheritEnv": false,
28
- "envAllowlist": []
29
- }
30
- },
31
- {
32
- "serviceId": "remote-http",
33
- "enable": false,
34
- "name": "Remote Streamable HTTP Service",
35
- "description": "Example downstream MCP service over Streamable HTTP.",
36
- "transport": {
37
- "type": "http",
38
- "url": "http://127.0.0.1:3200/mcp",
39
- "headers": {
40
- "Authorization": "Bearer example-token"
41
- }
42
- }
43
- }
44
- ]
45
- }
1
+ {
2
+ "logging": {
3
+ "enable": false,
4
+ "path": "./logs/mcp-gateway.log",
5
+ "maxBytes": 10485760
6
+ },
7
+ "services": [
8
+ {
9
+ "serviceId": "demo-echo",
10
+ "enable": false,
11
+ "name": "Demo Echo Service",
12
+ "description": "Sample echo MCP service.",
13
+ "callTimeoutMs": 120000,
14
+ "confirmationRequiredTools": [
15
+ "echo*"
16
+ ],
17
+ "disabledTools": [
18
+ "echo_debug*"
19
+ ],
20
+ "transport": {
21
+ "type": "stdio",
22
+ "command": "node",
23
+ "args": [
24
+ "--experimental-strip-types",
25
+ "examples/echo-service.ts"
26
+ ],
27
+ "inheritEnv": false,
28
+ "envAllowlist": []
29
+ },
30
+ "codexAutoReview": false
31
+ },
32
+ {
33
+ "serviceId": "remote-http",
34
+ "enable": false,
35
+ "name": "Remote Streamable HTTP Service",
36
+ "description": "Example downstream MCP service over Streamable HTTP.",
37
+ "transport": {
38
+ "type": "http",
39
+ "url": "http://127.0.0.1:3200/mcp",
40
+ "headers": {
41
+ "Authorization": "Bearer example-token"
42
+ }
43
+ },
44
+ "codexAutoReview": false
45
+ }
46
+ ]
47
+ }
package/dist/config.js CHANGED
@@ -85,6 +85,7 @@ function validateServiceConfig(input) {
85
85
  }
86
86
  const serviceId = requireNonEmptyString(input.serviceId, "service.serviceId");
87
87
  const enable = optionalBoolean(input.enable, `service '${serviceId}' enable`) ?? true;
88
+ const codexAutoReview = optionalBoolean(input.codexAutoReview, `service '${serviceId}' codexAutoReview`) ?? false;
88
89
  const name = requireNonEmptyString(input.name, `service '${serviceId}' name`);
89
90
  const description = optionalString(input.description, `service '${serviceId}' description`);
90
91
  const callTimeoutMs = optionalInteger(input.callTimeoutMs, `service '${serviceId}' callTimeoutMs`, 1, 24 * 60 * 60 * 1000);
@@ -93,6 +94,7 @@ function validateServiceConfig(input) {
93
94
  return {
94
95
  serviceId,
95
96
  enable,
97
+ codexAutoReview,
96
98
  name,
97
99
  description,
98
100
  transport: validateTransportConfig(serviceId, input.transport),
@@ -1,4 +1,5 @@
1
1
  import { ToolConfirmationInterceptor } from "./mcp/tool-confirmation.js";
2
+ import { withCodexApprovalMeta } from "./mcp/codex-approval.js";
2
3
  import { matchesAnyToolNamePattern } from "./tool-name-pattern.js";
3
4
  /**
4
5
  * Handles MCP JSON-RPC requests independently of the outer transport.
@@ -54,9 +55,9 @@ export class McpGatewayEngine {
54
55
  * Returns service summaries optionally matching identifiers, descriptions, and availability.
55
56
  */
56
57
  listServices(args) {
57
- const serviceId = optionalUniqueNonEmptyStringArray(args.serviceId, "The 'serviceId' argument must be a unique non-empty string array when provided.");
58
- const desc = optionalUniqueNonEmptyStringArray(args.desc, "The 'desc' argument must be a unique non-empty string array when provided.");
59
- const available = optionalBoolean(args.available, "The 'available' argument must be a boolean when provided.");
58
+ const serviceId = optionalStringOrArray(args.serviceIdFilter, "The 'serviceIdFilter' argument must be a non-empty string or unique non-empty string array when provided.");
59
+ const desc = optionalStringOrArray(args.descFilter, "The 'descFilter' argument must be a non-empty string or unique non-empty string array when provided.");
60
+ const available = optionalBoolean(args.availableFilter, "The 'availableFilter' argument must be a boolean when provided.");
60
61
  const serviceIdKeywords = normalizeKeywords(serviceId);
61
62
  const descriptionKeywords = normalizeKeywords(desc);
62
63
  const services = this.registry.listServices().filter((snapshot) => {
@@ -95,8 +96,8 @@ export class McpGatewayEngine {
95
96
  */
96
97
  listTools(args) {
97
98
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
98
- const toolName = optionalUniqueNonEmptyStringArray(args.toolName, "The 'toolName' argument must be a unique non-empty string array when provided.");
99
- const desc = optionalUniqueNonEmptyStringArray(args.desc, "The 'desc' argument must be a unique non-empty string array when provided.");
99
+ const toolName = optionalStringOrArray(args.toolNameFilter, "The 'toolNameFilter' argument must be a non-empty string or unique non-empty string array when provided.");
100
+ const desc = optionalStringOrArray(args.descFilter, "The 'descFilter' argument must be a non-empty string or unique non-empty string array when provided.");
100
101
  const includeSchema = optionalBoolean(args.includeSchema, "The 'includeSchema' argument must be a boolean when provided.") ?? false;
101
102
  return successContent({
102
103
  tools: this.registry.listTools(serviceId, toolName, desc).map((tool) => {
@@ -117,18 +118,27 @@ export class McpGatewayEngine {
117
118
  */
118
119
  getToolSchema(args) {
119
120
  const serviceId = requireString(args.serviceId, "The 'serviceId' argument must be a string.");
120
- const toolNames = requireUniqueNonEmptyStringArray(args.toolName, "The 'toolName' argument must be a unique non-empty string array.");
121
- const schemas = Object.fromEntries(toolNames.map((toolName) => {
121
+ const toolNames = requireStringOrArray(args.toolName, "The 'toolName' argument must be a non-empty string or unique non-empty string array.");
122
+ const found = [];
123
+ const missing = [];
124
+ for (const toolName of toolNames) {
122
125
  const tool = this.registry.getTool(serviceId, toolName);
123
126
  if (!tool) {
124
- throw new Error(`Unknown tool '${toolName}' in service '${serviceId}'.`);
127
+ missing.push([toolName, `Unknown tool in service '${serviceId}'.`]);
128
+ continue;
125
129
  }
126
- return [toolName, {
130
+ found.push([toolName, {
127
131
  inputSchema: tool.inputSchema ?? null,
128
132
  outputSchema: tool.outputSchema ?? null
129
- }];
130
- }));
131
- return successContent({ schemas });
133
+ }]);
134
+ }
135
+ return {
136
+ ...successContent({
137
+ schemas: Object.fromEntries(found),
138
+ ...(missing.length ? { errors: Object.fromEntries(missing) } : {})
139
+ }),
140
+ ...(found.length === 0 ? { isError: true } : {})
141
+ };
132
142
  }
133
143
  /**
134
144
  * Routes one downstream tool call through the service registry.
@@ -147,7 +157,7 @@ export class McpGatewayEngine {
147
157
  }
148
158
  if (this.toolConfirmation.handlesState(context.requestState)
149
159
  || matchesAnyToolNamePattern(toolName, snapshot?.config.confirmationRequiredTools)) {
150
- return this.toolConfirmation.execute(serviceId, toolName, toolArgs, context, invoke);
160
+ return this.toolConfirmation.execute(serviceId, toolName, toolArgs, context, invoke, (params) => withCodexApprovalMeta(params, context.clientInfo, toolName, toolArgs, serviceId, snapshot?.config.name, snapshot?.config.codexAutoReview === true));
151
161
  }
152
162
  return invoke(context);
153
163
  }
@@ -174,56 +184,56 @@ export function buildGatewayTools(options = {}) {
174
184
  const tools = [
175
185
  {
176
186
  name: "gateway_list_services",
177
- description: "Lists downstream MCP services by case-insensitive identifier or description substring filters and optional availability.",
187
+ description: "Finds enabled services. Text filters use case-insensitive substrings joined by OR; availability further limits matches.",
178
188
  inputSchema: objectSchema([], {
179
- serviceId: uniqueNonEmptyStringArraySchema("Optional unique service identifier substrings. Matching is case-insensitive; identifier and description filters use OR."),
180
- desc: uniqueNonEmptyStringArraySchema("Optional unique description substrings. Matching is case-insensitive; identifier and description filters use OR."),
181
- available: {
189
+ serviceIdFilter: stringOrArraySchema("Service ID keywords."),
190
+ descFilter: stringOrArraySchema("Description keywords."),
191
+ availableFilter: {
182
192
  type: "boolean",
183
- description: "Optionally limits results to services with the requested current availability."
193
+ description: "true: available services; false: unavailable services; omitted or null: either."
184
194
  }
185
195
  }),
186
196
  outputSchema: outputSchemas.listServices
187
197
  },
188
198
  {
189
199
  name: "gateway_get_service",
190
- description: "Returns one downstream service's configured identity, availability, recent error and connection time, protocol version, and server information.",
200
+ description: "Inspects a service's connection status, server metadata, and last error.",
191
201
  inputSchema: objectSchema(["serviceId"], {
192
- serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services.")
202
+ serviceId: stringSchema("Exact, case-sensitive service ID from gateway_list_services.")
193
203
  }),
194
204
  outputSchema: outputSchemas.getService
195
205
  },
196
206
  {
197
207
  name: "gateway_list_tools",
198
- description: "Lists downstream tools by case-insensitive name or description substring filters and optionally includes each matching schema.",
208
+ description: "Finds tools within one service. Text filters use case-insensitive substrings joined by OR.",
199
209
  inputSchema: objectSchema(["serviceId"], {
200
- serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
201
- toolName: uniqueNonEmptyStringArraySchema("Optional unique name substrings. Matching is case-insensitive; any name or description keyword may match."),
202
- 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."),
210
+ serviceId: stringSchema("Exact, case-sensitive service ID from gateway_list_services."),
211
+ toolNameFilter: stringOrArraySchema("Tool name keywords."),
212
+ descFilter: stringOrArraySchema("Description keywords. Matches may include negative guidance."),
203
213
  includeSchema: {
204
214
  type: "boolean",
205
- description: "Includes inputSchema and outputSchema in every returned tool when true. Defaults to false."
215
+ description: "Include inputSchema and outputSchema. Omitted or null: false."
206
216
  }
207
217
  }),
208
218
  outputSchema: outputSchemas.listTools
209
219
  },
210
220
  {
211
221
  name: "gateway_get_tool_schema",
212
- description: "Returns schemas for exact, case-sensitive downstream tool names, keyed by name; the whole request fails when any name is unknown.",
222
+ description: "Returns schemas keyed by tool name. Unknown names appear in errors; valid schemas are retained.",
213
223
  inputSchema: objectSchema(["serviceId", "toolName"], {
214
- serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
215
- toolName: uniqueNonEmptyStringArraySchema("Unique exact, case-sensitive downstream tool names returned by gateway_list_tools.")
224
+ serviceId: stringSchema("Exact, case-sensitive service ID from gateway_list_services."),
225
+ toolName: stringOrArraySchema("Exact, case-sensitive tool names from gateway_list_tools.")
216
226
  }),
217
227
  outputSchema: outputSchemas.getToolSchema
218
228
  },
219
229
  {
220
230
  name: "gateway_manage_service",
221
- description: "Reconnects a downstream service without changing config, or persistently enables or disables it in the gateway config and reloads the registry.",
231
+ description: "Reconnects, enables, or disables a configured service.",
222
232
  inputSchema: objectSchema(["serviceId", "action"], {
223
- serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
233
+ serviceId: stringSchema("Exact, case-sensitive service ID from configuration. Disabled services are absent from gateway_list_services."),
224
234
  action: {
225
235
  type: "string",
226
- description: "reconnect refreshes the connection and metadata without changing config; enable and disable persist the enable flag and reload the registry.",
236
+ description: "reconnect refreshes the connection; enable and disable persist to config.",
227
237
  enum: ["reconnect", "enable", "disable"]
228
238
  }
229
239
  }),
@@ -231,17 +241,31 @@ export function buildGatewayTools(options = {}) {
231
241
  },
232
242
  {
233
243
  name: "gateway_call_tool",
234
- 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.",
244
+ description: "Calls one downstream tool and forwards its result.",
235
245
  inputSchema: objectSchema(["serviceId", "toolName", "arguments"], {
236
- serviceId: stringSchema("Logical downstream service identifier returned by gateway_list_services."),
237
- toolName: stringSchema("Exact, case-sensitive downstream tool name returned by gateway_list_tools."),
246
+ serviceId: stringSchema("Exact, case-sensitive service ID from gateway_list_services."),
247
+ toolName: stringSchema("Exact, case-sensitive tool name from gateway_list_tools."),
238
248
  arguments: {
239
249
  type: "object",
240
- description: "Required arguments object built from the downstream inputSchema. Pass an empty object when the tool has no arguments."
250
+ description: "Downstream tool arguments matching its inputSchema. Use {} for no arguments."
241
251
  }
242
252
  })
243
253
  }
244
254
  ];
255
+ // 可选参数允许显式传 null,运行时统一按未传处理。
256
+ for (const tool of tools) {
257
+ const required = tool.inputSchema.required;
258
+ const properties = tool.inputSchema.properties;
259
+ for (const [name, schema] of Object.entries(properties)) {
260
+ if (!required.includes(name)) {
261
+ const { description, ...shape } = schema;
262
+ properties[name] = {
263
+ ...(description ? { description } : {}),
264
+ ...nullableSchema(shape)
265
+ };
266
+ }
267
+ }
268
+ }
245
269
  return options.includeAdminTools === false
246
270
  ? tools.filter((tool) => tool.name !== "gateway_manage_service")
247
271
  : tools;
@@ -257,16 +281,11 @@ function formatServiceSummary(snapshot) {
257
281
  };
258
282
  }
259
283
  /**
260
- * Builds a standard MCP tool success payload with text and structured content.
284
+ * 返回单份结构化结果,避免在文本内容中重复同一份 JSON。
261
285
  */
262
286
  function successContent(data) {
263
287
  return {
264
- content: [
265
- {
266
- type: "text",
267
- text: JSON.stringify(data, null, 2)
268
- }
269
- ],
288
+ content: [],
270
289
  structuredContent: data
271
290
  };
272
291
  }
@@ -332,11 +351,14 @@ function buildGatewayOutputSchemas() {
332
351
  getToolSchema: objectSchema(["schemas"], {
333
352
  schemas: {
334
353
  type: "object",
335
- minProperties: 1,
336
354
  additionalProperties: objectSchema(["inputSchema", "outputSchema"], {
337
355
  inputSchema: nullableToolSchema,
338
356
  outputSchema: nullableToolSchema
339
357
  })
358
+ },
359
+ errors: {
360
+ type: "object",
361
+ additionalProperties: { type: "string" }
340
362
  }
341
363
  }),
342
364
  manageService: objectSchema(["serviceId", "action", "enabled", "available"], {
@@ -385,6 +407,14 @@ function uniqueNonEmptyStringArraySchema(description) {
385
407
  }
386
408
  };
387
409
  }
410
+ /**
411
+ * 接受单个非空字符串或非空且不重复的字符串数组。
412
+ */
413
+ function stringOrArraySchema(description) {
414
+ const { description: _stringDescription, ...string } = stringSchema(description);
415
+ const { description: _arrayDescription, ...array } = uniqueNonEmptyStringArraySchema(description);
416
+ return { description, anyOf: [string, array] };
417
+ }
388
418
  /**
389
419
  * Ensures the input is a plain object.
390
420
  */
@@ -404,12 +434,15 @@ function requireString(input, message) {
404
434
  return input;
405
435
  }
406
436
  /**
407
- * Returns an optional unique non-empty array of non-empty strings.
437
+ * 将字符串或字符串数组统一为非空且不重复的字符串数组。
408
438
  */
409
- function optionalUniqueNonEmptyStringArray(input, message) {
439
+ function optionalStringOrArray(input, message) {
410
440
  if (input === undefined || input === null) {
411
441
  return undefined;
412
442
  }
443
+ if (typeof input === "string") {
444
+ input = [input];
445
+ }
413
446
  if (!Array.isArray(input)
414
447
  || input.length === 0
415
448
  || input.some((value) => typeof value !== "string" || value.trim() === "")
@@ -419,10 +452,10 @@ function optionalUniqueNonEmptyStringArray(input, message) {
419
452
  return input;
420
453
  }
421
454
  /**
422
- * Returns a required unique non-empty string array.
455
+ * 校验必填字符串或字符串数组并统一返回数组。
423
456
  */
424
- function requireUniqueNonEmptyStringArray(input, message) {
425
- const values = optionalUniqueNonEmptyStringArray(input, message);
457
+ function requireStringOrArray(input, message) {
458
+ const values = optionalStringOrArray(input, message);
426
459
  if (!values) {
427
460
  throw new Error(message);
428
461
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 按 Codex 0.160.0 的私有约定构造审批元数据,不改变服务端权限校验。
3
+ * @author chenjd
4
+ * @created 2026-10-02 22:15:29
5
+ */
6
+ export function buildCodexApprovalMeta(clientInfo, toolName, toolParams, description, sensitive = false) {
7
+ if (typeof clientInfo !== "object" || clientInfo === null || Array.isArray(clientInfo)) {
8
+ return undefined;
9
+ }
10
+ const name = clientInfo.name;
11
+ if (typeof name !== "string" || !/^codex(?:$|[-_])/i.test(name.trim())) {
12
+ return undefined;
13
+ }
14
+ return {
15
+ codex_request_type: "approval_request",
16
+ codex_approval_kind: "mcp_tool_call",
17
+ codex_strict_auto_review: true,
18
+ ...(sensitive ? { codex_sensitive_action: true } : {}),
19
+ tool_name: toolName,
20
+ tool_description: description,
21
+ tool_params: structuredClone(toolParams)
22
+ };
23
+ }
24
+ /** 仅为网关自行生成的空确认表单添加 Codex 扩展。 */
25
+ export function withCodexApprovalMeta(params, clientInfo, toolName, toolParams, serviceId, serviceName, enabled = false) {
26
+ const existing = params._meta ?? {};
27
+ if (!enabled || Object.keys(params.requestedSchema.properties).length > 0
28
+ || existing.codex_requires_user_input === true
29
+ || (existing.codex_approval_kind !== undefined && existing.codex_approval_kind !== "mcp_tool_call")) {
30
+ return params;
31
+ }
32
+ // 网关要求显式确认的调用统一同步审查,避免未知工具提前执行。
33
+ const approvalMeta = buildCodexApprovalMeta(clientInfo, toolName, toolParams, params.message, true);
34
+ if (!approvalMeta)
35
+ return params;
36
+ const meta = {
37
+ ...existing,
38
+ ...approvalMeta,
39
+ connector_id: serviceId,
40
+ connector_name: serviceName ?? serviceId
41
+ };
42
+ delete meta.persist;
43
+ return { ...params, _meta: meta };
44
+ }
@@ -0,0 +1,95 @@
1
+ import { fromJsonSchema } from "@modelcontextprotocol/server";
2
+ /**
3
+ * 保留 SDK 的完整校验和 schema 导出,仅整理输入失败时的提示。
4
+ */
5
+ export function createInputSchema(schema) {
6
+ const base = fromJsonSchema(schema);
7
+ const properties = schema.properties;
8
+ const required = new Set(schema.required);
9
+ const validators = Object.fromEntries(Object.entries(properties).map(([name, field]) => [
10
+ name, fromJsonSchema(field)
11
+ ]));
12
+ return {
13
+ "~standard": {
14
+ ...base["~standard"],
15
+ validate: async (input) => {
16
+ const result = await base["~standard"].validate(input);
17
+ if (!result.issues) {
18
+ return result;
19
+ }
20
+ if (!isObject(input)) {
21
+ return { issues: [{ message: "Arguments must be an object." }] };
22
+ }
23
+ const messages = [];
24
+ for (const name of Object.keys(input)) {
25
+ if (!Object.hasOwn(properties, name)) {
26
+ messages.push(`Unsupported parameter ${JSON.stringify(name)}. Allowed parameters: ${Object.keys(properties).join(", ")}.`);
27
+ }
28
+ }
29
+ for (const [name, field] of Object.entries(properties)) {
30
+ if (input[name] === undefined) {
31
+ if (required.has(name)) {
32
+ messages.push(`Missing required parameter ${JSON.stringify(name)}.`);
33
+ }
34
+ continue;
35
+ }
36
+ const checked = await validators[name]["~standard"].validate(input[name]);
37
+ if (checked.issues) {
38
+ messages.push(`${name}: ${describeInvalid(input[name], field)}`);
39
+ }
40
+ }
41
+ return messages.length ? { issues: messages.map(message => ({ message })) } : result;
42
+ }
43
+ }
44
+ };
45
+ }
46
+ /**
47
+ * 展开网关参数的联合类型,避免把每个分支的错误逐条返回。
48
+ */
49
+ function alternatives(schema) {
50
+ return Array.isArray(schema.anyOf)
51
+ ? schema.anyOf.flatMap(alternatives)
52
+ : [schema];
53
+ }
54
+ /**
55
+ * 按参数 schema 生成可纠正的提示,不回显参数值。
56
+ */
57
+ function describeInvalid(value, schema) {
58
+ const choices = alternatives(schema);
59
+ const type = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
60
+ const branch = choices.find(choice => choice.type === type);
61
+ const expected = choices.map(choice => {
62
+ if (Array.isArray(choice.enum)) {
63
+ return choice.enum.map(item => JSON.stringify(item)).join(" | ");
64
+ }
65
+ if (choice.type === "string" && choice.pattern === "\\S") {
66
+ return "non-blank string";
67
+ }
68
+ if (choice.type === "array") {
69
+ return `${choice.minItems ? "non-empty " : ""}${choice.uniqueItems ? "unique " : ""}string array`;
70
+ }
71
+ return String(choice.type);
72
+ }).join(" or ");
73
+ let reason = "";
74
+ if (branch && Array.isArray(value)) {
75
+ if (typeof branch.minItems === "number" && value.length < branch.minItems) {
76
+ reason = "Array must not be empty. ";
77
+ }
78
+ else if (branch.uniqueItems && new Set(value).size !== value.length) {
79
+ reason = "Array items must be unique. ";
80
+ }
81
+ else if (isObject(branch.items) && branch.items.type === "string") {
82
+ const index = value.findIndex(item => typeof item !== "string" || !item.trim());
83
+ if (index >= 0) {
84
+ reason = `Item at index ${index} must be a non-blank string. `;
85
+ }
86
+ }
87
+ }
88
+ return `${reason}Expected ${expected}.`;
89
+ }
90
+ /**
91
+ * 识别参数对象,排除 null 和数组。
92
+ */
93
+ function isObject(value) {
94
+ return typeof value === "object" && value !== null && !Array.isArray(value);
95
+ }
@@ -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";
@@ -117,6 +117,8 @@ export class SdkMcpClient {
117
117
  const params = {
118
118
  name,
119
119
  arguments: args,
120
+ // 将原始客户端身份随调用传递,由下游自行选择元数据格式。
121
+ ...(context.clientInfo ? { _meta: { [CLIENT_INFO_META_KEY]: structuredClone(context.clientInfo) } } : {}),
120
122
  ...(context.inputResponses ? { inputResponses: context.inputResponses } : {}),
121
123
  ...(context.requestState ? { requestState: context.requestState } : {})
122
124
  };
@@ -1,7 +1,8 @@
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";
5
+ import { createInputSchema } from "./input-schema.js";
5
6
  /**
6
7
  * Creates one SDK server instance with the selected gateway tool surface.
7
8
  */
@@ -29,7 +30,7 @@ export function createGatewayMcpServer(engine, options = {}) {
29
30
  };
30
31
  const server = new McpServer({ name: "mcp-gateway", version: VERSION }, serverOptions);
31
32
  for (const tool of buildGatewayTools(options)) {
32
- const inputSchema = fromJsonSchema(tool.inputSchema);
33
+ const inputSchema = createInputSchema(tool.inputSchema);
33
34
  const outputSchema = tool.outputSchema
34
35
  ? fromJsonSchema(tool.outputSchema)
35
36
  : undefined;
@@ -38,7 +39,7 @@ export function createGatewayMcpServer(engine, options = {}) {
38
39
  inputSchema,
39
40
  ...(outputSchema ? { outputSchema } : {})
40
41
  }, async (args, context) => {
41
- const downstreamContext = toDownstreamContext(context, server.server.getClientCapabilities());
42
+ const downstreamContext = toDownstreamContext(context, server.server.getClientCapabilities(), server.server.getClientVersion());
42
43
  return engine.executeTool(tool.name, args, downstreamContext);
43
44
  });
44
45
  }
@@ -47,9 +48,13 @@ export function createGatewayMcpServer(engine, options = {}) {
47
48
  /**
48
49
  * Extracts request-scoped MRTR, capability, and cancellation state for the downstream call.
49
50
  */
50
- function toDownstreamContext(context, mcp2025ClientCapabilities) {
51
+ function toDownstreamContext(context, mcp2025ClientCapabilities, mcp2025ClientInfo) {
51
52
  const envelope = context.mcpReq.envelope;
52
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;
53
58
  const clientCapabilities = isRecord(envelopeCapabilities)
54
59
  ? envelopeCapabilities
55
60
  : mcp2025ClientCapabilities;
@@ -59,6 +64,7 @@ function toDownstreamContext(context, mcp2025ClientCapabilities) {
59
64
  return {
60
65
  signal: context.mcpReq.signal,
61
66
  ...(clientCapabilities ? { clientCapabilities } : {}),
67
+ ...(clientInfo ? { clientInfo } : {}),
62
68
  ...(context.mcpReq.inputResponses ? { inputResponses: context.mcpReq.inputResponses } : {}),
63
69
  ...(context.mcpReq.requestState() ? { requestState: context.mcpReq.requestState() } : {}),
64
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.10.0",
3
+ "version": "0.11.2",
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",
@@ -1,27 +1,26 @@
1
- ---
2
- name: mcp-gateway
3
- description: Route work through an MCP gateway with token-efficient downstream service discovery, filtered tool search, exact schema lookup, service diagnostics, and forwarded tool calls. Use when an agent needs to find or call tools behind the gateway without loading every downstream schema.
4
- ---
5
-
6
- # MCP Gateway
7
-
8
- Use the gateway as the single entry point for downstream MCP services.
9
-
10
- ## Workflow
11
-
1
+ ---
2
+ name: mcp-gateway
3
+ description: Use when discovering or calling downstream tools through MCP Gateway without loading every tool schema.
4
+ ---
5
+
6
+ # MCP Gateway
7
+
8
+ Use the gateway as the single entry point for downstream MCP services.
9
+
10
+ ## Workflow
11
+
12
12
  1. Reuse an exact `serviceId` already confirmed in the current session; otherwise call `gateway_list_services`.
13
- 2. Reuse an exact downstream tool name already confirmed in the session; otherwise search only that service with `gateway_list_tools`. The unique non-empty `toolName` and `desc` filters are case-insensitive literal substrings joined by OR, so inspect description matches for negative guidance.
14
- 3. Obtain unfamiliar or safety-sensitive schemas with `includeSchema: true` or `gateway_get_tool_schema`; tool names are exact and case-sensitive.
15
- 4. Call `gateway_call_tool` with the confirmed identifiers and an explicit `arguments` object; pass `{}` when the tool has no arguments.
16
- 5. Refresh only the identifier or schema rejected as stale.
17
-
18
- ## Diagnostics and Control
19
-
20
- - Treat `serviceId` as a downstream identifier, never as a gateway-owned tool.
21
- - Use `gateway_get_service` for connection diagnostics. Use `gateway_manage_service` only when explicitly requested: `reconnect` does not change config, while `enable` and `disable` persist.
22
-
23
- ## Safety
24
-
25
- - Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
26
- - Treat gateway failures and structured downstream error results as failures.
27
- - Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.
13
+ 2. Reuse an exact downstream tool name already confirmed in the session; otherwise search only that service with `gateway_list_tools`.
14
+ 3. Obtain unfamiliar or safety-sensitive schemas with `includeSchema: true` or `gateway_get_tool_schema`.
15
+ 4. Call `gateway_call_tool` with the confirmed identifiers and arguments.
16
+ 5. Retain successful batch schemas; resolve only names listed in `errors`. Refresh only stale identifiers or schemas.
17
+
18
+ ## Diagnostics and Control
19
+
20
+ - Treat `serviceId` as a downstream identifier, never as a gateway-owned tool.
21
+ - Use `gateway_get_service` for connection diagnostics. Use `gateway_manage_service` only when explicitly requested: `reconnect` does not change config, while `enable` and `disable` persist.
22
+
23
+ ## Safety
24
+
25
+ - Treat gateway failures and structured downstream error results as failures.
26
+ - Resume an `input_required` result with the returned opaque state and matching input responses.