@jadchene/mcp-gateway-service 0.6.3 → 0.6.5

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
@@ -2,54 +2,105 @@ English | [简体中文](./README_zh.md)
2
2
 
3
3
  # MCP Gateway
4
4
 
5
- MCP Gateway is a token-efficient Model Context Protocol gateway. It exposes six stable routing tools instead of flattening every downstream tool into each client's startup context.
5
+ ## Introduction
6
6
 
7
- MCP Gateway v0.6.3 uses the official TypeScript SDK v2.
7
+ MCP Gateway puts multiple MCP services behind one endpoint. An agent connects to the gateway and sees six routing tools; downstream services, tools, and schemas are looked up only when they are needed.
8
+
9
+ The project uses the official TypeScript SDK v2 and requires Node.js 24 or later.
8
10
 
9
11
  > [!IMPORTANT]
10
- > MCP Gateway v0.6.2 and later accept only MCP `2026-07-28`, `2025-11-25`, and `2025-06-18`, using standard newline-delimited stdio or single-endpoint Streamable HTTP. Standalone HTTP+SSE (`/sse`), `Content-Length` framing, and other protocol revisions are not supported.
12
+ > MCP Gateway v0.6.2 and later accept only MCP `2026-07-28`, `2025-11-25`, and `2025-06-18`. Supported transports are newline-delimited stdio and single-endpoint Streamable HTTP. Standalone HTTP+SSE (`/sse`), `Content-Length` framing, and other protocol revisions are not supported.
11
13
 
12
- ## Capabilities
14
+ ## Why Use It
13
15
 
14
- - Inbound MCP server over stdio and stateless Streamable HTTP.
15
- - Outbound MCP client over standard stdio and Streamable HTTP.
16
- - Automatic negotiation among MCP `2026-07-28`, `2025-11-25`, and `2025-06-18`.
17
- - All three standard revisions are served automatically on inbound transports.
18
- - Full downstream tool metadata and JSON Schema 2020-12 preservation.
19
- - Form-mode elicitation bridging across all supported revisions, opaque `requestState` forwarding, arbitrary JSON `structuredContent`, cancellation, and `x-mcp-header` handling through the SDK.
20
- - SDK-managed response cache hints and client-local private caches.
21
- - Hot reload, lifecycle recovery, atomic invalid-config rejection, and optional file logging.
22
- - Host and Origin validation for inbound HTTP. Operational logs never use MCP stdout.
16
+ - Keep the agent context small even when many MCP services are configured.
17
+ - Connect the agent once, then add or remove downstream services in the gateway config.
18
+ - Find tools by name or description and load schemas only when required.
19
+ - Use stdio and Streamable HTTP services through the same interface.
20
+ - Reload config changes without restarting the gateway.
23
21
 
24
- ## Requirements and Installation
22
+ ## Quick Start
25
23
 
26
- - Node.js 24 or later.
24
+ ### Install
27
25
 
28
26
  ```bash
29
27
  npm install -g @jadchene/mcp-gateway-service
30
- cp config.example.json config.json
31
- mcp-gateway-service --config ./config.json
32
28
  ```
33
29
 
34
- Enable the additional inbound HTTP endpoint:
30
+ Create `config.json`. Replace `your-mcp-service` with the command of an installed MCP server:
31
+
32
+ ```json
33
+ {
34
+ "services": [
35
+ {
36
+ "serviceId": "tools",
37
+ "name": "Tools",
38
+ "transport": {
39
+ "type": "stdio",
40
+ "command": "your-mcp-service"
41
+ }
42
+ }
43
+ ]
44
+ }
45
+ ```
46
+
47
+ ### Stdio
48
+
49
+ The agent starts the gateway process, so no separate startup command is needed.
50
+
51
+ Codex `config.toml`:
52
+
53
+ ```toml
54
+ [mcp_servers.gateway]
55
+ command = "mcp-gateway-service"
56
+ args = ["--config", "./config.json"]
57
+ ```
58
+
59
+ Claude Code:
35
60
 
36
61
  ```bash
37
- mcp-gateway-service --config ./config.json --http --host 127.0.0.1 --port 3100 --path /mcp
62
+ claude mcp add gateway -- mcp-gateway-service --config ./config.json
63
+ ```
64
+
65
+ ### Streamable HTTP
66
+
67
+ Start the gateway:
68
+
69
+ ```bash
70
+ mcp-gateway-service --http --config ./config.json
71
+ ```
72
+
73
+ The default endpoint is `http://127.0.0.1:3000/mcp`.
74
+
75
+ Codex `config.toml`:
76
+
77
+ ```toml
78
+ [mcp_servers.gateway]
79
+ url = "http://127.0.0.1:3000/mcp"
38
80
  ```
39
81
 
40
- When HTTP is enabled, the process serves both stdio and HTTP. Use `--version` or `-v` to print the installed version.
82
+ Claude Code:
41
83
 
42
- ## Protocol Negotiation
84
+ ```bash
85
+ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
86
+ ```
43
87
 
44
- Protocol selection is automatic. The gateway and its downstream clients prefer MCP `2026-07-28`, then negotiate `2025-11-25` or `2025-06-18` when required by the peer. These are the only accepted protocol revisions. Inbound Streamable HTTP response shaping is selected automatically by the official SDK.
88
+ ## Configuration and Tools
45
89
 
