@decnutz/mcpgateway 0.0.0-stage → 0.2.1
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/LICENSE +21 -0
- package/README.md +339 -2
- package/dist/src/admin.d.ts +32 -0
- package/dist/src/admin.js +123 -0
- package/dist/src/audit.d.ts +62 -0
- package/dist/src/audit.js +185 -0
- package/dist/src/cli.d.ts +34 -0
- package/dist/src/cli.js +374 -0
- package/dist/src/config.d.ts +124 -0
- package/dist/src/config.js +599 -0
- package/dist/src/downstream.d.ts +59 -0
- package/dist/src/downstream.js +279 -0
- package/dist/src/gateway.d.ts +44 -0
- package/dist/src/gateway.js +194 -0
- package/dist/src/hiddenchars.d.ts +31 -0
- package/dist/src/hiddenchars.js +77 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/index.js +7 -0
- package/dist/src/metrics.d.ts +58 -0
- package/dist/src/metrics.js +138 -0
- package/dist/src/namespace.d.ts +65 -0
- package/dist/src/namespace.js +131 -0
- package/dist/src/pinning.d.ts +35 -0
- package/dist/src/pinning.js +131 -0
- package/dist/src/policy.d.ts +31 -0
- package/dist/src/policy.js +116 -0
- package/dist/src/ratelimit.d.ts +19 -0
- package/dist/src/ratelimit.js +62 -0
- package/dist/src/upstream.d.ts +107 -0
- package/dist/src/upstream.js +546 -0
- package/dist/src/util.d.ts +19 -0
- package/dist/src/util.js +47 -0
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +16 -0
- package/mcpgateway.example.yaml +90 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Calas Automations Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,340 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Image URLs are absolute on purpose: GitHub resolves relative paths, npm does not. -->
|
|
2
|
+

