@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
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upstream: the agent-facing side of the gateway. The gateway presents as ONE
|
|
3
|
+
* MCP server (stdio and/or Streamable HTTP) and routes every tools/call,
|
|
4
|
+
* resources/read, and prompts/get to the owning downstream server.
|
|
5
|
+
*
|
|
6
|
+
* Tool-call pipeline (in order):
|
|
7
|
+
* 1. route lookup — unknown tool -> InvalidParams
|
|
8
|
+
* 2. fleet policy verdict — enforce: deny -> audit + McpError;
|
|
9
|
+
* observe: forward anyway, audit the would-be verdict
|
|
10
|
+
* 3. per-tool rate limit — token bucket; exhausted -> audit + McpError
|
|
11
|
+
* 4. global in-flight cap — protects the gateway itself from collapse
|
|
12
|
+
* 5. downstream call — breaker + semaphore + timeout live downstream
|
|
13
|
+
* 6. response egress rules — block -> McpError; redact -> rewritten result
|
|
14
|
+
* 7. audit + metrics — every outcome lands in both
|
|
15
|
+
*
|
|
16
|
+
* Resources and prompts are routed (namespaced) and audited; fleet policy
|
|
17
|
+
* and rate limits apply to tools in v1 (blueprint D2).
|
|
18
|
+
*/
|
|
19
|
+
import { createServer as createHttpServer } from 'node:http';
|
|
20
|
+
import { randomUUID, timingSafeEqual } from 'node:crypto';
|
|
21
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
22
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
23
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
24
|
+
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema, ErrorCode, } from '@modelcontextprotocol/sdk/types.js';
|
|
25
|
+
import { collectSecretValues, redactSecretValues } from './audit.js';
|
|
26
|
+
import { checkResponse, checkToolCall, isHidden } from './policy.js';
|
|
27
|
+
import { newRequestId, safeJsonStringify, truncate } from './util.js';
|
|
28
|
+
import { VERSION } from './version.js';
|
|
29
|
+
import { matchesAny } from './config.js';
|
|
30
|
+
export const RESOURCE_SCHEME = 'mcpgateway';
|
|
31
|
+
export function publicResourceUri(server, originalUri) {
|
|
32
|
+
return `${RESOURCE_SCHEME}://${server}/${encodeURIComponent(originalUri)}`;
|
|
33
|
+
}
|
|
34
|
+
export function parsePublicResourceUri(publicUri) {
|
|
35
|
+
const prefix = `${RESOURCE_SCHEME}://`;
|
|
36
|
+
if (!publicUri.startsWith(prefix))
|
|
37
|
+
return null;
|
|
38
|
+
const rest = publicUri.slice(prefix.length);
|
|
39
|
+
const slash = rest.indexOf('/');
|
|
40
|
+
if (slash === -1)
|
|
41
|
+
return null;
|
|
42
|
+
try {
|
|
43
|
+
return { server: rest.slice(0, slash), originalUri: decodeURIComponent(rest.slice(slash + 1)) };
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// Gateway
|
|
51
|
+
// ---------------------------------------------------------------------------
|
|
52
|
+
const MAX_BODY_BYTES = 10 * 1024 * 1024;
|
|
53
|
+
export class GatewayUpstream {
|
|
54
|
+
deps;
|
|
55
|
+
inflight = 0;
|
|
56
|
+
constructor(deps) {
|
|
57
|
+
this.deps = deps;
|
|
58
|
+
}
|
|
59
|
+
// -- MCP server factory (one instance per transport/session) ----------------
|
|
60
|
+
/** Create the agent-facing MCP server. Handlers always read the CURRENT routing table. */
|
|
61
|
+
createMcpServer() {
|
|
62
|
+
const server = new Server({ name: 'mcpgateway', version: VERSION }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
63
|
+
const ctxOf = () => sessionContext.get(server) ?? { sessionId: 'stdio', keyId: undefined };
|
|
64
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
65
|
+
const table = this.deps.getTable();
|
|
66
|
+
const tools = [];
|
|
67
|
+
const keyId = ctxOf().keyId;
|
|
68
|
+
for (const entry of table.toolMeta.values()) {
|
|
69
|
+
if (isHidden(this.deps.policy, entry.publicName))
|
|
70
|
+
continue;
|
|
71
|
+
if (!this.keyMayUse(keyId, entry.publicName))
|
|
72
|
+
continue;
|
|
73
|
+
tools.push({
|
|
74
|
+
name: entry.publicName,
|
|
75
|
+
description: entry.description,
|
|
76
|
+
inputSchema: (entry.inputSchema ?? { type: 'object' }),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return { tools };
|
|
80
|
+
});
|
|
81
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
82
|
+
const name = request.params.name;
|
|
83
|
+
const args = request.params.arguments ?? {};
|
|
84
|
+
return this.handleToolCall(name, args, ctxOf());
|
|
85
|
+
});
|
|
86
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
87
|
+
const table = this.deps.getTable();
|
|
88
|
+
return { resources: [...table.resourceMeta.values()] };
|
|
89
|
+
});
|
|
90
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
91
|
+
return this.handleResourceRead(request.params.uri, ctxOf());
|
|
92
|
+
});
|
|
93
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => {
|
|
94
|
+
const table = this.deps.getTable();
|
|
95
|
+
const prompts = [];
|
|
96
|
+
for (const meta of table.promptMeta.values()) {
|
|
97
|
+
prompts.push({ name: meta.publicName, description: meta.description, arguments: meta.args });
|
|
98
|
+
}
|
|
99
|
+
return { prompts };
|
|
100
|
+
});
|
|
101
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
102
|
+
return this.handlePromptGet(request.params.name, (request.params.arguments ?? {}), ctxOf());
|
|
103
|
+
});
|
|
104
|
+
return server;
|
|
105
|
+
}
|
|
106
|
+
// -- stdio upstream ----------------------------------------------------------
|
|
107
|
+
async connectStdio() {
|
|
108
|
+
const server = this.createMcpServer();
|
|
109
|
+
const transport = new StdioServerTransport();
|
|
110
|
+
await server.connect(transport);
|
|
111
|
+
}
|
|
112
|
+
// -- Streamable HTTP upstream -------------------------------------------------
|
|
113
|
+
listenHttp(host, port) {
|
|
114
|
+
// Each session is bound to the key that created it: another valid key
|
|
115
|
+
// presenting the id gets 'unknown mcp-session-id' (no hijack, and audit
|
|
116
|
+
// records can't be misattributed to the session creator).
|
|
117
|
+
const sessions = new Map();
|
|
118
|
+
const httpServer = createHttpServer((req, res) => {
|
|
119
|
+
void this.handleHttp(req, res, sessions).catch((e) => {
|
|
120
|
+
this.deps.metrics.upstreamErrors.inc({});
|
|
121
|
+
if (!res.headersSent) {
|
|
122
|
+
res.writeHead(500, { 'content-type': 'application/json' });
|
|
123
|
+
res.end(JSON.stringify({ error: 'internal error' }));
|
|
124
|
+
}
|
|
125
|
+
void e;
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
return new Promise((resolve, reject) => {
|
|
129
|
+
httpServer.on('error', reject);
|
|
130
|
+
httpServer.listen(port, host, () => resolve(httpServer));
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async handleHttp(req, res, sessions) {
|
|
134
|
+
// DNS-rebinding / cross-site guard, before auth and session lookup.
|
|
135
|
+
// Requests with no Origin (non-browser clients) pass the Origin check.
|
|
136
|
+
const origin = req.headers['origin'];
|
|
137
|
+
const host = req.headers['host'] ?? '';
|
|
138
|
+
const reason = origin !== undefined && !this.deps.httpAllowedOrigins.includes(origin) ? 'origin'
|
|
139
|
+
: this.deps.httpAllowedHosts.length > 0 && !hostAllowed(host, this.deps.httpAllowedHosts) ? 'host'
|
|
140
|
+
: null;
|
|
141
|
+
if (reason !== null) {
|
|
142
|
+
this.deps.metrics.httpRejected.inc({ reason });
|
|
143
|
+
this.deps.log(`[mcpgateway] rejected HTTP request: ${reason} ${JSON.stringify(truncate(reason === 'origin' ? String(origin) : host, 200).text)}`);
|
|
144
|
+
res.writeHead(403, { 'content-type': 'application/json' });
|
|
145
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message: `forbidden: ${reason} not allowed` } }));
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
149
|
+
if (url.pathname !== '/mcp') {
|
|
150
|
+
res.writeHead(404, { 'content-type': 'application/json' });
|
|
151
|
+
res.end(JSON.stringify({ error: 'not found (MCP endpoint is POST /mcp)' }));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
// Edge auth for every HTTP request (GET/POST/DELETE alike).
|
|
155
|
+
const authed = this.authenticateHttp(req);
|
|
156
|
+
if (authed === null) {
|
|
157
|
+
res.writeHead(401, { 'content-type': 'application/json', 'www-authenticate': 'Bearer' });
|
|
158
|
+
res.end(JSON.stringify({ error: 'missing or invalid bearer token' }));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (req.method === 'POST') {
|
|
162
|
+
const body = await readBody(req, res);
|
|
163
|
+
if (body === null)
|
|
164
|
+
return; // error already written
|
|
165
|
+
const methods = Array.isArray(body) ? body.map((m) => m.method) : [body.method];
|
|
166
|
+
for (const method of methods) {
|
|
167
|
+
const scope = scopeForMethod(typeof method === 'string' ? method : '');
|
|
168
|
+
if (scope !== null && !authed.scopes.includes(scope)) {
|
|
169
|
+
res.writeHead(403, { 'content-type': 'application/json' });
|
|
170
|
+
res.end(JSON.stringify({ error: `key "${authed.keyId}" lacks scope "${scope}"` }));
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
175
|
+
const entry = sessionId !== undefined ? sessions.get(sessionId) : undefined;
|
|
176
|
+
let transport = entry?.keyId === authed.keyId ? entry.transport : undefined;
|
|
177
|
+
if (transport === undefined) {
|
|
178
|
+
if (sessionId !== undefined) {
|
|
179
|
+
res.writeHead(400, { 'content-type': 'application/json' });
|
|
180
|
+
res.end(JSON.stringify({ error: 'unknown mcp-session-id' }));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
// Bound the session table: clients that never DELETE would otherwise
|
|
184
|
+
// grow it without limit.
|
|
185
|
+
if (sessions.size >= this.deps.httpMaxSessions) {
|
|
186
|
+
res.writeHead(429, { 'content-type': 'application/json' });
|
|
187
|
+
res.end(JSON.stringify({ error: 'too many sessions' }));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const server = this.createMcpServer();
|
|
191
|
+
const newTransport = new StreamableHTTPServerTransport({
|
|
192
|
+
sessionIdGenerator: () => randomUUID(),
|
|
193
|
+
onsessioninitialized: (id) => {
|
|
194
|
+
sessions.set(id, { transport: newTransport, keyId: authed.keyId });
|
|
195
|
+
// Real session id for audit records on this session's calls.
|
|
196
|
+
sessionContext.set(server, { sessionId: id, keyId: authed.keyId });
|
|
197
|
+
},
|
|
198
|
+
onsessionclosed: (id) => {
|
|
199
|
+
sessions.delete(id);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
await server.connect(newTransport);
|
|
203
|
+
transport = newTransport;
|
|
204
|
+
}
|
|
205
|
+
await transport.handleRequest(req, res, body);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (req.method === 'GET' || req.method === 'DELETE') {
|
|
209
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
210
|
+
const entry = sessionId !== undefined ? sessions.get(sessionId) : undefined;
|
|
211
|
+
const transport = entry?.keyId === authed.keyId ? entry.transport : undefined;
|
|
212
|
+
if (transport === undefined) {
|
|
213
|
+
res.writeHead(400, { 'content-type': 'application/json' });
|
|
214
|
+
res.end(JSON.stringify({ error: 'unknown mcp-session-id' }));
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
await transport.handleRequest(req, res);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
res.writeHead(405, { 'content-type': 'application/json' });
|
|
221
|
+
res.end(JSON.stringify({ error: 'method not allowed' }));
|
|
222
|
+
}
|
|
223
|
+
// -- authentication ------------------------------------------------------------
|
|
224
|
+
/** Bearer auth for the HTTP upstream. Returns null when rejected. */
|
|
225
|
+
authenticateHttp(req) {
|
|
226
|
+
if (this.deps.auth.disabled)
|
|
227
|
+
return { keyId: 'anonymous', scopes: [...VALID_UPSTREAM_SCOPES] };
|
|
228
|
+
const header = req.headers['authorization'];
|
|
229
|
+
if (typeof header !== 'string' || !header.startsWith('Bearer '))
|
|
230
|
+
return null;
|
|
231
|
+
const presented = header.slice('Bearer '.length);
|
|
232
|
+
for (const k of this.deps.auth.keys) {
|
|
233
|
+
if (presented.length === k.key.length && timingSafeEqual(Buffer.from(presented), Buffer.from(k.key))) {
|
|
234
|
+
return { keyId: k.id, scopes: k.scopes };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
/** Per-key tool allowlist (auth.keys[].tools). No key (stdio) or no list = all tools. */
|
|
240
|
+
keyMayUse(keyId, publicName) {
|
|
241
|
+
const tools = this.deps.auth.keys.find((k) => k.id === keyId)?.tools;
|
|
242
|
+
return tools === undefined || matchesAny(tools, publicName);
|
|
243
|
+
}
|
|
244
|
+
// -- tool call pipeline ----------------------------------------------------------
|
|
245
|
+
async handleToolCall(publicName, args, ctx) {
|
|
246
|
+
const { metrics, audit } = this.deps;
|
|
247
|
+
const reqId = newRequestId();
|
|
248
|
+
const t0 = Date.now();
|
|
249
|
+
const table = this.deps.getTable();
|
|
250
|
+
const target = table.tools.get(publicName);
|
|
251
|
+
if (target === undefined) {
|
|
252
|
+
// Recon probes for tool names are worth an audit record too. The
|
|
253
|
+
// metric label stays fixed ('unknown'): the name is caller-controlled
|
|
254
|
+
// and must never become a metric label (cardinality DoS).
|
|
255
|
+
audit.log({
|
|
256
|
+
ts: new Date().toISOString(),
|
|
257
|
+
reqId,
|
|
258
|
+
sessionId: ctx.sessionId,
|
|
259
|
+
keyId: ctx.keyId,
|
|
260
|
+
tool: publicName,
|
|
261
|
+
server: 'unknown',
|
|
262
|
+
originalTool: publicName,
|
|
263
|
+
durationMs: Date.now() - t0,
|
|
264
|
+
status: 'error',
|
|
265
|
+
errorCode: 'unknown_tool',
|
|
266
|
+
errorMessage: `unknown tool "${truncateName(publicName)}"`,
|
|
267
|
+
args,
|
|
268
|
+
});
|
|
269
|
+
metrics.toolCalls.inc({ server: 'unknown', tool: 'unknown', status: 'error' });
|
|
270
|
+
throw new McpError(ErrorCode.InvalidParams, `unknown tool "${truncateName(publicName)}"`);
|
|
271
|
+
}
|
|
272
|
+
const finish = (status, extra = {}) => {
|
|
273
|
+
const durationMs = Date.now() - t0;
|
|
274
|
+
audit.log({
|
|
275
|
+
ts: new Date().toISOString(),
|
|
276
|
+
reqId,
|
|
277
|
+
sessionId: ctx.sessionId,
|
|
278
|
+
keyId: ctx.keyId,
|
|
279
|
+
tool: publicName,
|
|
280
|
+
server: target.server.name,
|
|
281
|
+
originalTool: target.original,
|
|
282
|
+
durationMs,
|
|
283
|
+
status,
|
|
284
|
+
args,
|
|
285
|
+
...extra,
|
|
286
|
+
});
|
|
287
|
+
metrics.toolCalls.inc({ server: target.server.name, tool: publicName, status });
|
|
288
|
+
metrics.toolDuration.observe({ server: target.server.name, tool: publicName }, durationMs / 1000);
|
|
289
|
+
};
|
|
290
|
+
// 2. Hidden tools are denied unconditionally: hiding is access control,
|
|
291
|
+
// not a policy verdict — observe mode must not forward what agents
|
|
292
|
+
// cannot even see. The caller gets the same "unknown tool" error as for
|
|
293
|
+
// unmapped names: confirming a hidden tool's existence would defeat the
|
|
294
|
+
// hiding (existence oracle). The audit record keeps the real reason for
|
|
295
|
+
// the operator.
|
|
296
|
+
if (isHidden(this.deps.policy, publicName)) {
|
|
297
|
+
metrics.policyDenials.inc({ tool: publicName, reason: 'hidden' });
|
|
298
|
+
finish('denied', { policyReason: 'hidden', errorMessage: `tool "${publicName}" is hidden by policy` });
|
|
299
|
+
throw new McpError(ErrorCode.InvalidParams, `unknown tool "${truncateName(publicName)}"`);
|
|
300
|
+
}
|
|
301
|
+
// Outside this key's tool list: same masking as hidden.
|
|
302
|
+
if (!this.keyMayUse(ctx.keyId, publicName)) {
|
|
303
|
+
metrics.policyDenials.inc({ tool: publicName, reason: 'key_scope' });
|
|
304
|
+
finish('denied', { policyReason: 'key_scope', errorMessage: `tool "${publicName}" is outside key "${ctx.keyId}"'s tool list` });
|
|
305
|
+
throw new McpError(ErrorCode.InvalidParams, `unknown tool "${truncateName(publicName)}"`);
|
|
306
|
+
}
|
|
307
|
+
// 3. Fleet policy.
|
|
308
|
+
const verdict = checkToolCall(this.deps.policy, publicName, args);
|
|
309
|
+
if (verdict.decision === 'deny' && this.deps.policy.mode === 'enforce') {
|
|
310
|
+
metrics.policyDenials.inc({ tool: publicName, reason: verdict.reason });
|
|
311
|
+
finish('denied', { policyReason: verdict.reason, errorMessage: verdict.detail });
|
|
312
|
+
throw new McpError(-32000, `tool call denied by policy: ${verdict.detail}`, { reason: verdict.reason });
|
|
313
|
+
}
|
|
314
|
+
const wouldDeny = verdict.decision === 'deny' ? verdict.reason : undefined;
|
|
315
|
+
// 3. Rate limit.
|
|
316
|
+
const rule = this.deps.perToolRateLimits[publicName] ?? this.deps.defaultRateLimit;
|
|
317
|
+
if (!this.deps.rateLimiter.tryAcquire(publicName, rule)) {
|
|
318
|
+
metrics.rateLimitHits.inc({ tool: publicName });
|
|
319
|
+
finish('rate_limited', {
|
|
320
|
+
policyReason: wouldDeny !== undefined ? `would_deny:${wouldDeny}` : undefined,
|
|
321
|
+
errorMessage: `rate limit exceeded for "${publicName}" (${rule.rps} rps, burst ${rule.burst})`,
|
|
322
|
+
});
|
|
323
|
+
throw new McpError(-32000, `rate limit exceeded for tool "${publicName}"`, { retryable: true });
|
|
324
|
+
}
|
|
325
|
+
// 4. Global in-flight cap — the gateway must never be what falls over.
|
|
326
|
+
if (this.inflight >= this.deps.globalMaxInflight) {
|
|
327
|
+
finish('error', { errorCode: 'gateway_overloaded', errorMessage: 'gateway at max in-flight capacity' });
|
|
328
|
+
throw new McpError(-32000, 'gateway overloaded: too many in-flight tool calls', { retryable: true });
|
|
329
|
+
}
|
|
330
|
+
// 5. Downstream call.
|
|
331
|
+
this.inflight += 1;
|
|
332
|
+
metrics.gatewayInflight.inc({});
|
|
333
|
+
metrics.serverInflight.inc({ server: target.server.name });
|
|
334
|
+
// Secret values from this call's args, for scrubbing downstream errors.
|
|
335
|
+
const secrets = collectSecretValues(args, this.deps.auditCfg.redactKeys);
|
|
336
|
+
const scrub = (s) => redactSecretValues(s, secrets);
|
|
337
|
+
// Set before any throw that has already been audited (policy/size/block),
|
|
338
|
+
// so the catch below doesn't audit twice — but downstream McpErrors must
|
|
339
|
+
// still be audited and scrubbed (the SDK wraps them in McpError too).
|
|
340
|
+
let alreadyAudited = false;
|
|
341
|
+
try {
|
|
342
|
+
const result = await target.server.callTool(target.original, args);
|
|
343
|
+
// 5b. Result-size guard: a malicious or buggy server must not OOM the
|
|
344
|
+
// gateway with a giant payload. (Servers are operator-trusted, but
|
|
345
|
+
// bugs happen; fail the call, not the process.)
|
|
346
|
+
const resultSize = safeJsonStringify(result).length;
|
|
347
|
+
if (resultSize > this.deps.maxResultChars) {
|
|
348
|
+
finish('error', {
|
|
349
|
+
policyReason: wouldDeny !== undefined ? `would_deny:${wouldDeny}` : undefined,
|
|
350
|
+
errorCode: 'result_too_large',
|
|
351
|
+
errorMessage: `tool result was ${resultSize} chars (max ${this.deps.maxResultChars})`,
|
|
352
|
+
});
|
|
353
|
+
alreadyAudited = true;
|
|
354
|
+
throw new McpError(-32000, `tool result exceeded the ${this.deps.maxResultChars}-char limit`, { retryable: false });
|
|
355
|
+
}
|
|
356
|
+
// 6. Response egress rules (structured redaction — never breaks JSON).
|
|
357
|
+
const checked = checkResponse(this.deps.policy, result);
|
|
358
|
+
if (checked.action === 'block') {
|
|
359
|
+
finish('blocked', {
|
|
360
|
+
policyReason: wouldDeny !== undefined ? `would_deny:${wouldDeny}` : undefined,
|
|
361
|
+
errorMessage: 'tool result blocked by policy response rules',
|
|
362
|
+
});
|
|
363
|
+
alreadyAudited = true;
|
|
364
|
+
throw new McpError(-32000, 'tool result blocked by policy');
|
|
365
|
+
}
|
|
366
|
+
finish('ok', {
|
|
367
|
+
policyReason: wouldDeny !== undefined ? `would_deny:${wouldDeny}` : undefined,
|
|
368
|
+
redactions: checked.redactions || undefined,
|
|
369
|
+
});
|
|
370
|
+
return checked.result;
|
|
371
|
+
}
|
|
372
|
+
catch (e) {
|
|
373
|
+
if (e instanceof McpError && alreadyAudited)
|
|
374
|
+
throw e;
|
|
375
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
376
|
+
const scrubbed = scrub(message);
|
|
377
|
+
const timedOut = /timed out/i.test(scrubbed);
|
|
378
|
+
// Preserve the downstream JSON-RPC code when there is one (more
|
|
379
|
+
// truthful than flattening everything to -32000).
|
|
380
|
+
const code = !timedOut && e instanceof McpError ? e.code : -32000;
|
|
381
|
+
const { text } = truncate(scrubbed, 1000);
|
|
382
|
+
finish(timedOut ? 'timeout' : 'error', {
|
|
383
|
+
policyReason: wouldDeny !== undefined ? `would_deny:${wouldDeny}` : undefined,
|
|
384
|
+
errorCode: timedOut ? 'timeout' : 'downstream_error',
|
|
385
|
+
errorMessage: text,
|
|
386
|
+
});
|
|
387
|
+
throw new McpError(code, `tool "${publicName}" failed: ${truncate(scrubbed, 500).text}`);
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
this.inflight -= 1;
|
|
391
|
+
metrics.gatewayInflight.dec({});
|
|
392
|
+
metrics.serverInflight.dec({ server: target.server.name });
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async handleResourceRead(publicUri, ctx) {
|
|
396
|
+
const reqId = newRequestId();
|
|
397
|
+
const t0 = Date.now();
|
|
398
|
+
const parsed = parsePublicResourceUri(publicUri);
|
|
399
|
+
const table = this.deps.getTable();
|
|
400
|
+
const target = parsed !== null ? table.resources.get(publicUri) : undefined;
|
|
401
|
+
if (target === undefined || parsed === null) {
|
|
402
|
+
throw new McpError(ErrorCode.InvalidParams, `unknown resource "${truncateName(publicUri)}"`);
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
const result = await target.server.readResource(parsed.originalUri);
|
|
406
|
+
this.deps.audit.log({
|
|
407
|
+
ts: new Date().toISOString(),
|
|
408
|
+
reqId,
|
|
409
|
+
sessionId: ctx.sessionId,
|
|
410
|
+
keyId: ctx.keyId,
|
|
411
|
+
tool: `resource:${publicUri}`,
|
|
412
|
+
server: target.server.name,
|
|
413
|
+
originalTool: parsed.originalUri,
|
|
414
|
+
durationMs: Date.now() - t0,
|
|
415
|
+
status: 'ok',
|
|
416
|
+
});
|
|
417
|
+
return result;
|
|
418
|
+
}
|
|
419
|
+
catch (e) {
|
|
420
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
421
|
+
this.deps.audit.log({
|
|
422
|
+
ts: new Date().toISOString(),
|
|
423
|
+
reqId,
|
|
424
|
+
sessionId: ctx.sessionId,
|
|
425
|
+
keyId: ctx.keyId,
|
|
426
|
+
tool: `resource:${publicUri}`,
|
|
427
|
+
server: target.server.name,
|
|
428
|
+
originalTool: parsed.originalUri,
|
|
429
|
+
durationMs: Date.now() - t0,
|
|
430
|
+
status: 'error',
|
|
431
|
+
errorCode: 'downstream_error',
|
|
432
|
+
errorMessage: truncate(message, 1000).text,
|
|
433
|
+
});
|
|
434
|
+
throw new McpError(-32000, `resource read failed: ${truncate(message, 500).text}`);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async handlePromptGet(publicName, args, ctx) {
|
|
438
|
+
const reqId = newRequestId();
|
|
439
|
+
const t0 = Date.now();
|
|
440
|
+
const table = this.deps.getTable();
|
|
441
|
+
const target = table.prompts.get(publicName);
|
|
442
|
+
if (target === undefined) {
|
|
443
|
+
throw new McpError(ErrorCode.InvalidParams, `unknown prompt "${truncateName(publicName)}"`);
|
|
444
|
+
}
|
|
445
|
+
try {
|
|
446
|
+
const result = await target.server.getPrompt(target.original, args);
|
|
447
|
+
this.deps.audit.log({
|
|
448
|
+
ts: new Date().toISOString(),
|
|
449
|
+
reqId,
|
|
450
|
+
sessionId: ctx.sessionId,
|
|
451
|
+
keyId: ctx.keyId,
|
|
452
|
+
tool: `prompt:${publicName}`,
|
|
453
|
+
server: target.server.name,
|
|
454
|
+
originalTool: target.original,
|
|
455
|
+
durationMs: Date.now() - t0,
|
|
456
|
+
status: 'ok',
|
|
457
|
+
args,
|
|
458
|
+
});
|
|
459
|
+
return result;
|
|
460
|
+
}
|
|
461
|
+
catch (e) {
|
|
462
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
463
|
+
this.deps.audit.log({
|
|
464
|
+
ts: new Date().toISOString(),
|
|
465
|
+
reqId,
|
|
466
|
+
sessionId: ctx.sessionId,
|
|
467
|
+
keyId: ctx.keyId,
|
|
468
|
+
tool: `prompt:${publicName}`,
|
|
469
|
+
server: target.server.name,
|
|
470
|
+
originalTool: target.original,
|
|
471
|
+
durationMs: Date.now() - t0,
|
|
472
|
+
status: 'error',
|
|
473
|
+
errorCode: 'downstream_error',
|
|
474
|
+
errorMessage: truncate(message, 1000).text,
|
|
475
|
+
args,
|
|
476
|
+
});
|
|
477
|
+
throw new McpError(-32000, `prompt failed: ${truncate(message, 500).text}`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
// Per-session audit context for HTTP sessions. The SDK Server handlers are
|
|
482
|
+
// registered once per server instance; tagSession stores the context here.
|
|
483
|
+
const sessionContext = new WeakMap();
|
|
484
|
+
const VALID_UPSTREAM_SCOPES = ['tools:call', 'tools:list', 'resources:*', 'prompts:*', 'admin'];
|
|
485
|
+
/** Map an MCP method to the scope required to call it (null = any authed key). */
|
|
486
|
+
export function scopeForMethod(method) {
|
|
487
|
+
if (method === 'tools/call')
|
|
488
|
+
return 'tools:call';
|
|
489
|
+
if (method === 'tools/list')
|
|
490
|
+
return 'tools:list';
|
|
491
|
+
if (method === 'resources/list' || method === 'resources/read' || method === 'resources/subscribe' || method === 'resources/unsubscribe') {
|
|
492
|
+
return 'resources:*';
|
|
493
|
+
}
|
|
494
|
+
if (method === 'prompts/list' || method === 'prompts/get')
|
|
495
|
+
return 'prompts:*';
|
|
496
|
+
return null; // initialize, ping, notifications, completion — any authed key
|
|
497
|
+
}
|
|
498
|
+
/** Host header matches an entry exactly, or by hostname when the entry has no port. */
|
|
499
|
+
function hostAllowed(host, allowed) {
|
|
500
|
+
const h = host.toLowerCase();
|
|
501
|
+
const name = h.startsWith('[') ? h.slice(0, h.indexOf(']') + 1) : h.split(':')[0];
|
|
502
|
+
return allowed.some((a) => a.toLowerCase() === h || a.toLowerCase() === name);
|
|
503
|
+
}
|
|
504
|
+
function truncateName(name) {
|
|
505
|
+
return name.length > 120 ? name.slice(0, 120) + '…' : name;
|
|
506
|
+
}
|
|
507
|
+
function readBody(req, res) {
|
|
508
|
+
return new Promise((resolve) => {
|
|
509
|
+
const chunks = [];
|
|
510
|
+
let size = 0;
|
|
511
|
+
let done = false;
|
|
512
|
+
const fail = (code, error) => {
|
|
513
|
+
if (done)
|
|
514
|
+
return;
|
|
515
|
+
done = true;
|
|
516
|
+
if (!res.headersSent) {
|
|
517
|
+
res.writeHead(code, { 'content-type': 'application/json' });
|
|
518
|
+
res.end(JSON.stringify({ error }));
|
|
519
|
+
}
|
|
520
|
+
resolve(null);
|
|
521
|
+
};
|
|
522
|
+
req.on('data', (chunk) => {
|
|
523
|
+
size += chunk.length;
|
|
524
|
+
if (size > MAX_BODY_BYTES) {
|
|
525
|
+
fail(413, 'request body too large');
|
|
526
|
+
req.destroy();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
chunks.push(chunk);
|
|
530
|
+
});
|
|
531
|
+
req.on('end', () => {
|
|
532
|
+
if (done)
|
|
533
|
+
return;
|
|
534
|
+
done = true;
|
|
535
|
+
try {
|
|
536
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
fail(400, 'invalid JSON body');
|
|
540
|
+
resolve(null);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
req.on('error', () => fail(400, 'error reading body'));
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
//# sourceMappingURL=upstream.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Unique id for correlating audit records, metrics and error responses. */
|
|
2
|
+
export declare function newRequestId(): string;
|
|
3
|
+
export declare function sleep(ms: number): Promise<void>;
|
|
4
|
+
/** Rejects with `label` after ms; clears the timer when the promise settles. */
|
|
5
|
+
export declare function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T>;
|
|
6
|
+
/** Truncate a string, appending a marker so truncation is visible. */
|
|
7
|
+
export declare function truncate(s: string, maxChars: number): {
|
|
8
|
+
text: string;
|
|
9
|
+
truncated: boolean;
|
|
10
|
+
};
|
|
11
|
+
/** JSON.stringify that never throws (circular refs -> placeholder). */
|
|
12
|
+
export declare function safeJsonStringify(value: unknown): string;
|
|
13
|
+
export declare function nowIso(): string;
|
|
14
|
+
/**
|
|
15
|
+
* Glob match where only `*` is special (matches any run of characters).
|
|
16
|
+
* Everything else is matched literally, so patterns can never ReDoS.
|
|
17
|
+
*/
|
|
18
|
+
export declare function globMatch(pattern: string, value: string): boolean;
|
|
19
|
+
//# sourceMappingURL=util.d.ts.map
|
package/dist/src/util.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Small shared helpers. No dependencies. */
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
/** Unique id for correlating audit records, metrics and error responses. */
|
|
4
|
+
export function newRequestId() {
|
|
5
|
+
return randomUUID();
|
|
6
|
+
}
|
|
7
|
+
export function sleep(ms) {
|
|
8
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
9
|
+
}
|
|
10
|
+
/** Rejects with `label` after ms; clears the timer when the promise settles. */
|
|
11
|
+
export function withTimeout(promise, ms, label) {
|
|
12
|
+
let timer;
|
|
13
|
+
const timeout = new Promise((_, reject) => {
|
|
14
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
|
|
15
|
+
});
|
|
16
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
17
|
+
if (timer !== undefined)
|
|
18
|
+
clearTimeout(timer);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Truncate a string, appending a marker so truncation is visible. */
|
|
22
|
+
export function truncate(s, maxChars) {
|
|
23
|
+
if (s.length <= maxChars)
|
|
24
|
+
return { text: s, truncated: false };
|
|
25
|
+
return { text: s.slice(0, maxChars) + '…[truncated]', truncated: true };
|
|
26
|
+
}
|
|
27
|
+
/** JSON.stringify that never throws (circular refs -> placeholder). */
|
|
28
|
+
export function safeJsonStringify(value) {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.stringify(value) ?? 'null';
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return '"[unserializable]"';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function nowIso() {
|
|
37
|
+
return new Date().toISOString();
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Glob match where only `*` is special (matches any run of characters).
|
|
41
|
+
* Everything else is matched literally, so patterns can never ReDoS.
|
|
42
|
+
*/
|
|
43
|
+
export function globMatch(pattern, value) {
|
|
44
|
+
const escaped = pattern.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'));
|
|
45
|
+
return new RegExp(`^${escaped.join('.*')}$`).test(value);
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Gateway version, read from package.json at runtime (single source of truth). */
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
function readVersion() {
|
|
6
|
+
try {
|
|
7
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
|
8
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
|
|
9
|
+
return typeof pkg.version === 'string' ? pkg.version : '0.0.0';
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return '0.0.0';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export const VERSION = readVersion();
|
|
16
|
+
//# sourceMappingURL=version.js.map
|