hmcp-gateway 0.0.2 → 0.2.0
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 +77 -0
- package/README.md +135 -9
- package/bin/hmcp-gateway.js +20 -0
- package/catalog/atlassian.yaml +41 -0
- package/catalog/brave-search.yaml +57 -0
- package/catalog/context7.yaml +42 -0
- package/catalog/fetch.yaml +37 -0
- package/catalog/figma.yaml +48 -0
- package/catalog/filesystem.yaml +48 -0
- package/catalog/git.yaml +48 -0
- package/catalog/github.yaml +103 -0
- package/catalog/huggingface.yaml +59 -0
- package/catalog/linear.yaml +47 -0
- package/catalog/memory.yaml +47 -0
- package/catalog/notion.yaml +41 -0
- package/catalog/playwright.yaml +38 -0
- package/catalog/postgres.yaml +66 -0
- package/catalog/sentry.yaml +39 -0
- package/catalog/sequential-thinking.yaml +29 -0
- package/catalog/stripe.yaml +41 -0
- package/catalog/supabase.yaml +45 -0
- package/catalog/time.yaml +49 -0
- package/dist/adopt-cli.d.ts +355 -0
- package/dist/adopt-cli.js +1885 -0
- package/dist/adopt-emit.d.ts +64 -0
- package/dist/adopt-emit.js +248 -0
- package/dist/adopt-plan.d.ts +108 -0
- package/dist/adopt-plan.js +501 -0
- package/dist/catalog.d.ts +140 -0
- package/dist/catalog.js +250 -0
- package/dist/classify.d.ts +23 -0
- package/dist/classify.js +47 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +656 -0
- package/dist/client-allow.d.ts +42 -0
- package/dist/client-allow.js +95 -0
- package/dist/client-config.d.ts +263 -0
- package/dist/client-config.js +995 -0
- package/dist/config-source.d.ts +106 -0
- package/dist/config-source.js +156 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +330 -0
- package/dist/connect-client.d.ts +51 -0
- package/dist/connect-client.js +299 -0
- package/dist/contracts.d.ts +251 -0
- package/dist/contracts.js +9 -0
- package/dist/credential.d.ts +63 -0
- package/dist/credential.js +136 -0
- package/dist/desktop-extensions.d.ts +53 -0
- package/dist/desktop-extensions.js +126 -0
- package/dist/draft.d.ts +71 -0
- package/dist/draft.js +596 -0
- package/dist/exposure-cli.d.ts +28 -0
- package/dist/exposure-cli.js +119 -0
- package/dist/gateway.d.ts +766 -0
- package/dist/gateway.js +2122 -0
- package/dist/github-doors.d.ts +162 -0
- package/dist/github-doors.js +780 -0
- package/dist/guard-install.d.ts +109 -0
- package/dist/guard-install.js +396 -0
- package/dist/guard.d.ts +265 -0
- package/dist/guard.js +975 -0
- package/dist/import-client.d.ts +184 -0
- package/dist/import-client.js +578 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +31 -0
- package/dist/notify.d.ts +44 -0
- package/dist/notify.js +93 -0
- package/dist/oauth.d.ts +139 -0
- package/dist/oauth.js +641 -0
- package/dist/observe.d.ts +10 -0
- package/dist/observe.js +26 -0
- package/dist/open.d.ts +24 -0
- package/dist/open.js +31 -0
- package/dist/packs.d.ts +119 -0
- package/dist/packs.js +131 -0
- package/dist/pin-cli.d.ts +28 -0
- package/dist/pin-cli.js +103 -0
- package/dist/probe-upstream.d.ts +31 -0
- package/dist/probe-upstream.js +377 -0
- package/dist/registry-map.d.ts +39 -0
- package/dist/registry-map.js +390 -0
- package/dist/rule-cli.d.ts +51 -0
- package/dist/rule-cli.js +412 -0
- package/dist/serve-http.d.ts +67 -0
- package/dist/serve-http.js +478 -0
- package/dist/snippet.d.ts +20 -0
- package/dist/snippet.js +826 -0
- package/dist/status-cli.d.ts +61 -0
- package/dist/status-cli.js +195 -0
- package/dist/suggest-cli.d.ts +43 -0
- package/dist/suggest-cli.js +279 -0
- package/dist/toml-edit.d.ts +43 -0
- package/dist/toml-edit.js +363 -0
- package/dist/toolname.d.ts +47 -0
- package/dist/toolname.js +149 -0
- package/dist/upstream-errors.d.ts +54 -0
- package/dist/upstream-errors.js +330 -0
- package/dist/upstream.d.ts +128 -0
- package/dist/upstream.js +413 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +11 -0
- package/package.json +51 -6
- package/packs/brave-search.yaml +20 -0
- package/packs/context7.yaml +13 -0
- package/packs/fetch.yaml +14 -0
- package/packs/filesystem.yaml +79 -0
- package/packs/git.yaml +29 -0
- package/packs/github.yaml +47 -0
- package/packs/huggingface.yaml +16 -0
- package/packs/memory.yaml +23 -0
- package/packs/playwright.yaml +41 -0
- package/packs/sequential-thinking.yaml +13 -0
- package/packs/time.yaml +14 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type AuditRecord } from "hmcp-core";
|
|
2
|
+
/**
|
|
3
|
+
* `hmcp-gateway status`: is it on, and what is it doing?
|
|
4
|
+
*
|
|
5
|
+
* Reads the config, the policy and whatever a running gateway has published
|
|
6
|
+
* to the shared store. It starts nothing and connects to no upstream, so it
|
|
7
|
+
* answers at once, works while the gateway is busy, and creates no files --
|
|
8
|
+
* a status command that left a database behind would itself change the
|
|
9
|
+
* answer to "has this ever run".
|
|
10
|
+
*/
|
|
11
|
+
export interface StatusCommandOptions {
|
|
12
|
+
readonly config: string;
|
|
13
|
+
readonly json?: boolean | undefined;
|
|
14
|
+
readonly write?: (line: string) => void;
|
|
15
|
+
/** Overridable for tests. */
|
|
16
|
+
readonly now?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface GatewayStatus {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly config: string;
|
|
21
|
+
readonly enforcement: "enforce" | "observe";
|
|
22
|
+
readonly posture: string;
|
|
23
|
+
readonly onUnclassified: string;
|
|
24
|
+
readonly upstreams: readonly string[];
|
|
25
|
+
readonly running: boolean;
|
|
26
|
+
readonly pid: number | null;
|
|
27
|
+
readonly startedAt: number | null;
|
|
28
|
+
readonly lastSeen: number | null;
|
|
29
|
+
/** Whether the running process has loaded the policy that is on disk now. Null when nothing is running. */
|
|
30
|
+
readonly policyCurrent: boolean | null;
|
|
31
|
+
/** Null when no gateway has published a tool list. */
|
|
32
|
+
readonly tools: {
|
|
33
|
+
readonly served: number;
|
|
34
|
+
readonly unclassified: number;
|
|
35
|
+
readonly withheld: number;
|
|
36
|
+
readonly switchedOff: number;
|
|
37
|
+
} | null;
|
|
38
|
+
readonly waiting: number;
|
|
39
|
+
readonly activeGrants: number;
|
|
40
|
+
readonly lastCall: Pick<AuditRecord, "ts" | "tool" | "decision" | "outcome" | "observe"> | null;
|
|
41
|
+
readonly last24h: {
|
|
42
|
+
readonly calls: number;
|
|
43
|
+
readonly allow: number;
|
|
44
|
+
readonly approve: number;
|
|
45
|
+
readonly deny: number;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Tools that advertised something different from what was pinned, as
|
|
49
|
+
* recorded. From the log, so this says what has happened rather than what
|
|
50
|
+
* is true this second.
|
|
51
|
+
*/
|
|
52
|
+
readonly contractChanges: readonly {
|
|
53
|
+
readonly tool: string;
|
|
54
|
+
readonly ts: string;
|
|
55
|
+
readonly denied: boolean;
|
|
56
|
+
}[];
|
|
57
|
+
readonly auditPath: string;
|
|
58
|
+
readonly storePath: string;
|
|
59
|
+
}
|
|
60
|
+
export declare function gatewayStatus(configPath: string, now?: number): GatewayStatus;
|
|
61
|
+
export declare function runStatusCommand(options: StatusCommandOptions): Promise<void>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { ApprovalStore, NO_TENANT, expandPath, policyDigest, queryAuditLog, TOOL_CHANGED_RULE, runtimeStateIsLive } from "hmcp-core";
|
|
4
|
+
import { loadGatewayConfig } from "./config.js";
|
|
5
|
+
import { resolveProcessTenant } from "./gateway.js";
|
|
6
|
+
const ago = (then, now) => {
|
|
7
|
+
const s = Math.max(0, Math.round((now - then) / 1000));
|
|
8
|
+
if (s < 90)
|
|
9
|
+
return `${s}s ago`;
|
|
10
|
+
if (s < 5400)
|
|
11
|
+
return `${Math.round(s / 60)}m ago`;
|
|
12
|
+
if (s < 129600)
|
|
13
|
+
return `${Math.round(s / 3600)}h ago`;
|
|
14
|
+
return `${Math.round(s / 86400)}d ago`;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* A record of a tool call, as opposed to one of the gateway's own: a startup
|
|
18
|
+
* injection finding, a withheld name, a policy reload. Only a call passes
|
|
19
|
+
* through the enforcement pipeline, which is the one place a duration is set.
|
|
20
|
+
*/
|
|
21
|
+
const isCall = (r) => r.duration_ms !== null;
|
|
22
|
+
export function gatewayStatus(configPath, now = Date.now()) {
|
|
23
|
+
const full = expandPath(configPath);
|
|
24
|
+
const base = dirname(full);
|
|
25
|
+
const { config, policy } = loadGatewayConfig(full);
|
|
26
|
+
const component = `gateway:${config.name}`;
|
|
27
|
+
const storePath = expandPath(policy.approvals.store_path, base);
|
|
28
|
+
const auditPath = expandPath(policy.audit.path, base);
|
|
29
|
+
let running = false;
|
|
30
|
+
let pid = null;
|
|
31
|
+
let startedAt = null;
|
|
32
|
+
let lastSeen = null;
|
|
33
|
+
let policyCurrent = null;
|
|
34
|
+
let tools = null;
|
|
35
|
+
let waiting = 0;
|
|
36
|
+
let activeGrants = 0;
|
|
37
|
+
/** From the store: tools whose advertised contract still differs from their pin, as `pin list` sees it. */
|
|
38
|
+
let stillChanged = null;
|
|
39
|
+
if (existsSync(storePath)) {
|
|
40
|
+
const store = new ApprovalStore(storePath);
|
|
41
|
+
try {
|
|
42
|
+
const state = store.runtimeState(component);
|
|
43
|
+
if (state) {
|
|
44
|
+
running = runtimeStateIsLive(state, now);
|
|
45
|
+
pid = state.pid;
|
|
46
|
+
startedAt = state.started_at;
|
|
47
|
+
lastSeen = state.last_seen;
|
|
48
|
+
if (running)
|
|
49
|
+
policyCurrent = state.policy_digest === policyDigest(policy);
|
|
50
|
+
}
|
|
51
|
+
/*
|
|
52
|
+
* A hosted gateway has one queue per tenant and no tenant of its own, so
|
|
53
|
+
* the honest count there is across all of them; a single-tenant one is
|
|
54
|
+
* read in exactly the scope the running gateway uses.
|
|
55
|
+
*/
|
|
56
|
+
const perRequest = policy.tenant?.source.kind === "jwt-verified";
|
|
57
|
+
const tenant = perRequest ? NO_TENANT : (resolveProcessTenant(policy) ?? NO_TENANT);
|
|
58
|
+
const scoped = store.scoped({ component, tenant });
|
|
59
|
+
waiting = perRequest
|
|
60
|
+
? store.listPendingAll(1000).filter((r) => r.component === component).length
|
|
61
|
+
: scoped.listPending(1000).length;
|
|
62
|
+
activeGrants = scoped.listGrants({ activeOnly: true }).length;
|
|
63
|
+
const pins = new Map(store.listPins(component).map((p) => [p.tool, p.digest]));
|
|
64
|
+
stillChanged = store
|
|
65
|
+
.toolChanges(component)
|
|
66
|
+
.filter((c) => pins.get(c.tool) !== c.digest)
|
|
67
|
+
.map((c) => ({ tool: c.tool, ts: new Date(c.detectedAt).toISOString(), denied: c.withheld }));
|
|
68
|
+
const inventory = store.inventory(component);
|
|
69
|
+
if (inventory.length > 0) {
|
|
70
|
+
tools = {
|
|
71
|
+
served: inventory.filter((t) => !t.hidden).length,
|
|
72
|
+
unclassified: inventory.filter((t) => !t.hidden && t.effect === null).length,
|
|
73
|
+
withheld: inventory.filter((t) => t.hidden).length,
|
|
74
|
+
switchedOff: scoped.listDisabledTools().length
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
store.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const recent = queryAuditLog(auditPath, {
|
|
83
|
+
component: [component],
|
|
84
|
+
since: new Date(now - 86_400_000).toISOString(),
|
|
85
|
+
limit: 1000
|
|
86
|
+
}).records.filter(isCall);
|
|
87
|
+
const last = queryAuditLog(auditPath, { component: [component], limit: 50 }).records.find(isCall);
|
|
88
|
+
/*
|
|
89
|
+
* Contract changes come from the log rather than from asking the upstreams,
|
|
90
|
+
* because this command connects to nothing: starting every server to print
|
|
91
|
+
* a status line is the wrong trade, and the finding was already recorded
|
|
92
|
+
* when the gateway saw it. `hmcp-gateway pin list` is the live answer.
|
|
93
|
+
*/
|
|
94
|
+
const changes = queryAuditLog(auditPath, { component: [component], limit: 2000 }).records.filter((r) => r.rule_id === TOOL_CHANGED_RULE);
|
|
95
|
+
return {
|
|
96
|
+
name: config.name,
|
|
97
|
+
config: full,
|
|
98
|
+
enforcement: policy.enforcement,
|
|
99
|
+
posture: policy.defaults.mode,
|
|
100
|
+
onUnclassified: policy.defaults.on_unclassified,
|
|
101
|
+
upstreams: config.upstreams.map((u) => u.name),
|
|
102
|
+
running,
|
|
103
|
+
pid,
|
|
104
|
+
startedAt,
|
|
105
|
+
lastSeen,
|
|
106
|
+
policyCurrent,
|
|
107
|
+
tools,
|
|
108
|
+
waiting,
|
|
109
|
+
activeGrants,
|
|
110
|
+
lastCall: last
|
|
111
|
+
? {
|
|
112
|
+
ts: last.ts,
|
|
113
|
+
tool: last.tool,
|
|
114
|
+
decision: last.decision,
|
|
115
|
+
outcome: last.outcome,
|
|
116
|
+
...(last.observe ? { observe: true } : {})
|
|
117
|
+
}
|
|
118
|
+
: null,
|
|
119
|
+
/*
|
|
120
|
+
* What `pin list` and `pin accept` act on: a change that has been accepted,
|
|
121
|
+
* or that the gateway itself moved the pin past, is not reported as still
|
|
122
|
+
* changed. The log is the fallback when there is no store to read.
|
|
123
|
+
*/
|
|
124
|
+
contractChanges: stillChanged ?? changes.map((r) => ({ tool: r.tool, ts: r.ts, denied: r.decision === "deny" })),
|
|
125
|
+
last24h: {
|
|
126
|
+
calls: recent.length,
|
|
127
|
+
allow: recent.filter((r) => r.decision === "allow").length,
|
|
128
|
+
approve: recent.filter((r) => r.decision === "approve").length,
|
|
129
|
+
deny: recent.filter((r) => r.decision === "deny").length
|
|
130
|
+
},
|
|
131
|
+
auditPath,
|
|
132
|
+
storePath
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
export async function runStatusCommand(options) {
|
|
136
|
+
const write = options.write ?? ((line) => process.stdout.write(`${line}\n`));
|
|
137
|
+
const now = options.now ?? Date.now();
|
|
138
|
+
const s = gatewayStatus(options.config, now);
|
|
139
|
+
if (options.json) {
|
|
140
|
+
write(JSON.stringify(s, null, 2));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const row = (label, value) => write(`${label.padEnd(12)}${value}`);
|
|
144
|
+
const observing = s.enforcement === "observe";
|
|
145
|
+
row("gateway", `${s.name} (${s.config})`);
|
|
146
|
+
// The mode comes first and in capitals when it is the one that protects
|
|
147
|
+
// nothing: every line after it describes a policy, and reads as protection.
|
|
148
|
+
row("mode", observing
|
|
149
|
+
? "OBSERVE -- the policy is NOT ENFORCED. Every call runs and is only recorded."
|
|
150
|
+
: "enforce -- the policy is applied to every call");
|
|
151
|
+
row("posture", `${s.posture} (unclassified tools: ${s.onUnclassified})${observing ? " [not applied]" : ""}`);
|
|
152
|
+
row("process", s.running
|
|
153
|
+
? `running, pid ${s.pid}, started ${ago(s.startedAt, now)}`
|
|
154
|
+
: s.lastSeen !== null
|
|
155
|
+
? `not running (last seen ${ago(s.lastSeen, now)})`
|
|
156
|
+
: "not running (no gateway has started from this config yet)");
|
|
157
|
+
if (s.policyCurrent === false) {
|
|
158
|
+
row("policy", "the file on disk differs from what the running gateway loaded; it reloads within a second, or needs a restart if the change was to audit, tenant or approvals.store_path");
|
|
159
|
+
}
|
|
160
|
+
row("upstreams", s.upstreams.join(", "));
|
|
161
|
+
row("tools", s.tools
|
|
162
|
+
? `${s.tools.served} served` +
|
|
163
|
+
(s.tools.unclassified ? `, ${s.tools.unclassified} unclassified` : "") +
|
|
164
|
+
(s.tools.withheld ? `, ${s.tools.withheld} withheld` : "") +
|
|
165
|
+
`, ${s.tools.switchedOff} switched off` +
|
|
166
|
+
(s.running ? "" : " (as last published; nothing is running to confirm it)")
|
|
167
|
+
: "unknown: no gateway has published a tool list yet");
|
|
168
|
+
row("waiting", s.waiting === 0
|
|
169
|
+
? "nothing is waiting for approval"
|
|
170
|
+
: `${s.waiting} call${s.waiting === 1 ? "" : "s"} waiting for approval -- review with: hmcp pending`);
|
|
171
|
+
if (s.contractChanges.length > 0) {
|
|
172
|
+
const names = [...new Set(s.contractChanges.map((c) => c.tool))];
|
|
173
|
+
row("changed", `${names.length} tool(s) have advertised something different from what was pinned ` +
|
|
174
|
+
`(${names.slice(0, 3).join(", ")}${names.length > 3 ? ", …" : ""})` +
|
|
175
|
+
(s.contractChanges.some((c) => c.denied) ? " -- withheld until accepted" : "") +
|
|
176
|
+
`; hmcp-gateway pin list`);
|
|
177
|
+
}
|
|
178
|
+
if (s.activeGrants > 0)
|
|
179
|
+
row("grants", `${s.activeGrants} standing grant${s.activeGrants === 1 ? "" : "s"} active`);
|
|
180
|
+
row("last call", s.lastCall
|
|
181
|
+
? `${s.lastCall.ts} ${s.lastCall.tool} ` +
|
|
182
|
+
(s.lastCall.observe ? `ran (would ${s.lastCall.decision})` : `${s.lastCall.decision} / ${s.lastCall.outcome}`)
|
|
183
|
+
: "none recorded");
|
|
184
|
+
const d = s.last24h;
|
|
185
|
+
row("last 24h", d.calls === 0
|
|
186
|
+
? "no calls"
|
|
187
|
+
: observing
|
|
188
|
+
? `${d.calls} calls, all ran: ${d.allow} would run, ${d.approve} would wait for a human, ${d.deny} would be refused`
|
|
189
|
+
: `${d.calls} calls: ${d.allow} allowed, ${d.approve} held for a human, ${d.deny} refused`);
|
|
190
|
+
row("audit log", s.auditPath);
|
|
191
|
+
if (observing) {
|
|
192
|
+
write("");
|
|
193
|
+
write("See what enforcing would change: hmcp-gateway suggest");
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type Rule } from "hmcp-core";
|
|
2
|
+
export interface SuggestCommandOptions {
|
|
3
|
+
readonly config: string;
|
|
4
|
+
/** Only records at or after this ISO timestamp. */
|
|
5
|
+
readonly since?: string | undefined;
|
|
6
|
+
readonly json?: boolean | undefined;
|
|
7
|
+
readonly write?: (line: string) => void;
|
|
8
|
+
}
|
|
9
|
+
/** A proposed rule, in the shape `policy.yaml` takes. */
|
|
10
|
+
export type SuggestedRule = Pick<Rule, "id" | "match" | "decision"> & Partial<Pick<Rule, "effect" | "on_violation" | "unknown_args" | "args">>;
|
|
11
|
+
export interface ToolObservation {
|
|
12
|
+
readonly tool: string;
|
|
13
|
+
readonly calls: number;
|
|
14
|
+
readonly effect: string | null;
|
|
15
|
+
/** The rule that would have decided it, and its reason, from the newest record. */
|
|
16
|
+
readonly ruleId: string;
|
|
17
|
+
readonly reason: string;
|
|
18
|
+
}
|
|
19
|
+
export interface Suggestion {
|
|
20
|
+
readonly gateway: string;
|
|
21
|
+
readonly policyFile: string;
|
|
22
|
+
/** What the policy gives a tool nothing classified, which decides how that section reads. */
|
|
23
|
+
readonly onUnclassified: "deny" | "approve";
|
|
24
|
+
/** Whether the policy has any rules yet, which decides how to say where the suggestions go. */
|
|
25
|
+
readonly hasRules: boolean;
|
|
26
|
+
readonly calls: number;
|
|
27
|
+
readonly from: string | null;
|
|
28
|
+
readonly to: string | null;
|
|
29
|
+
readonly wouldRun: number;
|
|
30
|
+
readonly wouldAsk: number;
|
|
31
|
+
readonly wouldRefuse: number;
|
|
32
|
+
readonly unclassified: readonly ToolObservation[];
|
|
33
|
+
readonly refused: readonly ToolObservation[];
|
|
34
|
+
readonly asked: readonly (ToolObservation & {
|
|
35
|
+
readonly suggested: boolean;
|
|
36
|
+
readonly why: string;
|
|
37
|
+
})[];
|
|
38
|
+
readonly rules: readonly SuggestedRule[];
|
|
39
|
+
/** One line per suggested rule saying what it was derived from. */
|
|
40
|
+
readonly notes: Readonly<Record<string, string>>;
|
|
41
|
+
}
|
|
42
|
+
export declare function buildSuggestion(configPath: string, since?: string): Suggestion;
|
|
43
|
+
export declare function runSuggestCommand(options: SuggestCommandOptions): Promise<void>;
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
2
|
+
import { stringify as stringifyYaml } from "yaml";
|
|
3
|
+
import { classifyByName, expandPath, leafPaths, queryAuditLog } from "hmcp-core";
|
|
4
|
+
import { loadGatewayConfig } from "./config.js";
|
|
5
|
+
/**
|
|
6
|
+
* `hmcp-gateway suggest`: what enforcing would have done to the calls that
|
|
7
|
+
* were observed, and a policy that fits them.
|
|
8
|
+
*
|
|
9
|
+
* It reads only records an observing gateway marked, so the history it
|
|
10
|
+
* reasons from is one where nothing was refused and the agent behaved as it
|
|
11
|
+
* does when unobstructed. For each tool that would have waited for a human
|
|
12
|
+
* several times it proposes a rule bounded by what was seen: the ordinary
|
|
13
|
+
* case then runs unasked, and anything outside it still stops for a person.
|
|
14
|
+
*
|
|
15
|
+
* It only ever prints. A proposed permission is something a person reads and
|
|
16
|
+
* pastes; a command that wrote "allow" rules into a policy from a log would
|
|
17
|
+
* be the agent's own behaviour granting itself access.
|
|
18
|
+
*/
|
|
19
|
+
/** Seen fewer times than this, a call says too little about what is ordinary. */
|
|
20
|
+
const MIN_CALLS_TO_SUGGEST = 3;
|
|
21
|
+
/** A string argument with at most this many distinct values is treated as a choice. */
|
|
22
|
+
const MAX_ENUM_VALUES = 5;
|
|
23
|
+
const MAX_ENUM_LENGTH = 40;
|
|
24
|
+
const MAX_PAGES = 100;
|
|
25
|
+
const UNCLASSIFIED_RULE = "defaults.on_unclassified";
|
|
26
|
+
const POSTURE_RULE = "defaults.mode";
|
|
27
|
+
/** A value the log does not actually hold: redacted, or cut short. */
|
|
28
|
+
function unknownValue(value) {
|
|
29
|
+
return typeof value === "string" && (value.startsWith("[redacted") || value.includes("…[truncated"));
|
|
30
|
+
}
|
|
31
|
+
const nice = (n) => {
|
|
32
|
+
const steps = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 65536];
|
|
33
|
+
return steps.find((s) => s >= n) ?? n;
|
|
34
|
+
};
|
|
35
|
+
/** `items[3].qty` as the pattern a bound is written against: `items[].qty`. Null if a key cannot be written. */
|
|
36
|
+
function pattern(path) {
|
|
37
|
+
let out = "";
|
|
38
|
+
for (const seg of path) {
|
|
39
|
+
if (typeof seg === "number")
|
|
40
|
+
out += "[]";
|
|
41
|
+
else {
|
|
42
|
+
if (/[.[\]]/.test(seg) || seg.length === 0)
|
|
43
|
+
return null;
|
|
44
|
+
out += out.length === 0 ? seg : `.${seg}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Bounds that every observed call satisfies, as tight as the evidence
|
|
51
|
+
* supports and no tighter. Returns null when some argument cannot be named
|
|
52
|
+
* in a bound at all, in which case no rule should be proposed.
|
|
53
|
+
*/
|
|
54
|
+
function boundsFor(samples) {
|
|
55
|
+
const seen = new Map();
|
|
56
|
+
for (const [i, args] of samples.entries()) {
|
|
57
|
+
for (const leaf of leafPaths(args)) {
|
|
58
|
+
const spec = pattern(leaf.path);
|
|
59
|
+
if (spec === null)
|
|
60
|
+
return null;
|
|
61
|
+
const entry = seen.get(spec) ?? { values: [], calls: new Set() };
|
|
62
|
+
entry.values.push(leaf.value);
|
|
63
|
+
entry.calls.add(i);
|
|
64
|
+
seen.set(spec, entry);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const args = {};
|
|
68
|
+
const said = [];
|
|
69
|
+
for (const [spec, { values, calls }] of [...seen].sort(([a], [b]) => a.localeCompare(b))) {
|
|
70
|
+
// An argument some calls left out must be allowed to be left out, or the
|
|
71
|
+
// rule would refuse the very calls it was written from. A fanned-out path
|
|
72
|
+
// is already exempt from the presence check.
|
|
73
|
+
const optional = calls.size < samples.length && !spec.includes("[]") ? { optional: true } : {};
|
|
74
|
+
if (values.some(unknownValue)) {
|
|
75
|
+
args[spec] = { ...optional };
|
|
76
|
+
said.push(`${spec} is not in the log (redacted), so it is named but not bounded`);
|
|
77
|
+
}
|
|
78
|
+
else if (values.every((v) => typeof v === "number")) {
|
|
79
|
+
const max = Math.max(...values);
|
|
80
|
+
args[spec] = { max, ...optional };
|
|
81
|
+
said.push(`${spec} was at most ${max}`);
|
|
82
|
+
}
|
|
83
|
+
else if (values.every((v) => typeof v === "boolean")) {
|
|
84
|
+
const distinct = [...new Set(values)].sort();
|
|
85
|
+
args[spec] = { enum: distinct, ...optional };
|
|
86
|
+
said.push(`${spec} was ${distinct.join(" or ")}`);
|
|
87
|
+
}
|
|
88
|
+
else if (values.every((v) => typeof v === "string")) {
|
|
89
|
+
const strings = values;
|
|
90
|
+
const distinct = [...new Set(strings)].sort();
|
|
91
|
+
const repeats = distinct.length < strings.length;
|
|
92
|
+
if (repeats && distinct.length <= MAX_ENUM_VALUES && distinct.every((v) => v.length <= MAX_ENUM_LENGTH)) {
|
|
93
|
+
args[spec] = { enum: distinct, ...optional };
|
|
94
|
+
said.push(`${spec} was always one of ${distinct.length} value${distinct.length === 1 ? "" : "s"}`);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
const longest = Math.max(...strings.map((v) => v.length));
|
|
98
|
+
const maxLength = nice(Math.max(1, longest * 2));
|
|
99
|
+
args[spec] = { maxLength, ...optional };
|
|
100
|
+
said.push(`${spec} was at most ${longest} characters (allowing ${maxLength})`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
// Mixed types, nulls, empty containers: say the argument exists and
|
|
105
|
+
// leave the judgement to whoever reads the rule.
|
|
106
|
+
args[spec] = { ...optional };
|
|
107
|
+
said.push(`${spec} varied in type, so it is named but not bounded`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { args, note: said.join("; ") };
|
|
111
|
+
}
|
|
112
|
+
function observedRecords(auditPath, component, since) {
|
|
113
|
+
const out = [];
|
|
114
|
+
let cursor;
|
|
115
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
116
|
+
const result = queryAuditLog(auditPath, {
|
|
117
|
+
component: [component],
|
|
118
|
+
limit: 1000,
|
|
119
|
+
...(since ? { since } : {}),
|
|
120
|
+
...(cursor !== undefined ? { beforeSeq: cursor } : {})
|
|
121
|
+
});
|
|
122
|
+
out.push(...result.records.filter((r) => r.observe === true && r.tool !== ""));
|
|
123
|
+
if (result.nextCursor === null)
|
|
124
|
+
break;
|
|
125
|
+
cursor = result.nextCursor;
|
|
126
|
+
}
|
|
127
|
+
return out.reverse();
|
|
128
|
+
}
|
|
129
|
+
export function buildSuggestion(configPath, since) {
|
|
130
|
+
const full = expandPath(configPath);
|
|
131
|
+
const base = dirname(full);
|
|
132
|
+
const { config, policy } = loadGatewayConfig(full);
|
|
133
|
+
const records = observedRecords(expandPath(policy.audit.path, base), `gateway:${config.name}`, since);
|
|
134
|
+
const policyFile = typeof config.policy === "string" ? expandPath(config.policy, base) : `${full} (inline policy)`;
|
|
135
|
+
const byTool = new Map();
|
|
136
|
+
for (const r of records)
|
|
137
|
+
byTool.set(r.tool, [...(byTool.get(r.tool) ?? []), r]);
|
|
138
|
+
const unclassified = [];
|
|
139
|
+
const refused = [];
|
|
140
|
+
const asked = [];
|
|
141
|
+
const rules = [];
|
|
142
|
+
const notes = {};
|
|
143
|
+
const taken = new Set(policy.rules.map((r) => r.id));
|
|
144
|
+
for (const [tool, all] of [...byTool].sort(([a], [b]) => a.localeCompare(b))) {
|
|
145
|
+
for (const kind of ["deny", "approve"]) {
|
|
146
|
+
const group = all.filter((r) => r.decision === kind);
|
|
147
|
+
if (group.length === 0)
|
|
148
|
+
continue;
|
|
149
|
+
const newest = group[group.length - 1];
|
|
150
|
+
const seen = {
|
|
151
|
+
tool,
|
|
152
|
+
calls: group.length,
|
|
153
|
+
effect: newest.effect,
|
|
154
|
+
ruleId: newest.rule_id,
|
|
155
|
+
reason: newest.reason
|
|
156
|
+
};
|
|
157
|
+
if (newest.rule_id === UNCLASSIFIED_RULE) {
|
|
158
|
+
unclassified.push(seen);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (kind === "deny") {
|
|
162
|
+
refused.push(seen);
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
let why = "";
|
|
166
|
+
if (newest.rule_id !== POSTURE_RULE)
|
|
167
|
+
why = `held by rule "${newest.rule_id}", which already says what you want here`;
|
|
168
|
+
else if (newest.effect === "destructive")
|
|
169
|
+
why = "destructive, so it is left to a person every time";
|
|
170
|
+
else if (group.length < MIN_CALLS_TO_SUGGEST)
|
|
171
|
+
why = "seen too few times to say what is ordinary";
|
|
172
|
+
else if (/[*?{},]/.test(tool))
|
|
173
|
+
why = "its name contains pattern characters, so write the rule by hand";
|
|
174
|
+
const bounds = why ? null : boundsFor(group.map((r) => r.args_redacted ?? {}));
|
|
175
|
+
if (!why && bounds === null)
|
|
176
|
+
why = "an argument name cannot be written as a bound";
|
|
177
|
+
if (bounds) {
|
|
178
|
+
let id = `suggested-${tool}`;
|
|
179
|
+
while (taken.has(id))
|
|
180
|
+
id += "-2";
|
|
181
|
+
taken.add(id);
|
|
182
|
+
rules.push({
|
|
183
|
+
id,
|
|
184
|
+
match: tool,
|
|
185
|
+
...(newest.effect ? { effect: newest.effect } : {}),
|
|
186
|
+
decision: "allow",
|
|
187
|
+
on_violation: "approve",
|
|
188
|
+
unknown_args: "deny",
|
|
189
|
+
args: bounds.args
|
|
190
|
+
});
|
|
191
|
+
notes[id] = `${group.length} calls. ${bounds.note || "It was called with no arguments"}.`;
|
|
192
|
+
}
|
|
193
|
+
asked.push({ ...seen, suggested: bounds !== null, why: bounds ? "a bounded rule is suggested below" : why });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
gateway: config.name,
|
|
198
|
+
policyFile,
|
|
199
|
+
onUnclassified: policy.defaults.on_unclassified,
|
|
200
|
+
hasRules: policy.rules.length > 0,
|
|
201
|
+
calls: records.length,
|
|
202
|
+
from: records[0]?.ts ?? null,
|
|
203
|
+
to: records[records.length - 1]?.ts ?? null,
|
|
204
|
+
wouldRun: records.filter((r) => r.decision === "allow").length,
|
|
205
|
+
wouldAsk: records.filter((r) => r.decision === "approve").length,
|
|
206
|
+
wouldRefuse: records.filter((r) => r.decision === "deny").length,
|
|
207
|
+
unclassified,
|
|
208
|
+
refused,
|
|
209
|
+
asked,
|
|
210
|
+
rules,
|
|
211
|
+
notes
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
const times = (n) => `${n} time${n === 1 ? "" : "s"}`;
|
|
215
|
+
export async function runSuggestCommand(options) {
|
|
216
|
+
const write = options.write ?? ((line) => process.stdout.write(`${line}\n`));
|
|
217
|
+
const s = buildSuggestion(options.config, options.since);
|
|
218
|
+
if (options.json) {
|
|
219
|
+
write(JSON.stringify(s, null, 2));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (s.calls === 0) {
|
|
223
|
+
write(`No observed calls yet for gateway "${s.gateway}".`);
|
|
224
|
+
write("");
|
|
225
|
+
write(`A gateway records them while its policy says "enforcement: observe" (${s.policyFile}).`);
|
|
226
|
+
write("Run it that way for a while, use your agent as you normally would, then run this again.");
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
write(`Observed ${s.calls} calls through gateway "${s.gateway}", ${s.from} to ${s.to}.`);
|
|
230
|
+
write("All of them ran. Had the policy been enforced:");
|
|
231
|
+
write(` ${String(s.wouldRun).padStart(5)} would have run`);
|
|
232
|
+
write(` ${String(s.wouldAsk).padStart(5)} would have waited for a human`);
|
|
233
|
+
write(` ${String(s.wouldRefuse).padStart(5)} would have been refused`);
|
|
234
|
+
if (s.unclassified.length > 0) {
|
|
235
|
+
write("");
|
|
236
|
+
write(s.onUnclassified === "deny"
|
|
237
|
+
? "NOT CLASSIFIED -- nothing says what these do, so enforcement would refuse every call to them."
|
|
238
|
+
: "NOT CLASSIFIED -- nothing says what these do, so enforcement would ask you about every call to them.");
|
|
239
|
+
write("Say what each one is, once:");
|
|
240
|
+
for (const t of s.unclassified) {
|
|
241
|
+
const guess = classifyByName(t.tool);
|
|
242
|
+
write(` ${t.tool.padEnd(40)} called ${times(t.calls)}`);
|
|
243
|
+
write(` hmcp-gateway rule ${t.tool}${guess ? ` # its name reads as ${guess}` : ""}`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (s.refused.length > 0) {
|
|
247
|
+
write("");
|
|
248
|
+
write("REFUSED BY POLICY -- change the rule named if these should run:");
|
|
249
|
+
for (const t of s.refused) {
|
|
250
|
+
write(` ${t.tool.padEnd(40)} called ${times(t.calls)} ${t.ruleId}: ${t.reason}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (s.asked.length > 0) {
|
|
254
|
+
write("");
|
|
255
|
+
write("WOULD HAVE ASKED YOU:");
|
|
256
|
+
for (const t of s.asked)
|
|
257
|
+
write(` ${t.tool.padEnd(40)} ${times(t.calls).padEnd(10)} ${t.why}`);
|
|
258
|
+
}
|
|
259
|
+
if (s.rules.length > 0) {
|
|
260
|
+
write("");
|
|
261
|
+
write(s.hasRules
|
|
262
|
+
? `SUGGESTED RULES -- add these above the existing rules in ${s.policyFile}`
|
|
263
|
+
: `SUGGESTED RULES -- replace the "rules: []" line in ${s.policyFile} with this`);
|
|
264
|
+
write("# Each lets calls like the ones observed run without asking, and still sends");
|
|
265
|
+
write("# anything outside them to a human. They are drawn from what your agent did,");
|
|
266
|
+
write("# not from what it should do: read every bound before adopting it.");
|
|
267
|
+
write("rules:");
|
|
268
|
+
for (const rule of s.rules) {
|
|
269
|
+
write(` # ${rule.match}: ${s.notes[rule.id]}`);
|
|
270
|
+
for (const line of stringifyYaml([rule]).trimEnd().split("\n"))
|
|
271
|
+
write(` ${line}`);
|
|
272
|
+
write("");
|
|
273
|
+
}
|
|
274
|
+
write("# end of suggested rules");
|
|
275
|
+
}
|
|
276
|
+
write("");
|
|
277
|
+
write(`When the policy says what you want, set "enforcement: enforce" in ${s.policyFile}.`);
|
|
278
|
+
write("A running gateway picks that up without a restart.");
|
|
279
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex's `config.toml` (shared with the ChatGPT desktop app): reading it,
|
|
3
|
+
* and changing only the MCP server tables in it.
|
|
4
|
+
*
|
|
5
|
+
* The TOML library is used to read, never to write. Writing a whole TOML
|
|
6
|
+
* document back from its parsed value loses every comment and all of the
|
|
7
|
+
* person's layout, in a file they edit by hand. So every change here is a
|
|
8
|
+
* cut or an append on the file's own text: a server's table (and its
|
|
9
|
+
* `[mcp_servers.<name>.*]` sub-tables) removed, or a new table added at the
|
|
10
|
+
* end. After each change the result is read again and must equal the
|
|
11
|
+
* original with exactly that change, or nothing is written.
|
|
12
|
+
*
|
|
13
|
+
* A file whose servers are written in a form these cuts cannot handle safely
|
|
14
|
+
* -- an inline table, dotted keys, an array of tables, a server split across
|
|
15
|
+
* the file -- can be read and listed, but is refused for editing.
|
|
16
|
+
*/
|
|
17
|
+
export declare class TomlEditError extends Error {
|
|
18
|
+
}
|
|
19
|
+
/** The file as a plain JSON value: no null prototypes, dates as their TOML text. */
|
|
20
|
+
export declare function parseToml(text: string): Record<string, unknown>;
|
|
21
|
+
/**
|
|
22
|
+
* Why this file's servers cannot be changed by cutting and appending text, or
|
|
23
|
+
* null when they can. Names a form, never a value.
|
|
24
|
+
*/
|
|
25
|
+
export declare function tomlEditProblem(text: string): string | null;
|
|
26
|
+
/** A TOML basic string: quotes, backslashes and control characters escaped. */
|
|
27
|
+
export declare function tomlString(value: string): string;
|
|
28
|
+
/** A key, bare when TOML allows it and quoted otherwise. */
|
|
29
|
+
export declare function tomlKey(key: string): string;
|
|
30
|
+
/** `[a.b]` with its plain settings, then each table-valued setting as a `[a.b.<key>]` of its own. */
|
|
31
|
+
export declare function tomlTable(path: readonly string[], value: Record<string, unknown>, eol?: string): string;
|
|
32
|
+
/** Whether two read TOML documents say the same, a missing `mcp_servers` and an empty one being the same. */
|
|
33
|
+
export declare function sameToml(a: unknown, b: unknown): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* The file's text with its servers changed from `current` to `next`: each
|
|
36
|
+
* server that went or changed has its tables cut out, each one that is new
|
|
37
|
+
* or changed is appended at the end. Everything else is the file's own bytes.
|
|
38
|
+
*
|
|
39
|
+
* Refuses, with nothing written by the caller, when the servers are in a form
|
|
40
|
+
* this cannot cut safely or when the result does not read back as exactly
|
|
41
|
+
* the intended change.
|
|
42
|
+
*/
|
|
43
|
+
export declare function editTomlServers(text: string, next: Record<string, unknown>): string;
|