46
- Form-mode elicitation works across all three revisions. A 2025 downstream `elicitation/create` request is forwarded directly to a 2025 upstream client; for a 2026 upstream client, it is converted into `input_required` and resumed with the returned opaque `requestState` and `inputResponses`. Tool calls on each 2025 downstream connection are serialized so form responses cannot cross between calls.
90
+ ### CLI Options
47
91
 
48
- For MCP `2025-11-25`, the gateway negotiates only capabilities it implements. Experimental Tasks, URL-mode elicitation, and sampling tool calls are not advertised.
92
+ | Option | Description | Default |
93
+ | --- | --- | --- |
94
+ | `--config <path>` | Config file path. | `MCP_GATEWAY_CONFIG`, then `./config.json` |
95
+ | `--http` | Enables the Streamable HTTP endpoint. | Disabled |
96
+ | `--host <host>` | HTTP bind address. | `127.0.0.1` |
97
+ | `--port <port>` | HTTP port. | `3000` |
98
+ | `--path <path>` | HTTP endpoint path. | `/mcp` |
99
+ | `--version`, `-v` | Prints the installed version. | — |
49
100
 
50
- ## Service Configuration
101
+ Stdio remains available when `--http` is enabled.
51
102
 
52
- Pass `--config`, set `MCP_GATEWAY_CONFIG`, or place `config.json` in the current directory.
103
+ ### Config File
53
104
 
54
105
  ```json
55
106
  {
@@ -60,94 +111,78 @@ Pass `--config`, set `MCP_GATEWAY_CONFIG`, or place `config.json` in the current
60
111
  "services": [
61
112
  {
62
113
  "serviceId": "local-tools",
63
- "enable": true,
64
114
  "name": "Local Tools",
65
115
  "transport": {
66
116
  "type": "stdio",
67
- "command": "node",
68
- "args": ["./server.js"]
117
+ "command": "your-mcp-service",
118
+ "args": []
69
119
  }
70
120
  },
71
121
  {
72
122
  "serviceId": "remote-tools",
73
- "enable": true,
74
123
  "name": "Remote Tools",
75
124
  "transport": {
76
125
  "type": "http",
77
- "url": "http://127.0.0.1:3200/mcp",
78
- "headers": {
79
- "Authorization": "Bearer example-token"
80
- }
126
+ "url": "http://127.0.0.1:3200/mcp"
81
127
  }
82
128
  }
83
129
  ]
84
130
  }
85
131
  ```
86
132
 
87
- Common fields:
88
-
89
- - `enable` defaults to `true`.
90
- - `logging.enable` defaults to `false`. A relative log path is resolved from the config file directory.
91
- - Stdio always uses the standard newline-delimited JSON-RPC transport.
92
- - HTTP always uses the standard single-endpoint Streamable HTTP transport.
93
- - Protocol revision negotiation is automatic and has no configuration switch.
94
- - Static HTTP headers are supported. Header values and environment secrets are not written to logs.
95
-
96
- ## Inbound Streamable HTTP
97
-
98
- MCP `2026-07-28` HTTP is stateless: each request is an independent `POST /mcp`. The gateway does not create `Mcp-Session-Id` sessions, and `GET`/`DELETE` return `405`. The SDK validates `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`, request metadata, and protocol errors.
99
-
100
- The same endpoint serves MCP `2025-11-25` and `2025-06-18` through their standard stateless Streamable HTTP form. As a downstream client, the gateway preserves a session for either revision when a server issues `Mcp-Session-Id`.
101
-
102
- The default bind address is `127.0.0.1`. Host and Origin checks protect the local endpoint from DNS rebinding. Do not expose it beyond a trusted local network without an authentication layer.
103
-
104
- ## Gateway Tools
105
-
106
- | Tool | Purpose |
133
+ | Field | Description |
107
134
  | --- | --- |
108
- | `gateway_list_services` | List configured downstream services and availability. |
109
- | `gateway_get_service` | Inspect one service's status, protocol version, and server identity. |
110
- | `gateway_list_tools` | Search tool names/descriptions; optionally include schemas. |
111
- | `gateway_get_tool_schema` | Fetch schemas for exact, case-sensitive tool names in one batch. |
112
- | `gateway_manage_service` | Reconnect or persistently enable/disable one configured service. |
113
- | `gateway_call_tool` | Call one downstream tool and preserve its MCP result. |
114
-
115
- Recommended flow:
116
-
117
- 1. Call `gateway_list_services`.
118
- 2. Call `gateway_list_tools` only for the relevant service, using `toolName` and/or `desc` filters.
119
- 3. Reuse schemas returned by `includeSchema: true`, or batch exact names with `gateway_get_tool_schema`.
120
- 4. Call `gateway_call_tool`; always provide `arguments`, using `{}` for a no-argument tool.
121
-
122
- `gateway_call_tool` intentionally has no fixed output schema because downstream `structuredContent` may be any JSON value. MCP `2026-07-28` MRTR results and bridged 2025 form elicitation are returned as `input_required` without automatic approval; the upstream client must declare form elicitation support and retry with matching `inputResponses` and the opaque `requestState`.
135
+ | `services` | List of downstream MCP services. |
136
+ | `serviceId` | Required unique identifier used by gateway tools. |
137
+ | `name` | Required display name. |
138
+ | `description` | Optional service description. |
139
+ | `enable` | Optional; defaults to `true`. |
140
+ | `transport.type` | `stdio` or `http`. |
141
+ | `transport.command` | Required command for a stdio service. |
142
+ | `transport.args` | Optional command arguments for a stdio service. |
143
+ | `transport.cwd` | Optional working directory for a stdio service. |
144
+ | `transport.env` | Optional environment variables for a stdio service. |
145
+ | `transport.url` | Required Streamable HTTP URL for an HTTP service. |
146
+ | `transport.headers` | Optional static headers for an HTTP service. |
147
+ | `logging.enable` | Enables file logging; defaults to `false`. |
148
+ | `logging.path` | Log file path. Relative paths use the config file directory. |
149
+
150
+ The config file is watched for changes. Invalid updates are rejected and the last valid config stays active. See [config.example.json](./config.example.json) for another example.
151
+
152
+ ### Gateway Tools
153
+
154
+ | Tool | Description |
155
+ | --- | --- |
156
+ | `gateway_list_services` | Lists configured services and their availability. |
157
+ | `gateway_get_service` | Shows one service's connection state, protocol revision, server identity, and recent error. |
158
+ | `gateway_list_tools` | Searches a service's tools by name or description and can include schemas. |
159
+ | `gateway_get_tool_schema` | Returns schemas for exact tool names. |
160
+ | `gateway_manage_service` | Reconnects a service or enables/disables it in the config file. |
161
+ | `gateway_call_tool` | Calls one downstream tool and returns its MCP result. |
123
162
 
