@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.
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Fleet-wide policy engine — mcp-leash-style semantics applied at the gateway.
3
+ *
4
+ * Division of labor (blueprint D4):
5
+ * gateway policy = WHICH tools exist fleet-wide, WHO may call them, HOW OFTEN
6
+ * mcp-leash = per-server argument rules (separate tool)
7
+ * They compose; the gateway does not duplicate its argument rules.
8
+ *
9
+ * Precedence: deny_tools wins over allow_tools. hide_tools removes tools from
10
+ * listings (agents can't see what they can't call). argRules are SUBSTRING
11
+ * matchers on the JSON-encoded arguments (deliberately not regex — ReDoS).
12
+ * response rules scan the JSON-encoded result (bounded window).
13
+ */
14
+ import { globMatch, safeJsonStringify } from './util.js';
15
+ const REDACTED = '[REDACTED]';
16
+ /** Is the tool visible in listings? Hidden tools are also denied on call. */
17
+ export function isHidden(policy, publicToolName) {
18
+ return matchesAnyGlob(policy.hideTools, publicToolName);
19
+ }
20
+ export function checkToolCall(policy, publicToolName, args) {
21
+ // Hidden tools are denied outright (defense in depth: listing filter + call gate).
22
+ if (isHidden(policy, publicToolName)) {
23
+ return { decision: 'deny', reason: 'deny_list', detail: `tool "${publicToolName}" is hidden by policy` };
24
+ }
25
+ if (matchesAnyGlob(policy.denyTools, publicToolName)) {
26
+ return { decision: 'deny', reason: 'deny_list', detail: `tool "${publicToolName}" is denied by policy` };
27
+ }
28
+ if (!matchesAnyGlob(policy.allowTools, publicToolName)) {
29
+ return { decision: 'deny', reason: 'not_allow_listed', detail: `tool "${publicToolName}" is not on the policy allow list` };
30
+ }
31
+ // Argument rules: find the most specific matching rule set (exact name beats glob).
32
+ const rule = findArgRule(policy, publicToolName);
33
+ if (rule !== undefined) {
34
+ const argsJson = safeJsonStringify(args);
35
+ if (rule.deny !== undefined) {
36
+ for (const pat of rule.deny) {
37
+ if (argsJson.includes(pat)) {
38
+ return { decision: 'deny', reason: 'arg_deny', detail: `arguments matched deny pattern for "${publicToolName}"` };
39
+ }
40
+ }
41
+ }
42
+ if (rule.allow !== undefined && rule.allow.length > 0) {
43
+ const ok = rule.allow.some((pat) => argsJson.includes(pat));
44
+ if (!ok) {
45
+ return { decision: 'deny', reason: 'arg_allow_miss', detail: `arguments matched no allow pattern for "${publicToolName}"` };
46
+ }
47
+ }
48
+ }
49
+ return { decision: 'allow', reason: 'allow', detail: '' };
50
+ }
51
+ /**
52
+ * Scan a tool result per response rules.
53
+ *
54
+ * Detection (warn/block) runs over the JSON-encoded result, bounded to the
55
+ * first `scanWindowChars` characters (a 10MB result must not stall the
56
+ * gateway). Redaction walks the STRUCTURED value and rewrites string keys
57
+ * and values — never the serialized JSON text, so redaction can never
58
+ * produce invalid JSON (scrutiny finding: a pattern landing inside a JSON
59
+ * escape sequence used to break JSON.parse).
60
+ */
61
+ export function checkResponse(policy, result) {
62
+ const window = safeJsonStringify(result).slice(0, policy.scanWindowChars);
63
+ const warnings = [];
64
+ for (const pat of policy.responseWarn) {
65
+ if (pat.length > 0 && window.includes(pat))
66
+ warnings.push('response matched warn pattern');
67
+ }
68
+ for (const pat of policy.responseBlock) {
69
+ if (pat.length > 0 && window.includes(pat)) {
70
+ return { action: 'block', result: null, redactions: 0, warnings, blockedBy: 'response_block' };
71
+ }
72
+ }
73
+ let redactions = 0;
74
+ const redactPatterns = policy.responseRedact.filter((p) => p.length > 0);
75
+ const redactString = (s) => {
76
+ let out = s;
77
+ for (const pat of redactPatterns) {
78
+ let idx = out.indexOf(pat);
79
+ while (idx !== -1) {
80
+ redactions += 1;
81
+ out = out.slice(0, idx) + REDACTED + out.slice(idx + pat.length);
82
+ idx = out.indexOf(pat, idx + REDACTED.length);
83
+ }
84
+ }
85
+ return out;
86
+ };
87
+ const walk = (v) => {
88
+ if (typeof v === 'string')
89
+ return redactString(v);
90
+ if (Array.isArray(v))
91
+ return v.map(walk);
92
+ if (v !== null && typeof v === 'object') {
93
+ const out = {};
94
+ for (const [k, val] of Object.entries(v))
95
+ out[redactString(k)] = walk(val);
96
+ return out;
97
+ }
98
+ return v;
99
+ };
100
+ return { action: 'pass', result: walk(result), redactions, warnings };
101
+ }
102
+ function matchesAnyGlob(patterns, value) {
103
+ return patterns.some((p) => globMatch(p, value));
104
+ }
105
+ function findArgRule(policy, publicToolName) {
106
+ // Exact match first, then first glob match (config order).
107
+ const exact = policy.argRules[publicToolName];
108
+ if (exact !== undefined)
109
+ return exact;
110
+ for (const [pattern, rule] of Object.entries(policy.argRules)) {
111
+ if (globMatch(pattern, publicToolName))
112
+ return rule;
113
+ }
114
+ return undefined;
115
+ }
116
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Token-bucket rate limiter with bounded memory.
3
+ *
4
+ * Buckets are created lazily per key; idle buckets are pruned, and a hard cap
5
+ * on bucket count prevents unbounded growth from high-cardinality keys.
6
+ */
7
+ import type { RateLimitRule } from './config.js';
8
+ export declare class RateLimiter {
9
+ private buckets;
10
+ private hits;
11
+ /** Try to consume one token for key under rule. Returns true if allowed. */
12
+ tryAcquire(key: string, rule: RateLimitRule): boolean;
13
+ /** Remove buckets idle longer than IDLE_PRUNE_MS. Returns count removed. */
14
+ pruneIdle(now?: number): number;
15
+ bucketCount(): number;
16
+ totalHits(): number;
17
+ private evictOldestIdle;
18
+ }
19
+ //# sourceMappingURL=ratelimit.d.ts.map
@@ -0,0 +1,62 @@
1
+ const IDLE_PRUNE_MS = 10 * 60 * 1000;
2
+ const MAX_BUCKETS = 100_000;
3
+ export class RateLimiter {
4
+ buckets = new Map();
5
+ hits = 0;
6
+ /** Try to consume one token for key under rule. Returns true if allowed. */
7
+ tryAcquire(key, rule) {
8
+ const now = Date.now();
9
+ let b = this.buckets.get(key);
10
+ if (b === undefined) {
11
+ if (this.buckets.size >= MAX_BUCKETS)
12
+ this.evictOldestIdle(now);
13
+ b = { tokens: rule.burst, lastRefill: now, lastSeen: now };
14
+ this.buckets.set(key, b);
15
+ }
16
+ // Refill proportional to elapsed time.
17
+ const elapsedSec = (now - b.lastRefill) / 1000;
18
+ b.tokens = Math.min(rule.burst, b.tokens + elapsedSec * rule.rps);
19
+ b.lastRefill = now;
20
+ b.lastSeen = now;
21
+ if (b.tokens >= 1) {
22
+ b.tokens -= 1;
23
+ return true;
24
+ }
25
+ this.hits += 1;
26
+ return false;
27
+ }
28
+ /** Remove buckets idle longer than IDLE_PRUNE_MS. Returns count removed. */
29
+ pruneIdle(now = Date.now()) {
30
+ let removed = 0;
31
+ for (const [k, b] of this.buckets) {
32
+ if (now - b.lastSeen > IDLE_PRUNE_MS) {
33
+ this.buckets.delete(k);
34
+ removed += 1;
35
+ }
36
+ }
37
+ return removed;
38
+ }
39
+ bucketCount() {
40
+ return this.buckets.size;
41
+ }
42
+ totalHits() {
43
+ return this.hits;
44
+ }
45
+ evictOldestIdle(now) {
46
+ // At the cap: drop the single oldest-idle bucket to make room. The map is
47
+ // non-empty here (we only evict at the cap), so oldestKey is always found
48
+ // and the map stays exactly at MAX_BUCKETS.
49
+ let oldestKey;
50
+ let oldestSeen = Infinity;
51
+ for (const [k, b] of this.buckets) {
52
+ if (b.lastSeen < oldestSeen) {
53
+ oldestSeen = b.lastSeen;
54
+ oldestKey = k;
55
+ }
56
+ }
57
+ if (oldestKey !== undefined)
58
+ this.buckets.delete(oldestKey);
59
+ void now;
60
+ }
61
+ }
62
+ //# sourceMappingURL=ratelimit.js.map
@@ -0,0 +1,107 @@
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 { type IncomingMessage, type Server as HttpServer } from 'node:http';
20
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
21
+ import { type Prompt, type Resource } from '@modelcontextprotocol/sdk/types.js';
22
+ import type { DownstreamServer } from './downstream.js';
23
+ import type { ToolEntry } from './namespace.js';
24
+ import type { AuditLogger } from './audit.js';
25
+ import type { Metrics } from './metrics.js';
26
+ import type { RateLimiter } from './ratelimit.js';
27
+ import { type AuthKey, type PolicyConfig, type RateLimitRule } from './config.js';
28
+ export interface RouteTarget {
29
+ server: DownstreamServer;
30
+ /** original tool/prompt name, or original resource uri */
31
+ original: string;
32
+ }
33
+ export interface PromptEntry {
34
+ publicName: string;
35
+ server: string;
36
+ originalName: string;
37
+ description?: string;
38
+ args?: Prompt['arguments'];
39
+ }
40
+ export interface RoutingTable {
41
+ tools: Map<string, RouteTarget>;
42
+ toolMeta: Map<string, ToolEntry>;
43
+ prompts: Map<string, RouteTarget>;
44
+ promptMeta: Map<string, PromptEntry>;
45
+ /** public uri -> target (original = original uri) */
46
+ resources: Map<string, RouteTarget>;
47
+ resourceMeta: Map<string, Resource>;
48
+ }
49
+ export declare const RESOURCE_SCHEME = "mcpgateway";
50
+ export declare function publicResourceUri(server: string, originalUri: string): string;
51
+ export declare function parsePublicResourceUri(publicUri: string): {
52
+ server: string;
53
+ originalUri: string;
54
+ } | null;
55
+ export interface UpstreamAuth {
56
+ disabled: boolean;
57
+ keys: AuthKey[];
58
+ }
59
+ export interface UpstreamDeps {
60
+ getTable: () => RoutingTable;
61
+ policy: PolicyConfig;
62
+ rateLimiter: RateLimiter;
63
+ defaultRateLimit: RateLimitRule;
64
+ perToolRateLimits: Record<string, RateLimitRule>;
65
+ audit: AuditLogger;
66
+ /** audit config (redact keys) — separate so error scrubbing stays consistent */
67
+ auditCfg: {
68
+ redactKeys: string[];
69
+ };
70
+ metrics: Metrics;
71
+ globalMaxInflight: number;
72
+ /** drop results larger than this (chars of JSON) — OOM guard */
73
+ maxResultChars: number;
74
+ /** max concurrent Streamable HTTP sessions — abandoned sessions can't grow forever */
75
+ httpMaxSessions: number;
76
+ /** Origin/Host allow-lists for the HTTP upstream (see config) */
77
+ httpAllowedOrigins: string[];
78
+ httpAllowedHosts: string[];
79
+ auth: UpstreamAuth;
80
+ /** operational log line (stderr) */
81
+ log: (msg: string) => void;
82
+ }
83
+ interface AuthedKey {
84
+ keyId: string;
85
+ scopes: string[];
86
+ }
87
+ export declare class GatewayUpstream {
88
+ private deps;
89
+ private inflight;
90
+ constructor(deps: UpstreamDeps);
91
+ /** Create the agent-facing MCP server. Handlers always read the CURRENT routing table. */
92
+ createMcpServer(): Server;
93
+ connectStdio(): Promise<void>;
94
+ listenHttp(host: string, port: number): Promise<HttpServer>;
95
+ private handleHttp;
96
+ /** Bearer auth for the HTTP upstream. Returns null when rejected. */
97
+ authenticateHttp(req: IncomingMessage): AuthedKey | null;
98
+ /** Per-key tool allowlist (auth.keys[].tools). No key (stdio) or no list = all tools. */
99
+ private keyMayUse;
100
+ private handleToolCall;
101
+ private handleResourceRead;
102
+ private handlePromptGet;
103
+ }
104
+ /** Map an MCP method to the scope required to call it (null = any authed key). */
105
+ export declare function scopeForMethod(method: string): string | null;
106
+ export {};
107
+ //# sourceMappingURL=upstream.d.ts.map