@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,58 @@
1
+ /**
2
+ * Minimal Prometheus metrics registry — hand-rolled exposition format, zero deps.
3
+ *
4
+ * Metric names are fixed by the gateway (no user input in names). Label VALUES
5
+ * come from tool/server names; they are escaped per the Prometheus exposition
6
+ * format (backslash, double-quote, newline). Cardinality is bounded by the
7
+ * tool catalog, not by request content — args never become labels.
8
+ */
9
+ export type LabelSet = Record<string, string>;
10
+ declare class Counter {
11
+ private name;
12
+ private help;
13
+ private values;
14
+ private labelMap;
15
+ constructor(name: string, help: string);
16
+ inc(labels?: LabelSet, by?: number): void;
17
+ render(): string;
18
+ }
19
+ declare class Gauge {
20
+ private name;
21
+ private help;
22
+ private values;
23
+ private labelMap;
24
+ constructor(name: string, help: string);
25
+ set(labels: LabelSet, v: number): void;
26
+ inc(labels?: LabelSet, by?: number): void;
27
+ dec(labels?: LabelSet, by?: number): void;
28
+ render(): string;
29
+ }
30
+ declare class Histogram {
31
+ private name;
32
+ private help;
33
+ private buckets;
34
+ private counts;
35
+ private sums;
36
+ private labelMap;
37
+ constructor(name: string, help: string, buckets?: number[]);
38
+ observe(labels: LabelSet, v: number): void;
39
+ render(): string;
40
+ }
41
+ export declare class Metrics {
42
+ readonly toolCalls: Counter;
43
+ readonly policyDenials: Counter;
44
+ readonly rateLimitHits: Counter;
45
+ readonly auditErrors: Counter;
46
+ readonly upstreamErrors: Counter;
47
+ readonly pinMismatch: Counter;
48
+ readonly hiddenCharsTools: Gauge;
49
+ readonly httpRejected: Counter;
50
+ readonly serverUp: Gauge;
51
+ readonly serverInflight: Gauge;
52
+ readonly gatewayInflight: Gauge;
53
+ readonly buildInfo: Gauge;
54
+ readonly toolDuration: Histogram;
55
+ render(): string;
56
+ }
57
+ export {};
58
+ //# sourceMappingURL=metrics.d.ts.map
@@ -0,0 +1,138 @@
1
+ function escapeLabelValue(v) {
2
+ return v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
3
+ }
4
+ function labelString(labels) {
5
+ const parts = Object.entries(labels).map(([k, v]) => `${k}="${escapeLabelValue(v)}"`);
6
+ return parts.length > 0 ? `{${parts.join(',')}}` : '';
7
+ }
8
+ class Counter {
9
+ name;
10
+ help;
11
+ values = new Map();
12
+ labelMap = new Map();
13
+ constructor(name, help) {
14
+ this.name = name;
15
+ this.help = help;
16
+ }
17
+ inc(labels = {}, by = 1) {
18
+ const k = JSON.stringify(labels);
19
+ this.values.set(k, (this.values.get(k) ?? 0) + by);
20
+ this.labelMap.set(k, labels);
21
+ }
22
+ render() {
23
+ let out = `# HELP ${this.name} ${this.help}\n# TYPE ${this.name} counter\n`;
24
+ for (const [k, v] of this.values) {
25
+ out += `${this.name}${labelString(this.labelMap.get(k) ?? {})} ${v}\n`;
26
+ }
27
+ return out;
28
+ }
29
+ }
30
+ class Gauge {
31
+ name;
32
+ help;
33
+ values = new Map();
34
+ labelMap = new Map();
35
+ constructor(name, help) {
36
+ this.name = name;
37
+ this.help = help;
38
+ }
39
+ set(labels, v) {
40
+ const k = JSON.stringify(labels);
41
+ this.values.set(k, v);
42
+ this.labelMap.set(k, labels);
43
+ }
44
+ inc(labels = {}, by = 1) {
45
+ const k = JSON.stringify(labels);
46
+ this.values.set(k, (this.values.get(k) ?? 0) + by);
47
+ this.labelMap.set(k, labels);
48
+ }
49
+ dec(labels = {}, by = 1) {
50
+ this.inc(labels, -by);
51
+ }
52
+ render() {
53
+ let out = `# HELP ${this.name} ${this.help}\n# TYPE ${this.name} gauge\n`;
54
+ for (const [k, v] of this.values) {
55
+ out += `${this.name}${labelString(this.labelMap.get(k) ?? {})} ${v}\n`;
56
+ }
57
+ return out;
58
+ }
59
+ }
60
+ const DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
61
+ class Histogram {
62
+ name;
63
+ help;
64
+ buckets;
65
+ counts = new Map();
66
+ sums = new Map();
67
+ labelMap = new Map();
68
+ constructor(name, help, buckets = DEFAULT_BUCKETS) {
69
+ this.name = name;
70
+ this.help = help;
71
+ this.buckets = [...buckets].sort((a, b) => a - b);
72
+ }
73
+ observe(labels, v) {
74
+ const k = JSON.stringify(labels);
75
+ let arr = this.counts.get(k);
76
+ if (arr === undefined) {
77
+ arr = new Array(this.buckets.length + 1).fill(0);
78
+ this.counts.set(k, arr);
79
+ this.labelMap.set(k, labels);
80
+ this.sums.set(k, 0);
81
+ }
82
+ for (let i = 0; i < this.buckets.length; i++) {
83
+ if (v <= this.buckets[i])
84
+ arr[i] += 1;
85
+ }
86
+ arr[this.buckets.length] += 1; // +Inf
87
+ this.sums.set(k, (this.sums.get(k) ?? 0) + v);
88
+ }
89
+ render() {
90
+ let out = `# HELP ${this.name} ${this.help}\n# TYPE ${this.name} histogram\n`;
91
+ for (const [k, arr] of this.counts) {
92
+ const labels = this.labelMap.get(k) ?? {};
93
+ const base = labelString(labels);
94
+ const inner = base === '' ? '' : base.slice(1, -1);
95
+ const withLe = (le) => (inner === '' ? `{le="${le}"}` : `{${inner},le="${le}"}`);
96
+ for (let i = 0; i < this.buckets.length; i++) {
97
+ out += `${this.name}_bucket${withLe(String(this.buckets[i]))} ${arr[i]}\n`;
98
+ }
99
+ out += `${this.name}_bucket${withLe('+Inf')} ${arr[this.buckets.length]}\n`;
100
+ out += `${this.name}_sum${base} ${this.sums.get(k) ?? 0}\n`;
101
+ out += `${this.name}_count${base} ${arr[this.buckets.length]}\n`;
102
+ }
103
+ return out;
104
+ }
105
+ }
106
+ export class Metrics {
107
+ toolCalls = new Counter('mcpgateway_tool_calls_total', 'Tool calls routed by the gateway, by outcome.');
108
+ policyDenials = new Counter('mcpgateway_policy_denials_total', 'Tool calls denied by fleet policy.');
109
+ rateLimitHits = new Counter('mcpgateway_rate_limit_hits_total', 'Tool calls rejected by rate limiting.');
110
+ auditErrors = new Counter('mcpgateway_audit_errors_total', 'Audit log write failures (never fatal to requests).');
111
+ upstreamErrors = new Counter('mcpgateway_upstream_errors_total', 'Upstream transport errors.');
112
+ pinMismatch = new Counter('mcpgateway_pin_mismatch_total', 'Tool definitions that no longer match their pin.');
113
+ hiddenCharsTools = new Gauge('mcpgateway_hidden_chars_tools', 'Tools whose metadata contains invisible characters.');
114
+ httpRejected = new Counter('mcpgateway_http_rejected_total', 'HTTP upstream requests rejected by the Origin/Host check.');
115
+ serverUp = new Gauge('mcpgateway_server_up', '1 when the downstream server is connected and healthy.');
116
+ serverInflight = new Gauge('mcpgateway_server_inflight', 'Tool calls currently executing per downstream server.');
117
+ gatewayInflight = new Gauge('mcpgateway_gateway_inflight', 'Tool calls currently executing across the gateway.');
118
+ buildInfo = new Gauge('mcpgateway_build_info', 'Gateway build info.');
119
+ toolDuration = new Histogram('mcpgateway_tool_call_duration_seconds', 'Tool call duration in seconds.');
120
+ render() {
121
+ return [
122
+ this.buildInfo.render(),
123
+ this.toolCalls.render(),
124
+ this.policyDenials.render(),
125
+ this.rateLimitHits.render(),
126
+ this.auditErrors.render(),
127
+ this.upstreamErrors.render(),
128
+ this.httpRejected.render(),
129
+ this.pinMismatch.render(),
130
+ this.hiddenCharsTools.render(),
131
+ this.serverUp.render(),
132
+ this.serverInflight.render(),
133
+ this.gatewayInflight.render(),
134
+ this.toolDuration.render(),
135
+ ].join('');
136
+ }
137
+ }
138
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Unified namespace construction with collision resolution.
3
+ *
4
+ * Strategies (per blueprint D1):
5
+ * - prefix (default): every tool on a colliding name becomes
6
+ * `<server><sep><tool>` — deterministic, no silent shadowing.
7
+ * - priority: the highest-priority server keeps the bare name; losers are
8
+ * prefixed (still reachable). Every shadowing is reported.
9
+ * - explicit: namespace.mappings[toolName] names the winning server for each
10
+ * collision; unmapped collisions are a hard error (fail-closed).
11
+ *
12
+ * Aliases (`aliases: {"<server>:<tool>": "<publicName>"}`) apply after the
13
+ * strategy and let operators pick friendly names.
14
+ *
15
+ * The generic core (resolveNames) works for any named catalog entries
16
+ * (tools, prompts). Resource URIs are namespaced separately (see upstream).
17
+ */
18
+ import type { NamespaceConfig } from './config.js';
19
+ export interface CatalogTool {
20
+ name: string;
21
+ description?: string;
22
+ inputSchema?: unknown;
23
+ }
24
+ export interface ServerCatalog {
25
+ server: string;
26
+ tools: CatalogTool[];
27
+ }
28
+ export interface ToolEntry extends CatalogTool {
29
+ publicName: string;
30
+ server: string;
31
+ originalName: string;
32
+ }
33
+ export interface CollisionReport {
34
+ originalName: string;
35
+ servers: string[];
36
+ strategy: string;
37
+ /** public names the colliding tools resolved to, in server order */
38
+ resolvedAs: string[];
39
+ /** servers whose tools lost the bare name (priority/explicit) */
40
+ shadowed: string[];
41
+ /** winner server for priority/explicit */
42
+ winner?: string;
43
+ }
44
+ export interface NamespaceResult {
45
+ tools: ToolEntry[];
46
+ byPublicName: Map<string, ToolEntry>;
47
+ collisions: CollisionReport[];
48
+ warnings: string[];
49
+ }
50
+ export declare class NamespaceError extends Error {
51
+ constructor(message: string);
52
+ }
53
+ export interface NameCatalog {
54
+ server: string;
55
+ names: string[];
56
+ }
57
+ export interface ResolvedNames {
58
+ /** "server\0originalName" -> publicName */
59
+ assigned: Map<string, string>;
60
+ collisions: CollisionReport[];
61
+ warnings: string[];
62
+ }
63
+ export declare function resolveNames(catalogs: NameCatalog[], cfg: NamespaceConfig): ResolvedNames;
64
+ export declare function buildNamespace(catalogs: ServerCatalog[], cfg: NamespaceConfig): NamespaceResult;
65
+ //# sourceMappingURL=namespace.d.ts.map
@@ -0,0 +1,131 @@
1
+ export class NamespaceError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = 'NamespaceError';
5
+ }
6
+ }
7
+ const NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
8
+ export function resolveNames(catalogs, cfg) {
9
+ const warnings = [];
10
+ const collisions = [];
11
+ const byOriginal = new Map();
12
+ for (const cat of catalogs) {
13
+ for (const n of cat.names) {
14
+ if (!NAME_RE.test(n)) {
15
+ warnings.push(`server "${cat.server}" exposes illegal name "${n}" — skipped`);
16
+ continue;
17
+ }
18
+ const group = byOriginal.get(n) ?? [];
19
+ group.push(cat.server);
20
+ byOriginal.set(n, group);
21
+ }
22
+ }
23
+ const firstSeenOrder = [];
24
+ for (const cat of catalogs)
25
+ if (!firstSeenOrder.includes(cat.server))
26
+ firstSeenOrder.push(cat.server);
27
+ const priorityRank = (server) => {
28
+ const i = cfg.priority.indexOf(server);
29
+ if (i !== -1)
30
+ return i;
31
+ return cfg.priority.length + firstSeenOrder.indexOf(server);
32
+ };
33
+ const assigned = new Map();
34
+ for (const [origName, servers] of byOriginal) {
35
+ if (servers.length === 1) {
36
+ assigned.set(`${servers[0]}\0${origName}`, origName);
37
+ continue;
38
+ }
39
+ const sorted = [...servers].sort((a, b) => priorityRank(a) - priorityRank(b));
40
+ if (cfg.strategy === 'prefix') {
41
+ const resolvedAs = sorted.map((s) => `${s}${cfg.separator}${origName}`);
42
+ collisions.push({ originalName: origName, servers: sorted, strategy: 'prefix', resolvedAs, shadowed: [] });
43
+ sorted.forEach((s, i) => assigned.set(`${s}\0${origName}`, resolvedAs[i]));
44
+ }
45
+ else if (cfg.strategy === 'priority') {
46
+ const winner = sorted[0];
47
+ const losers = sorted.slice(1);
48
+ const resolvedAs = [origName, ...losers.map((s) => `${s}${cfg.separator}${origName}`)];
49
+ collisions.push({ originalName: origName, servers: sorted, strategy: 'priority', resolvedAs, shadowed: losers, winner });
50
+ warnings.push(`collision on "${origName}": "${winner}" keeps the bare name; shadowed: ${losers.join(', ')} (reachable as prefixed names)`);
51
+ assigned.set(`${winner}\0${origName}`, origName);
52
+ for (const s of losers)
53
+ assigned.set(`${s}\0${origName}`, `${s}${cfg.separator}${origName}`);
54
+ }
55
+ else {
56
+ const winner = cfg.mappings[origName];
57
+ if (winner === undefined || !servers.includes(winner)) {
58
+ throw new NamespaceError(`collision on "${origName}" (servers: ${servers.join(', ')}) has no namespace.mappings entry — ` +
59
+ `add 'mappings: {"${origName}": "<winning-server>"}' or switch strategy`);
60
+ }
61
+ const losers = sorted.filter((s) => s !== winner);
62
+ const resolvedAs = [origName, ...losers.map((s) => `${s}${cfg.separator}${origName}`)];
63
+ collisions.push({ originalName: origName, servers: sorted, strategy: 'explicit', resolvedAs, shadowed: losers, winner });
64
+ assigned.set(`${winner}\0${origName}`, origName);
65
+ for (const s of losers)
66
+ assigned.set(`${s}\0${origName}`, `${s}${cfg.separator}${origName}`);
67
+ }
68
+ }
69
+ // Aliases override the strategy assignment.
70
+ for (const [from, to] of Object.entries(cfg.aliases)) {
71
+ const sepIdx = from.indexOf(':');
72
+ const srv = from.slice(0, sepIdx);
73
+ const orig = from.slice(sepIdx + 1);
74
+ const key = `${srv}\0${orig}`;
75
+ if (!assigned.has(key)) {
76
+ throw new NamespaceError(`namespace.aliases["${from}"]: no such tool (server "${srv}" has no tool "${orig}")`);
77
+ }
78
+ assigned.set(key, to);
79
+ }
80
+ // Global validation: uniqueness + legality of every public name.
81
+ const seenPublic = new Map();
82
+ for (const [key, publicName] of assigned) {
83
+ if (!NAME_RE.test(publicName)) {
84
+ const [srv, orig] = key.split('\0');
85
+ throw new NamespaceError(`public name "${publicName}" for ${srv}:${orig} is illegal (names must match ^[a-zA-Z0-9_-]{1,64}$) — ` +
86
+ `shorten the server name or add an alias`);
87
+ }
88
+ const prev = seenPublic.get(publicName);
89
+ if (prev !== undefined) {
90
+ const [srv, orig] = key.split('\0');
91
+ const [psrv, porig] = prev.split('\0');
92
+ throw new NamespaceError(`public name collision: "${publicName}" would name both ${psrv}:${porig} and ${srv}:${orig} — ` +
93
+ `add namespace.aliases entries to disambiguate`);
94
+ }
95
+ seenPublic.set(publicName, key);
96
+ }
97
+ return { assigned, collisions, warnings };
98
+ }
99
+ // ---------------------------------------------------------------------------
100
+ // Tool-specific wrapper (keeps descriptions + schemas attached)
101
+ // ---------------------------------------------------------------------------
102
+ export function buildNamespace(catalogs, cfg) {
103
+ const nameCatalogs = catalogs.map((c) => ({ server: c.server, names: c.tools.map((t) => t.name) }));
104
+ const { assigned, collisions, warnings } = resolveNames(nameCatalogs, cfg);
105
+ const toolLookup = new Map();
106
+ for (const cat of catalogs) {
107
+ for (const t of cat.tools)
108
+ toolLookup.set(`${cat.server}\0${t.name}`, t);
109
+ }
110
+ const tools = [];
111
+ const byPublicName = new Map();
112
+ for (const [key, publicName] of assigned) {
113
+ const [srv, orig] = key.split('\0');
114
+ const tool = toolLookup.get(key);
115
+ if (tool === undefined)
116
+ continue; // skipped illegal name
117
+ const entry = {
118
+ name: publicName,
119
+ publicName,
120
+ server: srv,
121
+ originalName: orig,
122
+ description: tool.description,
123
+ inputSchema: tool.inputSchema,
124
+ };
125
+ tools.push(entry);
126
+ byPublicName.set(publicName, entry);
127
+ }
128
+ tools.sort((a, b) => a.publicName.localeCompare(b.publicName));
129
+ return { tools, byPublicName, collisions, warnings };
130
+ }
131
+ //# sourceMappingURL=namespace.js.map
@@ -0,0 +1,35 @@
1
+ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
2
+ import type { AuditLogger } from './audit.js';
3
+ import type { Metrics } from './metrics.js';
4
+ export type PinningMode = 'off' | 'warn' | 'quarantine';
5
+ export declare function fingerprint(tool: Tool): string;
6
+ /** Bytes of a pins file: sorted keys, trailing newline (stable for diffs). */
7
+ export declare function pinsFileContent(catalogs: Array<{
8
+ server: string;
9
+ tools: Tool[];
10
+ }>): string;
11
+ export declare function loadPinsFile(path: string): Map<string, string>;
12
+ export declare class PinGuard {
13
+ private mode;
14
+ private audit;
15
+ private metrics;
16
+ private pins;
17
+ /** definitions seen matching their pin, so a later change can name its fields */
18
+ private pinnedDefs;
19
+ /** last hash reported per tool, so rebuilds don't repeat the same event */
20
+ private reported;
21
+ private tofuPending;
22
+ private mismatched;
23
+ constructor(mode: PinningMode, file: string | undefined, audit: AuditLogger, metrics: Metrics);
24
+ /** Tools currently not matching their pin. */
25
+ get mismatchCount(): number;
26
+ /**
27
+ * Compare every tool with its pin; audit + count changes. Returns the
28
+ * "<server>\0<name>" keys to hold back (quarantine mode only).
29
+ */
30
+ check(catalogs: Array<{
31
+ server: string;
32
+ tools: Tool[];
33
+ }>): Set<string>;
34
+ }
35
+ //# sourceMappingURL=pinning.d.ts.map
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Tool-definition pinning (rug-pull guard).
3
+ *
4
+ * A pin is the sha256 of a tool's canonical definition (name, title,
5
+ * description, inputSchema, outputSchema, annotations; keys sorted
6
+ * recursively), keyed "<server>:<originalName>". Pins come from a file written
7
+ * by `mcpgateway pin`, or are taken on first sight at startup (TOFU).
8
+ *
9
+ * Pinning detects definition changes. It cannot detect a server that keeps its
10
+ * definition and changes behaviour.
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { readFileSync } from 'node:fs';
14
+ import { newRequestId } from './util.js';
15
+ const PINNED_FIELDS = ['name', 'title', 'description', 'inputSchema', 'outputSchema', 'annotations'];
16
+ function canonical(v) {
17
+ if (Array.isArray(v))
18
+ return v.map(canonical);
19
+ if (v !== null && typeof v === 'object') {
20
+ const out = {};
21
+ for (const k of Object.keys(v).sort())
22
+ out[k] = canonical(v[k]);
23
+ return out;
24
+ }
25
+ return v;
26
+ }
27
+ const sha = (v) => createHash('sha256').update(JSON.stringify(canonical(v)) ?? 'null').digest('hex');
28
+ function definition(tool) {
29
+ const out = {};
30
+ for (const f of PINNED_FIELDS)
31
+ if (tool[f] !== undefined)
32
+ out[f] = tool[f];
33
+ return out;
34
+ }
35
+ export function fingerprint(tool) {
36
+ return sha(definition(tool));
37
+ }
38
+ /** Bytes of a pins file: sorted keys, trailing newline (stable for diffs). */
39
+ export function pinsFileContent(catalogs) {
40
+ const pins = {};
41
+ for (const c of catalogs)
42
+ for (const t of c.tools)
43
+ pins[`${c.server}:${t.name}`] = fingerprint(t);
44
+ return JSON.stringify({ version: 1, pins: canonical(pins) }, null, 2) + '\n';
45
+ }
46
+ export function loadPinsFile(path) {
47
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
48
+ const pins = parsed.pins;
49
+ if (parsed.version !== 1 || pins === null || typeof pins !== 'object' || !Object.values(pins).every((v) => typeof v === 'string')) {
50
+ throw new Error(`${path}: not a version-1 pins file (regenerate with \`mcpgateway pin\`)`);
51
+ }
52
+ return new Map(Object.entries(pins));
53
+ }
54
+ export class PinGuard {
55
+ mode;
56
+ audit;
57
+ metrics;
58
+ pins;
59
+ /** definitions seen matching their pin, so a later change can name its fields */
60
+ pinnedDefs = new Map();
61
+ /** last hash reported per tool, so rebuilds don't repeat the same event */
62
+ reported = new Map();
63
+ tofuPending;
64
+ mismatched = new Set();
65
+ constructor(mode, file, audit, metrics) {
66
+ this.mode = mode;
67
+ this.audit = audit;
68
+ this.metrics = metrics;
69
+ this.pins = file !== undefined ? loadPinsFile(file) : new Map();
70
+ this.tofuPending = file === undefined;
71
+ }
72
+ /** Tools currently not matching their pin. */
73
+ get mismatchCount() {
74
+ return this.mismatched.size;
75
+ }
76
+ /**
77
+ * Compare every tool with its pin; audit + count changes. Returns the
78
+ * "<server>\0<name>" keys to hold back (quarantine mode only).
79
+ */
80
+ check(catalogs) {
81
+ const held = new Set();
82
+ if (this.mode === 'off')
83
+ return held;
84
+ const tofu = this.tofuPending;
85
+ this.tofuPending = false;
86
+ this.mismatched.clear();
87
+ for (const { server, tools } of catalogs) {
88
+ for (const tool of tools) {
89
+ const key = `${server}:${tool.name}`;
90
+ const def = definition(tool);
91
+ const hash = sha(def);
92
+ const pin = this.pins.get(key);
93
+ if (pin === undefined && tofu) {
94
+ this.pins.set(key, hash);
95
+ this.pinnedDefs.set(key, def);
96
+ continue;
97
+ }
98
+ if (pin === hash) {
99
+ this.pinnedDefs.set(key, def);
100
+ this.reported.delete(key);
101
+ continue;
102
+ }
103
+ if (this.mode === 'quarantine')
104
+ held.add(`${server}\0${tool.name}`);
105
+ if (pin !== undefined)
106
+ this.mismatched.add(key);
107
+ if (this.reported.get(key) === hash)
108
+ continue;
109
+ this.reported.set(key, hash);
110
+ const old = this.pinnedDefs.get(key);
111
+ const fields = old === undefined ? undefined
112
+ : PINNED_FIELDS.filter((f) => sha(old[f]) !== sha(def[f]));
113
+ if (pin !== undefined)
114
+ this.metrics.pinMismatch.inc({ server });
115
+ this.audit.log({
116
+ ts: new Date().toISOString(),
117
+ reqId: newRequestId(),
118
+ tool: tool.name,
119
+ server,
120
+ originalTool: tool.name,
121
+ durationMs: 0,
122
+ status: pin === undefined ? 'pin_new' : 'pin_mismatch',
123
+ policyReason: this.mode === 'quarantine' ? 'quarantined' : undefined,
124
+ pin: { old: pin, new: hash, fields },
125
+ });
126
+ }
127
+ }
128
+ return held;
129
+ }
130
+ }
131
+ //# sourceMappingURL=pinning.js.map
@@ -0,0 +1,31 @@
1
+ import type { PolicyConfig } from './config.js';
2
+ export type ToolDecision = 'allow' | 'deny';
3
+ export interface ToolVerdict {
4
+ decision: ToolDecision;
5
+ /** machine-readable reason: allow|deny_list|not_allow_listed|arg_deny|arg_allow_miss */
6
+ reason: string;
7
+ detail: string;
8
+ }
9
+ export interface ResponseVerdict {
10
+ action: 'pass' | 'block';
11
+ /** result after structured redaction (null when blocked) */
12
+ result: unknown;
13
+ redactions: number;
14
+ warnings: string[];
15
+ blockedBy?: string;
16
+ }
17
+ /** Is the tool visible in listings? Hidden tools are also denied on call. */
18
+ export declare function isHidden(policy: PolicyConfig, publicToolName: string): boolean;
19
+ export declare function checkToolCall(policy: PolicyConfig, publicToolName: string, args: unknown): ToolVerdict;
20
+ /**
21
+ * Scan a tool result per response rules.
22
+ *
23
+ * Detection (warn/block) runs over the JSON-encoded result, bounded to the
24
+ * first `scanWindowChars` characters (a 10MB result must not stall the
25
+ * gateway). Redaction walks the STRUCTURED value and rewrites string keys
26
+ * and values — never the serialized JSON text, so redaction can never
27
+ * produce invalid JSON (scrutiny finding: a pattern landing inside a JSON
28
+ * escape sequence used to break JSON.parse).
29
+ */
30
+ export declare function checkResponse(policy: PolicyConfig, result: unknown): ResponseVerdict;
31
+ //# sourceMappingURL=policy.d.ts.map