124
- ## Client Examples
163
+ 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.
125
164
 
126
- Stdio (Codex-style TOML):
165
+ Calls keep the downstream tool's original side effects and confirmation rules. Enabling or disabling a service with `gateway_manage_service` updates the config file.
127
166
 
128
- ```toml
129
- [mcp_servers.gateway]
130
- command = "mcp-gateway-service"
131
- args = ["--config", "./config.json"]
132
- ```
167
+ Agents with Skills support can use the included [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) for the discovery and calling workflow.
133
168
 
134
- Streamable HTTP:
135
-
136
- ```toml
137
- [mcp_servers.gateway]
138
- url = "http://127.0.0.1:3100/mcp"
139
- ```
140
-
141
- ## Development and Verification
169
+ ## Development
142
170
 
143
171
  ```bash
172
+ git clone https://github.com/jadchene/mcp-gateway.git
173
+ cd mcp-gateway
144
174
  npm install
145
175
  npm run verify
146
- node dist/index.js --config ./config.json --version
176
+ npm run dev -- --config ./config.json
147
177
  ```
148
178
 
149
- The repository also ships the public skill at `skills/mcp-gateway/SKILL.md`.
179
+ Build and run the compiled service:
180
+
181
+ ```bash
182
+ npm run build
183
+ npm start -- --config ./config.json
184
+ ```
150
185
 
151
186
  ## License
152
187
 
153
- MIT. See [LICENSE](LICENSE).
188
+ [MIT](./LICENSE)
package/README_zh.md CHANGED
@@ -2,54 +2,105 @@
2
2
 
3
3
  # MCP Gateway
4
4
 
5
- MCP Gateway 是一个节省 token 的 Model Context Protocol 网关。它不把所有下游工具展开到每个客户端的启动上下文,而是通过 6 个稳定工具完成发现、管理和转发。
5
+ ## 简介
6
6
 
7
- MCP Gateway v0.6.3 使用官方 TypeScript SDK v2。
7
+ MCP Gateway 把多个 MCP 服务收拢到一个入口。Agent 连接网关后只会看到 6 个路由工具,具体的下游服务、工具和 schema 在需要时再查询。
8
+
9
+ 项目使用官方 TypeScript SDK v2,需要 Node.js 24 或更高版本。
8
10
 
9
11
  > [!IMPORTANT]
10
- > MCP Gateway v0.6.2 及后续版本仅接受 MCP `2026-07-28`、`2025-11-25` 和 `2025-06-18`,传输方式仅支持标准换行分隔 stdio 和单端点 Streamable HTTP。不支持独立 HTTP+SSE(`/sse`)、`Content-Length` framing 和其他协议版本。
12
+ > MCP Gateway v0.6.2 及后续版本仅接受 MCP `2026-07-28`、`2025-11-25` 和 `2025-06-18`。传输方式仅支持换行分隔 stdio 和单端点 Streamable HTTP。不支持独立 HTTP+SSE(`/sse`)、`Content-Length` framing 和其他协议版本。
11
13
 
12
- ## 能力
14
+ ## 为什么使用
13
15
 
14
- - 上游同时支持 stdio 和无状态 Streamable HTTP。
15
- - 下游支持标准 stdio 和 Streamable HTTP。
16
- - 在 MCP `2026-07-28`、`2025-11-25` 与 `2025-06-18` 之间自动协商。
17
- - 入站传输自动服务这三个标准版本。
18
- - 完整转发下游工具元数据和 JSON Schema 2020-12。
19
- - 在全部受支持版本间桥接表单模式 elicitation,并由 SDK 处理 opaque `requestState`、任意 JSON `structuredContent`、取消传播和 `x-mcp-header`。
20
- - 遵守 SDK 缓存提示,private 缓存按客户端实例隔离。
21
- - 支持配置热更新、生命周期恢复、无效配置原子拒绝和可选文件日志。
22
- - 入站 HTTP 校验 Host 和 Origin;运行日志不会写入 MCP stdout。
16
+ - 即使配置了很多 MCP 服务,也不会一次性占用大量 Agent 上下文。
17
+ - Agent 只需接入一次,后续增减下游服务只改网关配置。
18
+ - 可以按名称或描述查找工具,需要时再读取 schema。
19
+ - Stdio 和 Streamable HTTP 服务使用同一套调用方式。
20
+ - 修改配置文件后自动重载,不必重启网关。
23
21
 