|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
# mcpgateway
|
|
5
|
+
|
|
6
|
+
**One process in front of all your MCP servers: one tool list, one policy, one audit log, one place for credentials.**
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
git clone https://github.com/calasdan-sketch/mcpgateway && cd mcpgateway && npm install && npm run build && node dist/src/index.js init
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Needs Node 20 or newer. Install from npm: `npm install -g @decnutz/mcpgateway`, then `mcpgateway init`. `mcpgateway --help` lists every command.
|
|
13
|
+
|
|
14
|
+
[](https://www.npmjs.com/package/mcpgateway)
|
|
15
|
+

|
|
16
|
+

|
|
17
|
+
|
|
18
|
+
Real output, on a one-server `.mcp.json` (temporary home folder, `NO_COLOR=1`; the gateway key is random and shown here as `<key>`):
|
|
19
|
+
|
|
20
|
+
```text
|
|
21
|
+
$ mcpgateway init --from .mcp.json
|
|
22
|
+
wrote ./mcpgateway.yaml with 1 server from .mcp.json — edit it, then run: mcpgateway validate -c ./mcpgateway.yaml
|
|
23
|
+
generated a gateway key (not saved to the file) — set it in your environment:
|
|
24
|
+
export GATEWAY_KEY=<key>
|
|
25
|
+
$ mcpgateway validate -c mcpgateway.yaml
|
|
26
|
+
ok: 1 server(s), namespace strategy "prefix", upstream=stdio, admin=127.0.0.1:3001
|
|
27
|
+
hint: run `mcpgateway namespace` to preview the unified tool table (connects to servers)
|
|
28
|
+
$ mcpgateway namespace -c mcpgateway.yaml
|
|
29
|
+
TOOL SERVER -> ORIGINAL
|
|
30
|
+
search notes -> search
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- **One namespace.** A single `tools/list` across all your servers, with name collisions resolved the way you choose (`prefix`, `priority` or `explicit`).
|
|
34
|
+
- **One policy.** Allow, deny or hide tools fleet-wide, with per-tool rate limits, response redaction, and an observe mode to try a policy first.
|
|
35
|
+
- **One record.** An append-only audit log with secret redaction, Prometheus metrics, and bearer-key auth at the edge so downstream credentials stay in the gateway.
|
|
36
|
+
|
|
37
|
+
## Limits up front
|
|
38
|
+
|
|
39
|
+
- It routes, guards and observes; it does not rewrite payloads, and it does not proxy sampling or elicitation requests from servers.
|
|
40
|
+
- The config file is trusted operator input (like `sshd_config`): it names the commands to spawn. Do not generate it from untrusted input.
|
|
41
|
+
- Single process: no clustering or high availability. Audit logs are local JSONL; shipping them elsewhere is your job.
|
|
42
|
+
- Server URLs are called as configured; the gateway does not filter them.
|
|
43
|
+
|
|
44
|
+
The full list is under [Limitations](#limitations-honest).
|
|
45
|
+
|
|
46
|
+
## What it is
|
|
47
|
+
|
|
48
|
+
One process fronting all your MCP servers. MCP works in demos; production is a
|
|
49
|
+
mess — dozens of tools across servers, duplicated config, fragmented audit
|
|
50
|
+
logs, tool name collisions, no fleet-wide policy, zero visibility into what
|
|
51
|
+
gets called. `mcpgateway` is the missing production layer:
|
|
52
|
+
|
|
53
|
+
- **Unified tool namespace** — one `tools/list` across all servers, with
|
|
54
|
+
collision resolution (`prefix` default, `priority`, `explicit`)
|
|
55
|
+
- **Fleet-wide policy** — allow/deny/hide, argument substring rules, response
|
|
56
|
+
redact/block/warn, observe mode (same ideas as mcp-leash, applied fleet-wide)
|
|
57
|
+
- **Per-tool rate limits** — token buckets, bounded memory
|
|
58
|
+
- **Centralized audit log** — append-only JSONL, secret redaction, rotation
|
|
59
|
+
- **Prometheus metrics** — per-tool calls, latency histograms, server health
|
|
60
|
+
- **Auth at the edge** — bearer keys with scopes; the gateway holds downstream
|
|
61
|
+
credentials (no more per-server secret sprawl)
|
|
62
|
+
- **Curated discovery** — `mcpgateway namespace` previews the unified table;
|
|
63
|
+
`/v1/registry` and `/v1/namespace` on the admin API
|
|
64
|
+
|
|
65
|
+
Drop-in: point your agent at the gateway instead of N servers — stdio (swap
|
|
66
|
+
the server command) or Streamable HTTP.
|
|
67
|
+
|
|
68
|
+
## Install
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
npm install -g @decnutz/mcpgateway
|
|
72
|
+
# or run from source:
|
|
73
|
+
npm install && npm run build && node dist/src/index.js --help
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Requires Node ≥ 20.
|
|
77
|
+
|
|
78
|
+
## Quickstart
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
mcpgateway init # writes ./mcpgateway.yaml and prints a fresh random key
|
|
82
|
+
export GATEWAY_KEY=<the printed key> # the key is printed, never written to the file
|
|
83
|
+
# edit mcpgateway.yaml: replace the sample servers with yours (the sample
|
|
84
|
+
# `github` server needs GITHUB_TOKEN set, or validate stops with an error)
|
|
85
|
+
mcpgateway validate -c mcpgateway.yaml
|
|
86
|
+
mcpgateway namespace -c mcpgateway.yaml # preview the unified tool table
|
|
87
|
+
mcpgateway serve -c mcpgateway.yaml
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Already have a `.mcp.json`? Start from it instead of the sample servers:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
mcpgateway init --from .mcp.json # full config with your servers; secrets become ${NAME} placeholders
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or print only the `servers:` block:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
mcpgateway import .mcp.json > servers.yaml # paste the servers: block into mcpgateway.yaml
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`import` reads `mcpServers` (or `servers`, or a top-level map). Entries with
|
|
103
|
+
`command` become `transport: stdio` (with `args` and `env`); entries with `url`
|
|
104
|
+
become `transport: http` (with `headers`). Names are lowercased and other
|
|
105
|
+
characters become `-`; clashes get `-2`, `-3`. Any `env` or `headers` value
|
|
106
|
+
whose name looks secret (same list as the audit `redactKeys` default: `token`,
|
|
107
|
+
`secret`, `password`, `authorization`, ...) is replaced with `${NAME}` and a
|
|
108
|
+
note on stderr tells you which variable to export, so the secret is never
|
|
109
|
+
written to the YAML. Values under other names are copied as-is, so check the
|
|
110
|
+
output before committing it. Invalid JSON exits `2`.
|
|
111
|
+
|
|
112
|
+
**Exit codes** (every command): `0` ok, `1` runtime failure, `2` bad usage or bad/missing config (`serve`, `namespace`, `pin` and `validate` all agree).
|
|
113
|
+
|
|
114
|
+
Point your agent at it (stdio drop-in):
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{
|
|
118
|
+
"mcpServers": {
|
|
119
|
+
"gateway": { "command": "mcpgateway", "args": ["serve", "-c", "/path/to/mcpgateway.yaml"] }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Or serve Streamable HTTP (`upstream.http.enabled: true` in config, or the
|
|
125
|
+
`--http` flag: `mcpgateway serve -c mcpgateway.yaml --http`) and point remote
|
|
126
|
+
agents at `http://host:3000/mcp` with a bearer key.
|
|
127
|
+
|
|
128
|
+
## How it works
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
agent ──stdio / Streamable HTTP──▶ mcpgateway ──┬──stdio──▶ server A
|
|
132
|
+
(one session) auth at edge │ ├──stdio──▶ server B
|
|
133
|
+
unified namespace policy engine│ └──http───▶ server C
|
|
134
|
+
rate limits audit+metrics│
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Each downstream server gets an independent MCP session with bounded
|
|
138
|
+
concurrency (stdio defaults to 1 — most stdio servers are single-threaded),
|
|
139
|
+
per-call timeouts, a circuit breaker (5 consecutive failures → 30s open, fail
|
|
140
|
+
fast, half-open ping probe), and periodic health checks. Catalog changes
|
|
141
|
+
(`tools/list_changed`) rebuild the unified namespace without dropping
|
|
142
|
+
in-flight calls.
|
|
143
|
+
|
|
144
|
+
### Namespace & collisions
|
|
145
|
+
|
|
146
|
+
MCP tool names must match `^[a-zA-Z0-9_-]{1,64}$`. When two servers expose the
|
|
147
|
+
same tool name:
|
|
148
|
+
|
|
149
|
+
| strategy | behavior |
|
|
150
|
+
|---|---|
|
|
151
|
+
| `prefix` (default) | `compare` on `github` → `github__compare`. Deterministic, no silent shadowing. |
|
|
152
|
+
| `priority` | highest-priority server keeps the bare name; losers are prefixed (still reachable). Every shadowing is logged. |
|
|
153
|
+
| `explicit` | `mappings: {"compare": "github"}` picks the winner; unmapped collisions are a **startup error**. |
|
|
154
|
+
|
|
155
|
+
Non-colliding tools keep their bare names. Aliases (`{"server:tool": "name"}`)
|
|
156
|
+
override anything. A renamed tool longer than 64 chars, or a public name that
|
|
157
|
+
collides with another tool's natural name, is a hard error with a suggested
|
|
158
|
+
fix — run `mcpgateway namespace` to preview before serving.
|
|
159
|
+
|
|
160
|
+
### Policy (fleet scope)
|
|
161
|
+
|
|
162
|
+
`policy.allowTools` / `denyTools` / `hideTools` are glob patterns over public
|
|
163
|
+
tool names (`*` supported); **deny wins**, hidden tools vanish from listings
|
|
164
|
+
*and* are denied on call — the caller sees the same `unknown tool` error as
|
|
165
|
+
for unmapped names, so probing can't confirm a hidden tool exists (the audit
|
|
166
|
+
record keeps the real `hidden` reason for operators). `argRules` are
|
|
167
|
+
**substring** matchers over the JSON-encoded arguments (deliberately not
|
|
168
|
+
regex — no ReDoS). `responseRedact` / `responseBlock` / `responseWarn` scan
|
|
169
|
+
the JSON-encoded result (first 64KB). `mode: observe` logs would-be verdicts
|
|
170
|
+
and forwards everything — safe onboarding.
|
|
171
|
+
|
|
172
|
+
This is the **fleet** layer. For per-server argument rules on one server's
|
|
173
|
+
tools, you can also put
|
|
174
|
+
[mcp-leash](https://github.com/calasdan-sketch/mcp-jail) (formerly mcp-jail)
|
|
175
|
+
in front of that server: the gateway decides *which* tools exist and *who*
|
|
176
|
+
may call them; mcp-leash checks the arguments of each call to that server.
|
|
177
|
+
mcp-leash is a separate tool; the two are not wired together.
|
|
178
|
+
|
|
179
|
+
### Tool-definition pinning (rug-pull guard)
|
|
180
|
+
|
|
181
|
+
A server can change a tool's description or schema after you approved it.
|
|
182
|
+
The gateway fingerprints each downstream tool (sha256 over the canonical JSON
|
|
183
|
+
of `name`, `title`, `description`, `inputSchema`, `outputSchema`,
|
|
184
|
+
`annotations`; key order does not matter) and compares it with a pin on
|
|
185
|
+
startup and on every `list_changed`.
|
|
186
|
+
|
|
187
|
+
```yaml
|
|
188
|
+
pinning:
|
|
189
|
+
mode: warn # off | warn (default) | quarantine
|
|
190
|
+
file: pins.json # optional; without it, tools are pinned on first sight at startup (in memory)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
- `warn`: a changed tool is still served; one `pin_mismatch` audit record
|
|
194
|
+
(old and new hash, and the changed field names when the old definition was
|
|
195
|
+
seen in this process) and `mcpgateway_pin_mismatch_total{server}`. A tool
|
|
196
|
+
with no pin gets a `pin_new` record.
|
|
197
|
+
- `quarantine`: the same records, and the changed or unpinned tool is removed
|
|
198
|
+
from `tools/list`; calls get the ordinary `unknown tool` error.
|
|
199
|
+
- `/healthz` reports `pinMismatches`.
|
|
200
|
+
- `mcpgateway pin -c mcpgateway.yaml -o pins.json` writes the pins (sorted,
|
|
201
|
+
stable bytes). To accept a change, re-run it and review the file diff.
|
|
202
|
+
There is no accept API.
|
|
203
|
+
|
|
204
|
+
Pinning detects definition changes. It cannot detect a server that keeps its
|
|
205
|
+
definition and changes behaviour. Without `file`, pins live in memory only, so
|
|
206
|
+
a restart re-trusts whatever the servers serve at that moment.
|
|
207
|
+
|
|
208
|
+
### Invisible-character check
|
|
209
|
+
|
|
210
|
+
On every catalog build, each tool's `name`, `title`, `description` and every
|
|
211
|
+
string inside its `inputSchema` are scanned for characters a human reviewer
|
|
212
|
+
cannot see but a model reads: the Unicode tag block (U+E0000 to U+E007F),
|
|
213
|
+
zero-width and direction marks (U+200B to U+200F), bidi embeddings and
|
|
214
|
+
overrides (U+202A to U+202E), invisible operators (U+2060 to U+2064), bidi
|
|
215
|
+
isolates (U+2066 to U+2069) and U+FEFF. A flagged tool gets one
|
|
216
|
+
`hidden_chars` audit record (code points and their JSON path), and
|
|
217
|
+
`mcpgateway_hidden_chars_tools` counts flagged tools. By default the tool is
|
|
218
|
+
still served; `policy.hideSuspicious: true` hides it and calls get the
|
|
219
|
+
`unknown tool` error.
|
|
220
|
+
|
|
221
|
+
It flags invisible characters; it does not judge visible text. Zero-width
|
|
222
|
+
joiners inside legitimate emoji sequences are flagged too.
|
|
223
|
+
|
|
224
|
+
### Audit & metrics
|
|
225
|
+
|
|
226
|
+
One JSONL record per call: timestamp, request id, session, key id, tool,
|
|
227
|
+
server, original tool name, duration, status, error. Argument values whose key
|
|
228
|
+
looks secret (`token`, `secret`, `password`, … — configurable, substring,
|
|
229
|
+
case-insensitive, recursive) become `[REDACTED]`; serialized args are capped
|
|
230
|
+
(8KB default, visible truncation marker); set `logArgs: false` to store only a
|
|
231
|
+
SHA-256 of the args. Size-based rotation with a bounded file count — the log
|
|
232
|
+
can never fill the disk. The writer never throws into the request path;
|
|
233
|
+
failures are counted and surfaced on `/healthz`.
|
|
234
|
+
|
|
235
|
+
Prometheus text on the admin port: `mcpgateway_tool_calls_total`,
|
|
236
|
+
`mcpgateway_tool_call_duration_seconds` (histogram), `mcpgateway_server_up`,
|
|
237
|
+
`mcpgateway_server_inflight`, `mcpgateway_policy_denials_total`,
|
|
238
|
+
`mcpgateway_rate_limit_hits_total`, `mcpgateway_audit_errors_total`,
|
|
239
|
+
`mcpgateway_http_rejected_total`, `mcpgateway_pin_mismatch_total`, `mcpgateway_hidden_chars_tools`.
|
|
240
|
+
|
|
241
|
+
### Admin API (default `http://127.0.0.1:3001`)
|
|
242
|
+
|
|
243
|
+
- `GET /healthz` — open (load-balancer convention): status, per-server health, audit errors
|
|
244
|
+
- `GET /metrics` — Prometheus exposition (`admin` scope)
|
|
245
|
+
- `GET /v1/registry` — servers, tool counts, health (any key)
|
|
246
|
+
- `GET /v1/namespace` — unified tool table + collision report (any key)
|
|
247
|
+
- `POST /v1/reload` — refresh all downstream catalogs (`admin` scope)
|
|
248
|
+
|
|
249
|
+
The admin API **refuses to bind a public address** unless
|
|
250
|
+
`admin.allowPublicAdmin: true` is set explicitly.
|
|
251
|
+
|
|
252
|
+
## Configuration
|
|
253
|
+
|
|
254
|
+
See [`mcpgateway.example.yaml`](mcpgateway.example.yaml) — every option is
|
|
255
|
+
commented. Highlights:
|
|
256
|
+
|
|
257
|
+
- `${VAR}` / `${VAR:-default}` env interpolation everywhere (unset without a
|
|
258
|
+
default = startup error naming the variable)
|
|
259
|
+
- stdio servers spawn with `shell: false` and an argv array; env is a small
|
|
260
|
+
safe-default set plus your `env` block
|
|
261
|
+
- `validate`/`serve` refuse any key containing `changeme` (the example
|
|
262
|
+
file's fallback), so a gateway started without `GATEWAY_KEY` fails instead
|
|
263
|
+
of running on a key that is public in this repo; keys under 16 chars are
|
|
264
|
+
refused too
|
|
265
|
+
- bearer keys carry scopes: `tools:call`, `tools:list`, `resources:*`,
|
|
266
|
+
`prompts:*`, `admin` (compared in constant time)
|
|
267
|
+
- a Streamable HTTP session id only works with the key that opened it
|
|
268
|
+
- `auth.keys[].tools` (optional glob list over public tool names) limits what
|
|
269
|
+
one key can list and call; a call outside the list gets the same
|
|
270
|
+
`unknown tool` error as a missing tool and is audited as `denied` with
|
|
271
|
+
reason `key_scope`. Without `tools`, a key sees every tool. The stdio
|
|
272
|
+
upstream has no key, so per-key lists apply to the HTTP upstream only
|
|
273
|
+
- the config file is **trusted operator input** (like `sshd_config`) — `chmod 600`
|
|
274
|
+
|
|
275
|
+
## CLI
|
|
276
|
+
|
|
277
|
+
```
|
|
278
|
+
mcpgateway serve [-c config.yaml] # stdio upstream by default; logs to stderr
|
|
279
|
+
mcpgateway validate [-c config.yaml] # config checks; --network adds reachability
|
|
280
|
+
mcpgateway namespace [-c config.yaml] # connect + print the unified tool table
|
|
281
|
+
mcpgateway init [-o out.yaml] # write the starter config
|
|
282
|
+
mcpgateway pin [-c config.yaml] [-o pins.json] # connect + write tool-definition pins
|
|
283
|
+
mcpgateway import .mcp.json # print a servers: block from a Claude-style config
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Limitations (honest)
|
|
287
|
+
|
|
288
|
+
- **No sampling/elicitation proxying.** If a downstream server initiates
|
|
289
|
+
`sampling/createMessage` or `elicitation/create`, the gateway answers
|
|
290
|
+
"method not found". Forwarding server→client requests across two
|
|
291
|
+
independent sessions is a correctness swamp we chose not to wade into for v1.
|
|
292
|
+
- **No roots.** The gateway advertises an empty roots list downstream.
|
|
293
|
+
- **Prefix-on-collision only.** Non-colliding tools keep bare names, so adding
|
|
294
|
+
a server later *can* rename a previously bare tool (it becomes prefixed).
|
|
295
|
+
Pin names you depend on with `aliases`.
|
|
296
|
+
- **Single process.** No clustering or HA in v1; run one gateway per host and
|
|
297
|
+
put it behind your own supervisor. In-flight calls are capped
|
|
298
|
+
(`globalMaxInflight`, default 256) so the gateway degrades loudly, not
|
|
299
|
+
silently.
|
|
300
|
+
- **Config is trusted.** A malicious config file owns the machine (it names
|
|
301
|
+
commands to spawn). This is by design — like `sshd_config` — but don't
|
|
302
|
+
generate configs from untrusted input.
|
|
303
|
+
- **HTTP URLs are operator-trusted.** Server `url`s are called as configured;
|
|
304
|
+
the gateway does not SSRF-filter them (your servers usually *are*
|
|
305
|
+
localhost). Don't point it at URLs you don't control.
|
|
306
|
+
- **No request/response transformation.** The gateway routes, guards, and
|
|
307
|
+
observes; it does not rewrite payloads. No result caching either.
|
|
308
|
+
- **Audit is local JSONL.** Rotation is bounded, but shipping to a SIEM is
|
|
309
|
+
your job (filebeat/vector sidecar).
|
|
310
|
+
- **Metrics are Prometheus-text only.** No OTel exporter in v1.
|
|
311
|
+
- **Origin/Host checks are allow-lists, nothing more.** Before auth, the HTTP
|
|
312
|
+
upstream answers 403 when an `Origin` header is present and not in
|
|
313
|
+
`upstream.http.allowedOrigins` (exact match; default empty, so any browser
|
|
314
|
+
origin is refused), and when the `Host` header is not in
|
|
315
|
+
`upstream.http.allowedHosts` (an entry without a port matches any port). A
|
|
316
|
+
loopback bind defaults `allowedHosts` to `localhost`, `127.0.0.1`, `[::1]`;
|
|
317
|
+
a non-loopback bind defaults to no Host check and `validate` warns. Requests
|
|
318
|
+
with no `Origin` (CLI and SDK clients) pass the Origin check. Rejections are
|
|
319
|
+
counted in `mcpgateway_http_rejected_total{reason}` and logged to stderr.
|
|
320
|
+
- **No SSE resumability.** No event store: if a Streamable HTTP connection
|
|
321
|
+
drops, clients reconnect and start a new session. Sessions are capped
|
|
322
|
+
(`maxSessions`, default 128) so abandoned ones can't exhaust memory.
|
|
323
|
+
- **Wedged stdio children are SIGTERM'd, not SIGKILL'd,** on gateway shutdown;
|
|
324
|
+
a child that ignores SIGTERM will linger as an orphan.
|
|
325
|
+
- **Downstream error messages are scrubbed** of any secret values seen in the
|
|
326
|
+
call's args (same redact-key list as the audit log), then truncated — but a
|
|
327
|
+
server that leaks secrets through *other* channels (e.g. inside a returned
|
|
328
|
+
document) is only caught if you configure `responseRedact` patterns.
|
|
329
|
+
|
|
330
|
+
## Development
|
|
331
|
+
|
|
332
|
+
```bash
|
|
333
|
+
npm install
|
|
334
|
+
npm test # build + unit and in-process integration tests
|
|
335
|
+
npm run lint # tsc --noEmit (strict)
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## License
|
|
339
|
+
|
|
340
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin HTTP API (localhost-bound by default; config refuses public binds
|
|
3
|
+
* without an explicit flag).
|
|
4
|
+
*
|
|
5
|
+
* GET /healthz — open (load-balancer convention): gateway status,
|
|
6
|
+
* per-server health, audit error count
|
|
7
|
+
* GET /metrics — Prometheus exposition (admin scope)
|
|
8
|
+
* GET /v1/registry — servers, tool counts, health (any authed key)
|
|
9
|
+
* GET /v1/namespace — unified tool table + collision report (any authed key)
|
|
10
|
+
* POST /v1/reload — refresh all downstream catalogs (admin scope)
|
|
11
|
+
*/
|
|
12
|
+
import { type Server as HttpServer } from 'node:http';
|
|
13
|
+
import type { AuditLogger } from './audit.js';
|
|
14
|
+
import type { Metrics } from './metrics.js';
|
|
15
|
+
import type { DownstreamServer } from './downstream.js';
|
|
16
|
+
import type { NamespaceResult } from './namespace.js';
|
|
17
|
+
import type { AuthKey } from './config.js';
|
|
18
|
+
export interface AdminDeps {
|
|
19
|
+
auth: {
|
|
20
|
+
disabled: boolean;
|
|
21
|
+
keys: AuthKey[];
|
|
22
|
+
};
|
|
23
|
+
audit: AuditLogger;
|
|
24
|
+
metrics: Metrics;
|
|
25
|
+
getServers: () => DownstreamServer[];
|
|
26
|
+
getNamespace: () => NamespaceResult | null;
|
|
27
|
+
/** tools whose definition no longer matches its pin */
|
|
28
|
+
pinMismatches: () => number;
|
|
29
|
+
reloadCatalogs: () => Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export declare function startAdmin(deps: AdminDeps, host: string, port: number): Promise<HttpServer>;
|
|
32
|
+
//# sourceMappingURL=admin.d.ts.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin HTTP API (localhost-bound by default; config refuses public binds
|
|
3
|
+
* without an explicit flag).
|
|
4
|
+
*
|
|
5
|
+
* GET /healthz — open (load-balancer convention): gateway status,
|
|
6
|
+
* per-server health, audit error count
|
|
7
|
+
* GET /metrics — Prometheus exposition (admin scope)
|
|
8
|
+
* GET /v1/registry — servers, tool counts, health (any authed key)
|
|
9
|
+
* GET /v1/namespace — unified tool table + collision report (any authed key)
|
|
10
|
+
* POST /v1/reload — refresh all downstream catalogs (admin scope)
|
|
11
|
+
*/
|
|
12
|
+
import { createServer as createHttpServer } from 'node:http';
|
|
13
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
14
|
+
import { VERSION } from './version.js';
|
|
15
|
+
function authenticate(req, auth) {
|
|
16
|
+
if (auth.disabled)
|
|
17
|
+
return { keyId: 'anonymous', scopes: ['admin'] };
|
|
18
|
+
const header = req.headers['authorization'];
|
|
19
|
+
if (typeof header !== 'string' || !header.startsWith('Bearer '))
|
|
20
|
+
return null;
|
|
21
|
+
const presented = header.slice('Bearer '.length);
|
|
22
|
+
for (const k of auth.keys) {
|
|
23
|
+
if (presented.length === k.key.length && timingSafeEqual(Buffer.from(presented), Buffer.from(k.key))) {
|
|
24
|
+
return { keyId: k.id, scopes: k.scopes };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
function json(res, code, body) {
|
|
30
|
+
res.writeHead(code, { 'content-type': 'application/json' });
|
|
31
|
+
res.end(JSON.stringify(body));
|
|
32
|
+
}
|
|
33
|
+
export function startAdmin(deps, host, port) {
|
|
34
|
+
const server = createHttpServer((req, res) => {
|
|
35
|
+
void handle(req, res, deps).catch(() => {
|
|
36
|
+
if (!res.headersSent)
|
|
37
|
+
json(res, 500, { error: 'internal error' });
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
server.on('error', reject);
|
|
42
|
+
server.listen(port, host, () => resolve(server));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async function handle(req, res, deps) {
|
|
46
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
47
|
+
const path = url.pathname;
|
|
48
|
+
if (req.method === 'GET' && path === '/healthz') {
|
|
49
|
+
const servers = deps.getServers().map((s) => ({
|
|
50
|
+
name: s.name,
|
|
51
|
+
up: s.healthy,
|
|
52
|
+
circuit: s.circuitState,
|
|
53
|
+
inflight: s.inFlight,
|
|
54
|
+
lastPingOk: s.lastPingOk,
|
|
55
|
+
lastError: s.lastError,
|
|
56
|
+
}));
|
|
57
|
+
const degraded = servers.some((s) => !s.up) || deps.audit.errors > 0;
|
|
58
|
+
json(res, degraded ? 503 : 200, {
|
|
59
|
+
status: degraded ? 'degraded' : 'ok',
|
|
60
|
+
version: VERSION,
|
|
61
|
+
auditErrors: deps.audit.errors,
|
|
62
|
+
pinMismatches: deps.pinMismatches(),
|
|
63
|
+
servers,
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const authed = authenticate(req, deps.auth);
|
|
68
|
+
if (authed === null) {
|
|
69
|
+
json(res, 401, { error: 'missing or invalid bearer token' });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const isAdmin = authed.scopes.includes('admin');
|
|
73
|
+
if (req.method === 'GET' && path === '/metrics') {
|
|
74
|
+
if (!isAdmin) {
|
|
75
|
+
json(res, 403, { error: `key "${authed.keyId}" lacks scope "admin"` });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' });
|
|
79
|
+
res.end(deps.metrics.render());
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (req.method === 'GET' && path === '/v1/registry') {
|
|
83
|
+
const ns = deps.getNamespace();
|
|
84
|
+
json(res, 200, {
|
|
85
|
+
version: VERSION,
|
|
86
|
+
servers: deps.getServers().map((s) => ({
|
|
87
|
+
name: s.name,
|
|
88
|
+
up: s.healthy,
|
|
89
|
+
circuit: s.circuitState,
|
|
90
|
+
tools: s.getCatalogs().tools.length,
|
|
91
|
+
resources: s.getCatalogs().resources.length,
|
|
92
|
+
prompts: s.getCatalogs().prompts.length,
|
|
93
|
+
})),
|
|
94
|
+
unifiedTools: ns?.tools.length ?? 0,
|
|
95
|
+
collisions: ns?.collisions ?? [],
|
|
96
|
+
});
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (req.method === 'GET' && path === '/v1/namespace') {
|
|
100
|
+
const ns = deps.getNamespace();
|
|
101
|
+
if (ns === null) {
|
|
102
|
+
json(res, 503, { error: 'namespace not built yet' });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
json(res, 200, {
|
|
106
|
+
tools: ns.tools.map((t) => ({ name: t.publicName, server: t.server, original: t.originalName, description: t.description })),
|
|
107
|
+
collisions: ns.collisions,
|
|
108
|
+
warnings: ns.warnings,
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (req.method === 'POST' && path === '/v1/reload') {
|
|
113
|
+
if (!isAdmin) {
|
|
114
|
+
json(res, 403, { error: `key "${authed.keyId}" lacks scope "admin"` });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
await deps.reloadCatalogs();
|
|
118
|
+
json(res, 200, { ok: true });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
json(res, 404, { error: 'not found' });
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=admin.js.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { AuditConfig } from './config.js';
|
|
2
|
+
export type AuditStatus = 'ok' | 'error' | 'denied' | 'rate_limited' | 'timeout' | 'blocked' | 'auth_failed' | 'pin_mismatch' | 'pin_new' | 'hidden_chars';
|
|
3
|
+
export interface AuditRecord {
|
|
4
|
+
ts: string;
|
|
5
|
+
reqId: string;
|
|
6
|
+
sessionId?: string;
|
|
7
|
+
keyId?: string;
|
|
8
|
+
tool: string;
|
|
9
|
+
server: string;
|
|
10
|
+
originalTool: string;
|
|
11
|
+
durationMs: number;
|
|
12
|
+
status: AuditStatus;
|
|
13
|
+
errorCode?: string;
|
|
14
|
+
errorMessage?: string;
|
|
15
|
+
/** redacted + truncated args (omitted when logArgs=false) */
|
|
16
|
+
args?: unknown;
|
|
17
|
+
argsTruncated?: boolean;
|
|
18
|
+
/** sha256 of the canonical args JSON — present when logArgs=false */
|
|
19
|
+
argsHash?: string;
|
|
20
|
+
policyReason?: string;
|
|
21
|
+
redactions?: number;
|
|
22
|
+
/** pinning events: pinned vs current hash, changed field names when known */
|
|
23
|
+
pin?: {
|
|
24
|
+
old?: string;
|
|
25
|
+
new: string;
|
|
26
|
+
fields?: string[];
|
|
27
|
+
};
|
|
28
|
+
/** invisible characters found in tool metadata */
|
|
29
|
+
hiddenChars?: Array<{
|
|
30
|
+
path: string;
|
|
31
|
+
codePoints: string[];
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export declare class AuditLogger {
|
|
35
|
+
private cfg;
|
|
36
|
+
private onError?;
|
|
37
|
+
private bytesWritten;
|
|
38
|
+
private maxBytes;
|
|
39
|
+
errors: number;
|
|
40
|
+
constructor(cfg: AuditConfig, onError?: (() => void) | undefined);
|
|
41
|
+
/** Count a write failure and notify the metrics registry (never throws). */
|
|
42
|
+
private fail;
|
|
43
|
+
/** Append one record. Never throws. */
|
|
44
|
+
log(record: AuditRecord): void;
|
|
45
|
+
close(): void;
|
|
46
|
+
private ensureOpen;
|
|
47
|
+
private prepare;
|
|
48
|
+
private rotate;
|
|
49
|
+
}
|
|
50
|
+
/** Recursively redact values whose key contains a redact substring (case-insensitive). */
|
|
51
|
+
export declare function redactDeep(value: unknown, redactKeys: string[]): unknown;
|
|
52
|
+
/**
|
|
53
|
+
* Collect the actual secret VALUES from a call's args (values of keys that
|
|
54
|
+
* matched the redact list). Used to scrub those values out of downstream
|
|
55
|
+
* error messages, which otherwise echo secrets into the audit log and the
|
|
56
|
+
* agent-facing error. Only values >= 8 chars are collected, so redacting
|
|
57
|
+
* them elsewhere can never nuke ordinary words.
|
|
58
|
+
*/
|
|
59
|
+
export declare function collectSecretValues(args: unknown, redactKeys: string[]): string[];
|
|
60
|
+
/** Replace every occurrence of each secret value with [REDACTED]. */
|
|
61
|
+
export declare function redactSecretValues(text: string, secrets: string[]): string;
|
|
62
|
+
//# sourceMappingURL=audit.d.ts.map
|