24
- ## 环境与安装
22
+ ## 快速开始
25
23
 
26
- - Node.js 24 或更高版本。
24
+ ### 安装
27
25
 
28
26
  ```bash
29
27
  npm install -g @jadchene/mcp-gateway-service
30
- cp config.example.json config.json
31
- mcp-gateway-service --config ./config.json
32
28
  ```
33
29
 
34
- 额外启用入站 HTTP:
30
+ 创建 `config.json`,将 `your-mcp-service` 替换为已经安装的 MCP 服务命令:
31
+
32
+ ```json
33
+ {
34
+ "services": [
35
+ {
36
+ "serviceId": "tools",
37
+ "name": "Tools",
38
+ "transport": {
39
+ "type": "stdio",
40
+ "command": "your-mcp-service"
41
+ }
42
+ }
43
+ ]
44
+ }
45
+ ```
46
+
47
+ ### Stdio
48
+
49
+ 网关进程由 Agent 启动,不需要单独运行启动命令。
50
+
51
+ Codex `config.toml`:
52
+
53
+ ```toml
54
+ [mcp_servers.gateway]
55
+ command = "mcp-gateway-service"
56
+ args = ["--config", "./config.json"]
57
+ ```
58
+
59
+ Claude Code:
35
60
 
36
61
  ```bash
37
- mcp-gateway-service --config ./config.json --http --host 127.0.0.1 --port 3100 --path /mcp
62
+ claude mcp add gateway -- mcp-gateway-service --config ./config.json
63
+ ```
64
+
65
+ ### Streamable HTTP
66
+
67
+ 启动网关:
68
+
69
+ ```bash
70
+ mcp-gateway-service --http --config ./config.json
71
+ ```
72
+
73
+ 默认地址为 `http://127.0.0.1:3000/mcp`。
74
+
75
+ Codex `config.toml`:
76
+
77
+ ```toml
78
+ [mcp_servers.gateway]
79
+ url = "http://127.0.0.1:3000/mcp"
38
80
  ```
39
81
 
40
- 启用 HTTP 时,进程同时提供 stdio 和 HTTP 入口。使用 `--version` 或 `-v` 查看版本。
82
+ Claude Code:
41
83
 
42
- ## 协议协商
84
+ ```bash
85
+ claude mcp add --transport http gateway http://127.0.0.1:3000/mcp
86
+ ```
43
87
 
44
- 协议选择完全自动:网关及其下游客户端优先协商 MCP `2026-07-28`,并根据对端能力协商 `2025-11-25` 或 `2025-06-18`。只接受这三个协议版本。入站 Streamable HTTP 的响应形态由官方 SDK 自动选择。
88
+ ## 配置与工具
45
89
 
46
- 三个协议版本都支持表单模式 elicitation。2025 下游发出的 `elicitation/create` 会直接转发给 2025 上游客户端;面对 2026 上游客户端时,网关会将其转换为 `input_required`,再使用返回的 opaque `requestState` 和 `inputResponses` 续调。每个 2025 下游连接上的工具调用会串行执行,避免表单响应串到其他调用。
90
+ ### 启动参数
47
91
 
48
- 对于 MCP `2025-11-25`,网关只协商已实现的能力,不声明实验性 Tasks、URL 模式 elicitation 和 sampling 工具调用。
92
+ | 参数 | 说明 | 默认值 |
93
+ | --- | --- | --- |
94
+ | `--config <path>` | 配置文件路径。 | `MCP_GATEWAY_CONFIG`,其次为 `./config.json` |
95
+ | `--http` | 启用 Streamable HTTP。 | 不启用 |
96
+ | `--host <host>` | HTTP 监听地址。 | `127.0.0.1` |
97
+ | `--port <port>` | HTTP 监听端口。 | `3000` |
98
+ | `--path <path>` | HTTP endpoint 路径。 | `/mcp` |
99
+ | `--version`、`-v` | 输出已安装版本。 | — |
49
100
 
50
- ## 服务配置
101
+ 启用 `--http` 后,stdio 入口仍然可用。
51
102
 
52
- 可通过 `--config`、`MCP_GATEWAY_CONFIG` 或当前目录的 `config.json` 指定配置。
103
+ ### 配置文件
53
104
 
54
105
  ```json
55
106
  {
@@ -60,94 +111,78 @@ mcp-gateway-service --config ./config.json --http --host 127.0.0.1 --port 3100 -
60
111
  "services": [
61
112
  {
62
113
  "serviceId": "local-tools",
63
- "enable": true,
64
114
  "name": "Local Tools",
65
115
  "transport": {
66
116
  "type": "stdio",
67
- "command": "node",
68
- "args": ["./server.js"]
117
+ "command": "your-mcp-service",
118
+ "args": []
69
119
  }
70
120
  },
71
121
  {
72
122
  "serviceId": "remote-tools",
73
- "enable": true,
74
123
  "name": "Remote Tools",
75
124
  "transport": {
76
125
  "type": "http",
77
- "url": "http://127.0.0.1:3200/mcp",
78
- "headers": {
79
- "Authorization": "Bearer example-token"
80
- }
126
+ "url": "http://127.0.0.1:3200/mcp"
81
127
  }
82
128
  }
83
129
  ]
84
130
  }
85
131
  ```
86
132
 
87
- 配置要点:
88
-
89
- - `enable` 默认为 `true`。
90
- - `logging.enable` 默认为 `false`;相对日志路径按配置文件所在目录解析。
91
- - stdio 始终使用标准的换行分隔 JSON-RPC 传输。
92
- - HTTP 始终使用标准的单端点 Streamable HTTP 传输。
93
- - 协议版本自动协商,不提供手动切换配置。
94
- - 支持静态 HTTP 请求头;请求头值和环境变量密钥不会写入日志。
95
-
96
- ## 入站 Streamable HTTP
97
-
98
- MCP `2026-07-28` HTTP 是无状态的:每个请求都是独立的 `POST /mcp`。网关不创建 `Mcp-Session-Id`,`GET` 和 `DELETE` 返回 `405`。标准版本头、方法头、名称头、每请求 metadata 和协议错误由 SDK 校验。
99
-
100
- 同一 endpoint 通过标准无状态 Streamable HTTP 服务 MCP `2025-11-25` 和 `2025-06-18`。作为下游客户端,如果任一版本的服务端签发 `Mcp-Session-Id`,网关会按标准维持该 session。
101
-
102
- 默认只绑定 `127.0.0.1`。Host 和 Origin 校验用于防护 DNS rebinding;没有额外认证层时,不应把端口暴露到不可信网络。
103
-
104
- ## 网关工具
105
-
106
- | 工具 | 用途 |
133
+ | 字段 | 说明 |
107
134
  | --- | --- |
108
- | `gateway_list_services` | 列出下游服务和可用状态。 |
109
- | `gateway_get_service` | 查看服务状态、协议版本和服务端身份。 |
110
- | `gateway_list_tools` | 按名称或描述搜索工具,可选返回 schema。 |
111
- | `gateway_get_tool_schema` | 批量获取准确、区分大小写的工具 schema。 |
112
- | `gateway_manage_service` | 重连,或持久化启用/禁用一个服务。 |
113
- | `gateway_call_tool` | 调用一个下游工具并原样转发其 MCP 结果。 |
114
-
115
- 推荐流程:
116
-
117
- 1. 调用 `gateway_list_services`。
118
- 2. 只对相关服务调用 `gateway_list_tools`,使用 `toolName` 和/或 `desc` 缩小范围。
119
- 3. 复用 `includeSchema: true` 返回的 schema;已知准确名称时用 `gateway_get_tool_schema` 一次批量查询。
120
- 4. 使用 `gateway_call_tool` 调用;`arguments` 始终必填,无参数工具传 `{}`。
121
-
122
- `gateway_call_tool` 不声明固定输出 schema,因为下游 `structuredContent` 可以是任意 JSON。MCP `2026-07-28` MRTR 结果和由 2025 表单 elicitation 转换出的 `input_required` 都不会被自动同意;上游必须声明表单 elicitation 支持,并使用匹配的 `inputResponses` 和 opaque `requestState` 重试。
135
+ | `services` | 下游 MCP 服务列表。 |
136
+ | `serviceId` | 必填,网关工具使用的唯一服务标识。 |
137
+ | `name` | 必填,服务名称。 |
138
+ | `description` | 可选,服务说明。 |
139
+ | `enable` | 可选,默认为 `true`。 |
140
+ | `transport.type` | `stdio` 或 `http`。 |
141
+ | `transport.command` | stdio 服务必填,启动命令。 |
142
+ | `transport.args` | stdio 服务的可选命令参数。 |
143
+ | `transport.cwd` | stdio 服务的可选工作目录。 |
144
+ | `transport.env` | stdio 服务的可选环境变量。 |
145
+ | `transport.url` | HTTP 服务必填,Streamable HTTP 地址。 |
146
+ | `transport.headers` | HTTP 服务的可选静态请求头。 |
147
+ | `logging.enable` | 是否写入文件日志,默认为 `false`。 |
148
+ | `logging.path` | 日志文件路径;相对路径按配置文件目录解析。 |
149
+
150
+ 网关会监听配置文件变化。配置有误时不会替换当前配置,服务继续按最后一次有效配置运行。其他示例见 [config.example.json](./config.example.json)。
151
+
152
+ ### 网关工具
153
+
154
+ | 工具 | 说明 |
155
+ | --- | --- |
156
+ | `gateway_list_services` | 列出已配置的服务及其可用状态。 |
157
+ | `gateway_get_service` | 查看服务连接状态、协议版本、服务端信息和最近一次错误。 |
158
+ | `gateway_list_tools` | 按名称或描述搜索服务中的工具,可同时返回 schema。 |
159
+ | `gateway_get_tool_schema` | 获取准确工具名称对应的 schema。 |
160
+ | `gateway_manage_service` | 重连服务,或在配置文件中启用、禁用服务。 |
161
+ | `gateway_call_tool` | 调用一个下游工具并返回 MCP 结果。 |
123
162
 
124
- ## 客户端示例
163
+ 通常按 `gateway_list_services` → `gateway_list_tools` → 按需调用 `gateway_get_tool_schema` → `gateway_call_tool` 的顺序使用。下游工具没有参数时,`gateway_call_tool` 的 `arguments` 传 `{}`。
125
164
 
126
- stdio(Codex 风格 TOML):
165
+ 工具调用会保留下游工具原有的副作用和确认规则。通过 `gateway_manage_service` 启用或禁用服务会修改配置文件。
127
166
 
128
- ```toml
129
- [mcp_servers.gateway]
130
- command = "mcp-gateway-service"
131
- args = ["--config", "./config.json"]
132
- ```
167
+ 支持 Skills 的 Agent 可以使用仓库内置的 [MCP Gateway Skill](./skills/mcp-gateway/SKILL.md) 完成工具发现和调用。
133
168
 
134
- Streamable HTTP:
135
-
136
- ```toml
137
- [mcp_servers.gateway]
138
- url = "http://127.0.0.1:3100/mcp"
139
- ```
140
-
141
- ## 开发与验证
169
+ ## 开发
142
170
 
143
171
  ```bash
172
+ git clone https://github.com/jadchene/mcp-gateway.git
173
+ cd mcp-gateway
144
174
  npm install
145
175
  npm run verify
146
- node dist/index.js --config ./config.json --version
176
+ npm run dev -- --config ./config.json
147
177
  ```
148
178
 
149
- 仓库还包含公开 Skill:`skills/mcp-gateway/SKILL.md`。
179
+ 构建并运行编译产物:
180
+
181
+ ```bash
182
+ npm run build
183
+ npm start -- --config ./config.json
184
+ ```
150
185
 
151
- ## License
186
+ ## 版权声明
152
187
 
153
- MIT. See [LICENSE](LICENSE).
188
+ [MIT](./LICENSE)
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { resolve } from "node:path";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
3
4
  import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
4
5
  import { SdkMcpClient } from "./sdk-client.js";
5
6
  /**
@@ -39,11 +40,24 @@ function createStandardTransport(command, args, cwd, env, logger, serviceId) {
39
40
  /**
40
41
  * Resolves a configured command into a directly spawnable executable on Windows.
41
42
  */
42
- function resolveCommandSpec(command, args) {
43
+ export function resolveCommandSpec(command, args) {
43
44
  if (process.platform !== "win32" || /[\\/]/.test(command) || /\.[A-Za-z0-9]+$/.test(command)) {
44
45
  return { command, args };
45
46
  }
46
- const resolved = resolveViaPowerShell(command) ?? resolveViaWhere(command);
47
+ const candidates = resolveViaWhere(command);
48
+ const native = candidates.find((candidate) => /\.(?:com|exe)$/i.test(candidate));
49
+ if (native) {
50
+ return { command: native, args };
51
+ }
52
+ const commandShim = candidates.find((candidate) => candidate.toLowerCase().endsWith(".cmd"));
53
+ const nodeExecutable = resolveViaWhere("node.exe").find((candidate) => candidate.toLowerCase().endsWith("node.exe"));
54
+ if (commandShim && nodeExecutable) {
55
+ const npmLaunch = resolveWindowsNpmShim(commandShim, nodeExecutable, args);
56
+ if (npmLaunch) {
57
+ return npmLaunch;
58
+ }
59
+ }
60
+ const resolved = resolveViaPowerShell(command);
47
61
  if (!resolved) {
48
62
  return { command, args };
49
63
  }
@@ -53,6 +67,29 @@ function resolveCommandSpec(command, args) {
53
67
  }
54
68
  return { command: resolved, args };
55
69
  }
70
+ /**
71
+ * Converts a standard Windows npm command shim into a directly managed Node.js process.
72
+ */
73
+ export function resolveWindowsNpmShim(shimPath, nodeExecutable, args) {
74
+ try {
75
+ const base = dirname(shimPath);
76
+ const content = readFileSync(shimPath, "utf8");
77
+ const matches = Array.from(content.matchAll(/"%dp0%\\([^"\r\n]+\.js)"/gi));
78
+ const relativeScript = matches.at(-1)?.[1];
79
+ if (!relativeScript) {
80
+ return null;
81
+ }
82
+ const script = resolve(base, relativeScript.replace(/\\/g, "/"));
83
+ const relativePath = relative(base, script);
84
+ if (relativePath.startsWith("..") || isAbsolute(relativePath) || !existsSync(script)) {
85
+ return null;
86
+ }
87
+ return { command: nodeExecutable, args: [script, ...args] };
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
56
93
  /**
57
94
  * Resolves a command name through PowerShell so script shims map to their real targets.
58
95
  */
@@ -82,10 +119,10 @@ function resolveViaWhere(command) {
82
119
  encoding: "utf8",
83
120
  stdio: ["ignore", "pipe", "ignore"]
84
121
  });
85
- return output.split(/\r?\n/).map((line) => line.trim()).find((line) => line && !line.toLowerCase().endsWith(".ps1")) ?? null;
122
+ return output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
86
123
  }
87
124
  catch {
88
- return null;
125
+ return [];
89
126
  }
90
127
  }
91
128
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jadchene/mcp-gateway-service",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
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,104 +1,40 @@
1
1
  ---
2
2
  name: mcp-gateway
3
- description: Use the MCP gateway for token-efficient discovery of downstream services and tools, name or description keyword search through gateway_list_tools, filtered schema inclusion, exact-name batch schema retrieval, and forwarded tool calls. Use when routing work through the gateway, broadening tool discovery, reducing repeated schema calls, or diagnosing a managed service.
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
4
  ---
5
5
 
6
6
  # MCP Gateway
7
7
 
8
- Operate downstream MCP services through the gateway's fixed, token-efficient discovery interface.
8
+ Use the gateway as the single entry point for downstream MCP services.
9
9
 
10
- ## Core Mandates
10
+ ## Routing Workflow
11
11
 
12
- - **Discovery First**: Never guess a `serviceId` or downstream `toolName`. Discover them through the gateway.
13
- - **Token Efficiency**: Keep tool discovery narrow. Use `includeSchema: true` only when schemas are needed for all filtered matches, and reuse schemas returned by the list call.
14
- - **Schema Before Unclear Arguments**: If the tool arguments are not fully certain, fetch the schema before calling the tool. Do not guess argument names, shapes, or confirmation fields.
15
- - **Cache Mentally Per Session**: Reuse known service lists, tool lists, and schemas within the current session instead of asking again without reason.
16
- - **Compression Recovery Gate**: After any context compression event, re-read `AGENTS.md` and this `SKILL.md` before continuing.
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 current session; otherwise call `gateway_list_tools` for only the selected service.
14
+ 3. Filter discovery with unique non-empty `toolName` and/or `desc` string arrays. Treat both filters as case-insensitive literal substring matches joined by OR.
15
+ 4. Obtain the input schema when arguments are unfamiliar, incomplete, or safety-sensitive. Use `includeSchema: true` during filtered discovery or call `gateway_get_tool_schema` with exact case-sensitive tool names.
16
+ 5. Call `gateway_call_tool` with the confirmed `serviceId`, exact `toolName`, and an explicit `arguments` object. Pass `{}` for a no-argument tool.
17
+ 6. Refresh only stale service, tool, or schema information after an unknown-identifier or validation failure.
17
18
 
18
- ## Required Workflow
19
+ ## Discovery Rules
19
20
 
20
- 1. Call `gateway_list_services` once to find the right downstream service.
21
- 2. Call `gateway_list_tools(serviceId)` only for the selected service. Use optional unique non-empty `toolName` and `desc` string arrays for case-insensitive literal substring matching. Description matches may come from negative guidance, so inspect the returned descriptions before selecting.
22
- 3. Pass `includeSchema: true` when every filtered match needs its schema, such as when comparing argument contracts or preparing to call multiple matches.
23
- 4. If selected schemas were not returned by the list call, call `gateway_get_tool_schema(serviceId, toolName)` with a unique non-empty array of exact, case-sensitive names before first use or whenever arguments remain uncertain. The whole request fails if any name is unknown; use a one-element array for one tool.
24
- 5. Call `gateway_call_tool(serviceId, toolName, arguments)` for execution. Always pass an explicit arguments object, using `{}` for no-argument tools, and treat downstream side effects according to the matched service rules.
25
- 6. Re-discover only when a call fails, service availability changes, or the task clearly requires fresh metadata.
21
+ - Never guess a service identifier, tool name, or argument shape.
22
+ - Treat `serviceId` as a downstream identifier returned by `gateway_list_services`; never use a gateway-owned tool name as a service identifier.
23
+ - Search only the relevant service instead of collecting every downstream tool.
24
+ - Inspect description matches because negative guidance may also contain the search term.
25
+ - Reuse schemas returned by `gateway_list_tools(includeSchema: true)` instead of fetching them again.
26
+ - Batch exact names in one `gateway_get_tool_schema` call when several selected tools need schemas.
27
+ - Treat downstream `structuredContent` as arbitrary JSON.
26
28
 
27
- ## Diagnostic Exception
29
+ ## Diagnostics and Control
28
30
 
29
- - Treat `gateway_get_service` as a diagnostic tool, not part of the default workflow.
30
- - Use it only when the user explicitly asks to inspect service health, connection state, protocol details, or recent service errors.
31
- - Do not call it during normal routing when service discovery, filtered tool discovery, and execution are sufficient.
32
- - Treat `gateway_manage_service` as an explicit service-control tool, not part of the default workflow.
33
- - Use `gateway_manage_service({ serviceId, action: "reconnect" })` only when the user explicitly wants to retry starting a failed service after its dependency becomes ready.
34
- - Use `gateway_manage_service({ serviceId, action: "enable" | "disable" })` only when the user explicitly wants to persistently change that service's enabled state in the config file.
31
+ - Use `gateway_get_service` only when connection state, protocol details, server identity, or recent errors matter.
32
+ - Use `gateway_manage_service` only when the user explicitly requests reconnecting, enabling, or disabling a service.
33
+ - Treat `reconnect` as a connection refresh that does not change config.
34
+ - Treat `enable` and `disable` as persistent config changes.
35
35
 
36
- ## Strict Argument Rule
36
+ ## Safety
37
37
 
38
- - Treat every `serviceId` argument accepted by `gateway_*` tools as a downstream service identifier returned by `gateway_list_services`. Never pass `gateway`, a gateway-owned tool name, or any inferred self-reference as `serviceId`.
39
- - If a tool has any non-trivial arguments, optional flags, confirmation fields, enum values, or write-safety fields, obtain its schema through `gateway_list_tools(..., includeSchema: true)` or `gateway_get_tool_schema` before execution unless the exact argument contract is already confirmed in the current session.
40
- - Treat a schema returned by `gateway_list_tools(includeSchema: true)` as authoritative for that tool. Do not immediately repeat the same lookup with `gateway_get_tool_schema`.
41
- - When exact names for several selected tools are already known, pass them in one `gateway_get_tool_schema` array instead of making one call per tool.
42
- - Apply gateway discovery, schema, management, and routing tools only to downstream services and downstream tools. Do not use them to inspect or call gateway-owned tools such as `gateway_list_tools` or `gateway_call_tool`; gateway-owned tool schemas come from the MCP client's current gateway tool definitions.
43
- - Do not rely on tool descriptions alone when the argument shape could affect correctness or safety.
44
- - This is especially important for write tools, confirmation-based tools, and tools with nested argument objects.
45
-
46
- ## Response Shape Expectations
47
-
48
- - `gateway_list_services` returns compact service entries with `serviceId`, `description`, and `available`.
49
- - `gateway_list_tools` returns compact tool entries with `name` and `description`. Optional `toolName` and `desc` must be unique non-empty string arrays; they match literal name and description substrings respectively, case-insensitively.
50
- - When both `toolName` and `desc` are present, return the union: a tool matches when its name or description contains any supplied keyword.
51
- - `gateway_list_tools` includes `inputSchema` and `outputSchema` in every matching entry when `includeSchema` is true.
52
- - `includeSchema` is optional and defaults to `false`. Keep it false for name-only discovery or broad unfiltered inventories.
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
- - 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, including one converted from a 2025 downstream form elicitation. 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.
57
-
58
- ## Token-Efficient Strategy
59
-
60
- - Start with the smallest discovery call that can answer the current question.
61
- - Avoid listing tools for multiple services when the target domain is already obvious.
62
- - Use `desc` when task language is more likely to appear in tool descriptions than tool names. Combine it with `toolName` to broaden discovery without requesting the full inventory.
63
- - Combine `toolName` filtering with `includeSchema: true` when multiple likely matches all need schema inspection; this replaces one list call plus repeated schema calls with one request.
64
- - Keep `includeSchema` false when only names and descriptions are needed, or when an unfiltered service exposes many tools.
65
- - When exact selected tool names are known and their schemas were omitted from discovery, fetch one or several in a single `gateway_get_tool_schema` call.
66
- - Never fetch a tool schema again in the same session when the list response already supplied it, unless metadata may have changed.
67
-
68
- ## Common Patterns
69
-
70
- - Need a service for one task domain:
71
- - `gateway_list_services`
72
- - choose the most relevant `serviceId`
73
- - `gateway_list_tools({ serviceId: "selected-service", toolName: ["optional-keyword"] })`
74
- - `gateway_list_tools({ serviceId: "selected-service", toolName: ["keyword-a", "keyword-b"] })`
75
- - `gateway_list_tools({ serviceId: "selected-service", toolName: ["name-keyword"], desc: ["description phrase"] })`
76
- - add `includeSchema: true` to either list call when every match needs schema inspection
77
- - otherwise call `gateway_get_tool_schema` after selecting exact tool names
78
- - `gateway_call_tool({ serviceId: "selected-service", toolName: "selected-tool", arguments: {...} })`
79
-
80
- - Need to inspect several filtered candidates before choosing or calling them:
81
- - `gateway_list_tools({ serviceId: "selected-service", toolName: ["candidate-a", "candidate-b"], includeSchema: true })`
82
- - compare or reuse the returned `inputSchema` and `outputSchema` without separate schema calls
83
-
84
- - Need schemas for exact selected tools whose schemas were not included in discovery:
85
- - `gateway_get_tool_schema({ serviceId: "selected-service", toolName: ["selected-tool"] })`
86
- - or `gateway_get_tool_schema({ serviceId: "selected-service", toolName: ["selected-tool-a", "selected-tool-b"] })`
87
- - read each result from `schemas[toolName]`
88
- - build arguments strictly from `inputSchema`
89
- - call the tool only after the schema is understood
90
-
91
- ## Prohibited Patterns
92
-
93
- - **Never** flatten all downstream tools into your own notes unless the task explicitly needs a full inventory.
94
- - **Never** invent arguments for a tool when the schema can be queried cheaply.
95
- - **Never** proceed without a schema from `gateway_list_tools(..., includeSchema: true)` or `gateway_get_tool_schema` when argument names or fields are unclear.
96
- - **Never** omit `gateway_call_tool.arguments`; pass `{}` when the downstream input schema has no properties.
97
- - **Never** assume a service is available without checking recent gateway discovery results when availability matters.
98
-
99
- ## Practical Guidance
100
-
101
- - Choose `serviceId` by task domain and service description instead of assuming a fixed service naming scheme.
102
- - Prefer the smallest discovery step that can answer the question.
103
- - If a downstream tool fails with a validation error, fetch or re-check its schema before retrying.
104
- - If there is any doubt about required parameters, confirmation tokens, or argument structure, fetch the schema first instead of guessing.
38
+ - Apply the downstream tool's schema, side-effect rules, and confirmation flow before calling it.
39
+ - Treat gateway failures and structured downstream error results as failures.
40
+ - Never auto-approve an `input_required` result. Obtain the requested user input and retry with the returned opaque state and matching responses.