@kollguard/mcp-guard 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kollitech Corp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # @kollguard/mcp-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Put [KollGuard](https://kollguard.com)'s per-tool **allow / approve / deny** policy in front of
4
+ any [MCP](https://modelcontextprotocol.io) server. The Guard is an MCP server your client
5
+ launches instead of the real one; it forwards to the real server and applies the policy you set
6
+ on **Agent Control → MCP tool policy**:
7
+
8
+ - **Deny** — the tool is never offered (`tools/list` hides it) and a call is refused even if the
9
+ client remembers the name.
10
+ - **Approve** — the tool is offered with a `[KollGuard: needs approval]` note; each call waits
11
+ for a human on Agent Control (web or the mobile push) before it reaches the server.
12
+ - **Allow** — the call still passes KollGuard's runtime gate (risk class, autonomy tier, kill
13
+ switches), then goes through.
14
+ - A tool whose description or schema **changed since the last KollGuard scan** is treated as
15
+ unknown until the server is re-scanned — the "rug pull" protection, applied before the model
16
+ reads the altered description.
17
+
18
+ Tool **arguments and results never leave your host**. KollGuard receives the server URL, the
19
+ tool name, the argument *names*, and the decision.
20
+
21
+ ## Setup
22
+
23
+ 1. Register the MCP server in KollGuard (**Scans → Add MCP server**) and let the first scan run.
24
+ 2. Set the policy on **Agent Control → MCP tool policy**.
25
+ 3. Create or pick the agent on **Agent Watch** and copy its `kgw_` token.
26
+ 4. Point your MCP client at the Guard instead of the server:
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "github": {
32
+ "command": "npx",
33
+ "args": ["-y", "@kollguard/mcp-guard", "--upstream", "https://api.githubcopilot.com/mcp"],
34
+ "env": { "KOLLGUARD_AGENT_TOKEN": "kgw_…", "UPSTREAM_AUTHORIZATION": "Bearer ghp_…" }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ Local (stdio) servers are wrapped the same way:
41
+
42
+ ```json
43
+ {
44
+ "command": "npx",
45
+ "args": ["-y", "@kollguard/mcp-guard", "--upstream-command", "npx -y @modelcontextprotocol/server-filesystem /repo", "--server-id", "fs-repo"],
46
+ "env": { "KOLLGUARD_AGENT_TOKEN": "kgw_…" }
47
+ }
48
+ ```
49
+
50
+ `--server-id` is the identity KollGuard knows the local server by (register it with that label).
51
+ The child process inherits your environment minus `KOLLGUARD_AGENT_TOKEN`.
52
+
53
+ ## Flags and environment
54
+
55
+ | | |
56
+ |---|---|
57
+ | `--upstream <url>` | Remote server (Streamable HTTP). |
58
+ | `--upstream-command "<cmd>"` | Local server, run as a child process over stdio. |
59
+ | `--server-id <id>` | Identity used in KollGuard for a local server (default: the command line). |
60
+ | `--wait <seconds>` | How long a call waits for a human before returning a retryable error (default 45, max 900). |
61
+ | `KOLLGUARD_AGENT_TOKEN` | Required. The calling agent's `kgw_` token from Agent Watch. |
62
+ | `KOLLGUARD_API_URL` | Optional. Defaults to KollGuard's hosted API base; set it for a private deployment. |
63
+ | `UPSTREAM_AUTHORIZATION` | Optional. `Authorization` header value for a remote server. |
64
+
65
+ ## What the model sees when a human has to decide
66
+
67
+ The call returns a JSON-RPC error (code `-32011`):
68
+
69
+ > Waiting for a human in KollGuard (request 1f3a…). Ask again in a minute with the same
70
+ > arguments; the same request is replayed, not re-queued.
71
+
72
+ Retrying the same tool with the same arguments polls that request instead of filing another, so
73
+ the approver sees one request. Approvals are valid for 15 minutes.
74
+
75
+ ## Fail closed
76
+
77
+ | Situation | Guard behaviour |
78
+ |---|---|
79
+ | KollGuard unreachable at start | No tools are listed; every call is denied; the policy is retried on the next request. |
80
+ | KollGuard unreachable later | The cached policy still shapes `tools/list`; every call is denied until KollGuard answers again. |
81
+ | Server not registered in KollGuard | Every tool is offered as needs-approval and every call goes to a human. |
82
+ | Agent killed, disabled or out of pilot/production | Denied by the gate, with the reason. |
83
+
84
+ There is no fail-open flag.
85
+
86
+ ## Errors
87
+
88
+ | Code | Meaning |
89
+ |---|---|
90
+ | `-32010` | Denied (policy, gate, or KollGuard unreachable). |
91
+ | `-32011` | Waiting for a human; retry with the same arguments. |
92
+ | `-32012` | Guard-side error (for example the server has no resources). |
93
+
94
+ ## Scope
95
+
96
+ Tools are governed. Resources and prompts pass through unchanged. Streaming tool results are
97
+ forwarded as the upstream returns them.
98
+
99
+ MIT — Kollitech.
package/guard.mjs ADDED
@@ -0,0 +1,201 @@
1
+ // kollguard-mcp-guard core: an MCP server (towards the client) that forwards to
2
+ // an upstream MCP server (remote or local) and applies the KollGuard per-tool
3
+ // policy to tools/list and tools/call. See docs/plans/mcp-guard.md.
4
+ //
5
+ // Everything that talks to the network is injectable (upstream client,
6
+ // KollGuard fetch, clock) so the test suite runs with no network.
7
+ //
8
+ // FAIL CLOSED: any KollGuard error on the call path denies the call. A missing
9
+ // policy at startup lists no tools. There is no fail-open switch.
10
+
11
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
12
+ import {
13
+ CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema,
14
+ ListPromptsRequestSchema, GetPromptRequestSchema, McpError,
15
+ } from '@modelcontextprotocol/sdk/types.js';
16
+ import { actionClassFor, callHash, callSummary, filterTools } from './policy.mjs';
17
+
18
+ export const VERSION = '0.1.0';
19
+ export const ERR_DENIED = -32010;
20
+ export const ERR_PENDING = -32011;
21
+ export const ERR_GUARD = -32012;
22
+
23
+ const DEFAULTS = { waitMs: 45_000, pollMs: 5_000, policyRefreshMs: 60_000, log: (m) => process.stderr.write(`kollguard-mcp-guard: ${m}\n`) };
24
+
25
+ /** Minimal KollGuard API client over fetch (x-agent-token). */
26
+ export function kollguardClient({ apiUrl, token, fetchImpl = fetch }) {
27
+ const base = apiUrl.replace(/\/$/, '');
28
+ const h = { 'x-agent-token': token, accept: 'application/json' };
29
+ async function call(method, path, body) {
30
+ const r = await fetchImpl(base + path, { method, headers: body ? { ...h, 'content-type': 'application/json' } : h, body: body ? JSON.stringify(body) : undefined });
31
+ let json;
32
+ try { json = await r.json(); } catch { json = null; }
33
+ return { status: r.status, json };
34
+ }
35
+ return {
36
+ policy: (server) => call('GET', `/api/agent-watch/authorize/mcp-policy?server=${encodeURIComponent(server)}`),
37
+ authorize: (body) => call('POST', '/api/agent-watch/authorize', body),
38
+ poll: (requestId) => call('GET', `/api/agent-watch/authorize/${encodeURIComponent(requestId)}`),
39
+ };
40
+ }
41
+
42
+ /**
43
+ * createGuard({ upstream, serverUrl, kollguard, ...opts })
44
+ * upstream: a connected @modelcontextprotocol/sdk Client (listTools/callTool/…)
45
+ * serverUrl: the upstream's identity as registered in KollGuard (URL, or a
46
+ * label for local stdio servers)
47
+ * kollguard: kollguardClient(...)
48
+ * Returns { server, start(), refreshPolicy(), state } — `server` is the SDK Server
49
+ * to connect to a transport (stdio in the CLI, in-memory in tests).
50
+ */
51
+ export function createGuard({ upstream, serverUrl, kollguard, waitMs, pollMs, policyRefreshMs, log, now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
52
+ const o = { ...DEFAULTS, waitMs: waitMs ?? DEFAULTS.waitMs, pollMs: pollMs ?? DEFAULTS.pollMs, policyRefreshMs: policyRefreshMs ?? DEFAULTS.policyRefreshMs };
53
+ const logf = log ?? DEFAULTS.log;
54
+ const state = {
55
+ policy: null, // last GET mcp-policy body, or null when never loaded
56
+ policyAt: 0,
57
+ policyError: null,
58
+ tools: [], // upstream tools (raw)
59
+ catalogHash: null,
60
+ pending: new Map(), // callHash -> { requestId, idempotencyKey, at }
61
+ sessionId: now().toString(36),
62
+ };
63
+
64
+ async function refreshPolicy() {
65
+ try {
66
+ const { status, json } = await kollguard.policy(serverUrl);
67
+ if (status !== 200 || !json || typeof json !== 'object') {
68
+ state.policyError = `policy read failed (${status})`;
69
+ logf(`${state.policyError}; ${state.policy ? 'keeping the cached policy for tools/list, denying calls' : 'no tools will be listed'}`);
70
+ return false;
71
+ }
72
+ state.policy = json; state.policyAt = now(); state.policyError = null;
73
+ return true;
74
+ } catch (e) {
75
+ state.policyError = `policy read failed: ${e instanceof Error ? e.message : String(e)}`;
76
+ logf(state.policyError);
77
+ return false;
78
+ }
79
+ }
80
+
81
+ async function loadTools() {
82
+ const tools = [];
83
+ let cursor;
84
+ do {
85
+ const r = await upstream.listTools(cursor ? { cursor } : undefined);
86
+ tools.push(...(r.tools ?? []));
87
+ cursor = r.nextCursor;
88
+ } while (cursor && tools.length < 500);
89
+ state.tools = tools;
90
+ return tools;
91
+ }
92
+
93
+ function visibleTools() {
94
+ if (!state.policy) return { visible: [], hidden: [], catalogHash: null };
95
+ const f = filterTools(state.policy, state.tools);
96
+ state.catalogHash = f.catalogHash;
97
+ return f;
98
+ }
99
+
100
+ const server = new Server({ name: 'kollguard-mcp-guard', version: VERSION }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
101
+
102
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
103
+ if (!state.policy || now() - state.policyAt > o.policyRefreshMs) await refreshPolicy();
104
+ await loadTools().catch((e) => logf(`upstream tools/list failed: ${e instanceof Error ? e.message : String(e)}`));
105
+ const f = visibleTools();
106
+ if (!state.policy) logf('no policy loaded — listing no tools (fail closed)');
107
+ else if (f.hidden.length) logf(`${f.hidden.length} tool(s) hidden by policy: ${f.hidden.map((h) => h.name).join(', ')}`);
108
+ return { tools: f.visible.map((v) => v.tool) };
109
+ });
110
+
111
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
112
+ const name = req.params.name;
113
+ const args = req.params.arguments ?? {};
114
+ if (!state.policy || now() - state.policyAt > o.policyRefreshMs) await refreshPolicy();
115
+ if (!state.policy) throw new McpError(ERR_DENIED, 'Denied: KollGuard policy is not available (fail closed).');
116
+ if (!state.tools.length) await loadTools().catch(() => undefined);
117
+ const f = visibleTools();
118
+ const entry = f.visible.find((v) => v.tool.name === name);
119
+ if (!entry) {
120
+ const why = f.hidden.find((h) => h.name === name) ? 'denied by KollGuard policy' : 'not offered by this server';
121
+ throw new McpError(ERR_DENIED, `Tool "${name}" is ${why}.`);
122
+ }
123
+ const raw = state.tools.find((t) => t.name === name);
124
+ const hash = callHash(serverUrl, name, args);
125
+
126
+ // Retry of a call that is already waiting on a human: poll that request.
127
+ const prior = state.pending.get(hash);
128
+ let decision = null, requestId = null, reason = '';
129
+ if (prior) {
130
+ const p = await safe(() => kollguard.poll(prior.requestId));
131
+ if (p && p.status === 200 && p.json) { decision = p.json.decision; requestId = prior.requestId; reason = p.json.reason ?? ''; }
132
+ if (decision !== 'pending') state.pending.delete(hash);
133
+ if (decision === 'allow') return forward();
134
+ if (decision === 'deny' || !decision) throw new McpError(ERR_DENIED, `Denied by KollGuard: ${reason || 'request expired or could not be read'}`);
135
+ } else {
136
+ const body = {
137
+ action: 'mcp:tools/call',
138
+ actionClass: actionClassFor(raw ?? { name }, ruleClass(name)),
139
+ mcpServer: serverUrl,
140
+ tool: name,
141
+ summary: callSummary(name, args),
142
+ idempotencyKey: `g-${hash}-${state.sessionId}`,
143
+ };
144
+ const a = await safe(() => kollguard.authorize(body));
145
+ if (!a || !a.json) throw new McpError(ERR_DENIED, 'Denied: KollGuard could not be reached (fail closed).');
146
+ decision = a.json.decision; requestId = a.json.requestId ?? null; reason = a.json.reason ?? '';
147
+ if (decision === 'allow') return forward();
148
+ if (decision !== 'pending' || !requestId) throw new McpError(ERR_DENIED, `Denied by KollGuard: ${reason || `status ${a.status}`}`);
149
+ state.pending.set(hash, { requestId, at: now() });
150
+ }
151
+
152
+ // Pending: wait up to waitMs, polling.
153
+ const deadline = now() + o.waitMs;
154
+ while (now() < deadline) {
155
+ await sleep(o.pollMs);
156
+ const p = await safe(() => kollguard.poll(requestId));
157
+ if (!p || p.status !== 200 || !p.json) continue; // transient; keep waiting until the deadline
158
+ if (p.json.decision === 'allow') { state.pending.delete(hash); return forward(); }
159
+ if (p.json.decision === 'deny') { state.pending.delete(hash); throw new McpError(ERR_DENIED, `Denied by KollGuard: ${p.json.reason ?? ''}`); }
160
+ }
161
+ throw new McpError(ERR_PENDING, `Waiting for a human in KollGuard (request ${requestId.slice(0, 8)}…). Ask again in a minute with the same arguments; the same request is replayed, not re-queued.`);
162
+
163
+ async function forward() {
164
+ return upstream.callTool({ name, arguments: args });
165
+ }
166
+ });
167
+
168
+ // resources/* and prompts/* pass through unchanged when the upstream offers them.
169
+ const caps = () => upstream.getServerCapabilities?.() ?? {};
170
+ server.setRequestHandler(ListResourcesRequestSchema, async (req) => (caps().resources ? upstream.listResources(req.params) : { resources: [] }));
171
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
172
+ if (!caps().resources) throw new McpError(ERR_GUARD, 'Upstream server has no resources.');
173
+ return upstream.readResource(req.params);
174
+ });
175
+ server.setRequestHandler(ListPromptsRequestSchema, async (req) => (caps().prompts ? upstream.listPrompts(req.params) : { prompts: [] }));
176
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
177
+ if (!caps().prompts) throw new McpError(ERR_GUARD, 'Upstream server has no prompts.');
178
+ return upstream.getPrompt(req.params);
179
+ });
180
+
181
+ function ruleClass(name) {
182
+ const r = state.policy?.policy?.tools?.[name];
183
+ return r && typeof r === 'object' ? r.class ?? null : null;
184
+ }
185
+
186
+ async function start() {
187
+ const ok = await refreshPolicy();
188
+ await loadTools().catch((e) => logf(`upstream tools/list failed: ${e instanceof Error ? e.message : String(e)}`));
189
+ const f = visibleTools();
190
+ if (ok && !state.policy.registered) logf(`"${serverUrl}" is not a registered MCP server in KollGuard — every tool needs a human until it is added and scanned`);
191
+ else if (ok && !state.policy.policy) logf(`no per-tool policy on "${serverUrl}" yet — the risk-class policy decides each call`);
192
+ logf(`ready: ${f.visible.length} tool(s) offered, ${f.hidden.length} hidden${state.catalogHash && state.policy?.baseline?.catalogHash && state.catalogHash !== state.policy.baseline.catalogHash ? ' — upstream tool manifest differs from the last KollGuard scan (changed tools are treated as unknown)' : ''}`);
193
+ return f;
194
+ }
195
+
196
+ return { server, start, refreshPolicy, state };
197
+ }
198
+
199
+ async function safe(fn) {
200
+ try { return await fn(); } catch { return null; }
201
+ }
package/index.mjs ADDED
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ // kollguard-mcp-guard — put KollGuard's per-tool policy in front of any MCP server.
3
+ //
4
+ // npx -y @kollguard/mcp-guard --upstream https://mcp.example.com/mcp
5
+ // npx -y @kollguard/mcp-guard --upstream-command "npx -y @modelcontextprotocol/server-filesystem /repo" --server-id fs-repo
6
+ //
7
+ // Env:
8
+ // KOLLGUARD_AGENT_TOKEN required — the calling agent's kgw_ token (Agent Watch)
9
+ // KOLLGUARD_API_URL optional — defaults to KollGuard's API base (the edge-function URL)
10
+ // UPSTREAM_AUTHORIZATION optional — Authorization header VALUE for a remote upstream (e.g. "Bearer …")
11
+ //
12
+ // Flags:
13
+ // --upstream <url> remote upstream (Streamable HTTP)
14
+ // --upstream-command "<cmd>" local upstream (stdio), run as a child process
15
+ // --server-id <id> identity used in KollGuard for a local upstream (default: the command)
16
+ // --wait <seconds> how long to wait for a human before returning a retryable error (default 45)
17
+ //
18
+ // stdout is the MCP channel; every log line goes to stderr.
19
+
20
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
21
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
22
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
23
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
24
+ import { createGuard, kollguardClient, VERSION } from './guard.mjs';
25
+
26
+ function parseArgs(argv) {
27
+ const out = { wait: 45 };
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const a = argv[i];
30
+ const next = () => { const v = argv[++i]; if (v === undefined) fail(`${a} needs a value`); return v; };
31
+ if (a === '--upstream') out.upstream = next();
32
+ else if (a === '--upstream-command') out.upstreamCommand = next();
33
+ else if (a === '--server-id') out.serverId = next();
34
+ else if (a === '--wait') out.wait = Number(next());
35
+ else if (a === '--version' || a === '-v') { process.stdout.write(`${VERSION}\n`); process.exit(0); }
36
+ else if (a === '--help' || a === '-h') { process.stdout.write(HELP); process.exit(0); }
37
+ else fail(`unknown flag ${a}`);
38
+ }
39
+ if (!out.upstream && !out.upstreamCommand) fail('--upstream <url> or --upstream-command "<cmd>" is required');
40
+ if (out.upstream && out.upstreamCommand) fail('use either --upstream or --upstream-command');
41
+ if (!Number.isFinite(out.wait) || out.wait < 0 || out.wait > 900) fail('--wait must be 0–900 seconds');
42
+ return out;
43
+ }
44
+
45
+ const HELP = `kollguard-mcp-guard ${VERSION}
46
+ Usage: kollguard-mcp-guard --upstream <url> | --upstream-command "<cmd>" [--server-id <id>] [--wait <seconds>]
47
+ Env: KOLLGUARD_AGENT_TOKEN (required), KOLLGUARD_API_URL (private deployments), UPSTREAM_AUTHORIZATION
48
+ `;
49
+
50
+ function fail(msg) {
51
+ process.stderr.write(`kollguard-mcp-guard: ${msg}\n${HELP}`);
52
+ process.exit(2);
53
+ }
54
+
55
+ function splitCommand(s) {
56
+ // Minimal shell-ish split: quotes group, backslash escapes inside quotes are not supported.
57
+ const out = [];
58
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
59
+ let m;
60
+ while ((m = re.exec(s))) out.push(m[1] ?? m[2] ?? m[3]);
61
+ return out;
62
+ }
63
+
64
+ async function main() {
65
+ const args = parseArgs(process.argv.slice(2));
66
+ const token = process.env.KOLLGUARD_AGENT_TOKEN;
67
+ if (!token || !token.startsWith('kgw_')) fail('KOLLGUARD_AGENT_TOKEN (a kgw_ agent token from Agent Watch) is required');
68
+ const apiUrl = process.env.KOLLGUARD_API_URL || 'https://slqciomtynfaxdxbgkqp.supabase.co/functions/v1';
69
+
70
+ let transport, serverUrl;
71
+ if (args.upstream) {
72
+ let url;
73
+ try { url = new URL(args.upstream); } catch { fail('--upstream must be a URL'); }
74
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') fail('--upstream must be http(s)');
75
+ const auth = process.env.UPSTREAM_AUTHORIZATION;
76
+ transport = new StreamableHTTPClientTransport(url, auth ? { requestInit: { headers: { authorization: auth } } } : undefined);
77
+ serverUrl = args.upstream;
78
+ } else {
79
+ const [command, ...cmdArgs] = splitCommand(args.upstreamCommand);
80
+ if (!command) fail('--upstream-command is empty');
81
+ // The child inherits the environment minus the KollGuard token: the upstream never sees it.
82
+ const env = { ...process.env };
83
+ delete env.KOLLGUARD_AGENT_TOKEN;
84
+ transport = new StdioClientTransport({ command, args: cmdArgs, env, stderr: 'inherit' });
85
+ serverUrl = args.serverId || `stdio:${command}${cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''}`;
86
+ }
87
+
88
+ const upstream = new Client({ name: 'kollguard-mcp-guard', version: VERSION });
89
+ await upstream.connect(transport);
90
+
91
+ const guard = createGuard({ upstream, serverUrl, kollguard: kollguardClient({ apiUrl, token }), waitMs: args.wait * 1000 });
92
+ await guard.start();
93
+ await guard.server.connect(new StdioServerTransport());
94
+
95
+ const stop = async () => { try { await upstream.close(); } catch { /* ignore */ } process.exit(0); };
96
+ process.on('SIGINT', stop);
97
+ process.on('SIGTERM', stop);
98
+ }
99
+
100
+ main().catch((e) => {
101
+ process.stderr.write(`kollguard-mcp-guard: ${e instanceof Error ? e.message : String(e)}\n`);
102
+ process.exit(1);
103
+ });
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@kollguard/mcp-guard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Put KollGuard's per-tool allow / approve / deny policy in front of any MCP server. Denied tools are never offered; approvals go to a human in KollGuard Agent Control.",
5
+ "type": "module",
6
+ "bin": {
7
+ "kollguard-mcp-guard": "index.mjs"
8
+ },
9
+ "files": [
10
+ "index.mjs",
11
+ "guard.mjs",
12
+ "policy.mjs",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test \"test/**/*.test.mjs\""
18
+ },
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "dependencies": {
23
+ "@modelcontextprotocol/sdk": "^1.30.0"
24
+ },
25
+ "overrides": {
26
+ "hono": ">=4.13.18",
27
+ "@hono/node-server": "^2.1.8"
28
+ },
29
+ "keywords": [
30
+ "mcp",
31
+ "model-context-protocol",
32
+ "kollguard",
33
+ "agent-governance",
34
+ "tool-policy",
35
+ "guardrails",
36
+ "security"
37
+ ],
38
+ "homepage": "https://kollguard.com/help/agent-control",
39
+ "author": "Kollitech",
40
+ "license": "MIT",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ }
44
+ }
package/policy.mjs ADDED
@@ -0,0 +1,111 @@
1
+ // Pure policy + catalog logic for kollguard-mcp-guard. No I/O.
2
+ //
3
+ // The hashes here MUST match supabase/functions/api/mcp/rules.ts (canonicalJson,
4
+ // catalogOf, catalogHash) so the Guard and the scanner agree on "changed".
5
+
6
+ import { createHash } from 'node:crypto';
7
+
8
+ export const DESC_CAP = 300;
9
+
10
+ export function sha256Hex(s) {
11
+ return createHash('sha256').update(s, 'utf8').digest('hex');
12
+ }
13
+
14
+ /** JSON.stringify with object keys sorted, so key order never changes a hash. */
15
+ export function canonicalJson(v) {
16
+ if (v === undefined) return 'null';
17
+ if (v === null || typeof v !== 'object') return JSON.stringify(v);
18
+ if (Array.isArray(v)) return `[${v.map(canonicalJson).join(',')}]`;
19
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k])}`).join(',')}}`;
20
+ }
21
+
22
+ /** Sorted catalog (by name; a duplicate name keeps its first occurrence). */
23
+ export function catalogOf(tools) {
24
+ const seen = new Set();
25
+ const out = [];
26
+ for (const t of tools) {
27
+ if (seen.has(t.name)) continue;
28
+ seen.add(t.name);
29
+ const description = t.description ?? '';
30
+ out.push({
31
+ name: t.name,
32
+ descriptionHash: sha256Hex(description),
33
+ schemaHash: sha256Hex(canonicalJson(t.inputSchema ?? null)),
34
+ });
35
+ }
36
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
37
+ }
38
+
39
+ export function catalogHash(catalog) {
40
+ return sha256Hex(catalog.map((c) => `${c.name}|${c.descriptionHash}|${c.schemaHash}`).join('\n'));
41
+ }
42
+
43
+ /**
44
+ * Effective mode for one tool.
45
+ * policyView: the GET mcp-policy response ({ registered, policy, baseline }).
46
+ * entry: this tool's current catalog entry (name + hashes), or null if
47
+ * the tool is not in the upstream's current list.
48
+ * Returns { mode, source, drifted } where source ∈ rule | default | unknown | unregistered | nopolicy.
49
+ */
50
+ export function effectiveMode(policyView, entry) {
51
+ if (!policyView || !policyView.registered) return { mode: 'approve', source: 'unregistered', drifted: false };
52
+ const policy = policyView.policy;
53
+ if (!policy) return { mode: 'allow', source: 'nopolicy', drifted: false };
54
+ const name = entry.name;
55
+ const base = policyView.baseline?.tools?.find((t) => t.name === name) ?? null;
56
+ const drifted = !!base && (base.descriptionHash !== entry.descriptionHash || base.schemaHash !== entry.schemaHash);
57
+ const inCatalog = !!base && !drifted;
58
+ const rule = Object.prototype.hasOwnProperty.call(policy.tools, name) ? policy.tools[name] : undefined;
59
+ // Rules are strings today; { mode, class } is the forward-compatible form (G2).
60
+ const explicit = rule && typeof rule === 'object' ? rule.mode : rule;
61
+ // A changed tool is "unknown" until the next scan re-baselines it — except that
62
+ // an explicit deny always denies.
63
+ if (explicit === 'deny') return { mode: 'deny', source: 'rule', drifted };
64
+ if (!inCatalog) return { mode: policy.unknownTools, source: 'unknown', drifted };
65
+ if (explicit) return { mode: explicit, source: 'rule', drifted: false };
66
+ return { mode: policy.defaultMode, source: 'default', drifted: false };
67
+ }
68
+
69
+ const RECIPIENT_PROPS = new Set(['to', 'recipient', 'recipients', 'email', 'phone', 'address', 'cc', 'bcc']);
70
+
71
+ /** Action class for the authorize gate (see docs/plans/mcp-guard.md §2.4). */
72
+ export function actionClassFor(tool, ruleClass) {
73
+ if (ruleClass) return ruleClass;
74
+ const a = tool.annotations ?? {};
75
+ const props = tool.inputSchema && typeof tool.inputSchema === 'object' && tool.inputSchema.properties && typeof tool.inputSchema.properties === 'object'
76
+ ? Object.keys(tool.inputSchema.properties) : [];
77
+ if (a.readOnlyHint === true) return 'read';
78
+ if (a.openWorldHint === true && props.some((p) => RECIPIENT_PROPS.has(p.toLowerCase()))) return 'external_comm';
79
+ return 'write';
80
+ }
81
+
82
+ /** Stable identity for one call: server + tool + canonical arguments. Never transmitted raw. */
83
+ export function callHash(server, tool, args) {
84
+ return sha256Hex(`${server}|${tool}|${canonicalJson(args ?? {})}`).slice(0, 32);
85
+ }
86
+
87
+ /** What the approver sees: tool name and argument NAMES only. */
88
+ export function callSummary(tool, args) {
89
+ const keys = args && typeof args === 'object' ? Object.keys(args) : [];
90
+ return keys.length ? `${tool} (${keys.length} arg${keys.length === 1 ? '' : 's'}: ${keys.slice(0, 12).join(', ')}${keys.length > 12 ? ', …' : ''})` : `${tool} (no args)`;
91
+ }
92
+
93
+ export const APPROVE_PREFIX = '[KollGuard: needs approval] ';
94
+
95
+ /** The tools/list the client is allowed to see, with modes attached. */
96
+ export function filterTools(policyView, tools) {
97
+ const catalog = catalogOf(tools);
98
+ const byName = new Map(catalog.map((c) => [c.name, c]));
99
+ const visible = [];
100
+ const hidden = [];
101
+ for (const t of tools) {
102
+ const entry = byName.get(t.name);
103
+ if (!entry) continue;
104
+ const r = effectiveMode(policyView, entry);
105
+ if (r.mode === 'deny') { hidden.push({ name: t.name, ...r }); continue; }
106
+ const out = { ...t };
107
+ if (r.mode === 'approve') out.description = APPROVE_PREFIX + (t.description ?? '');
108
+ visible.push({ tool: out, ...r });
109
+ }
110
+ return { visible, hidden, catalogHash: catalogHash(catalog) };
111
+ }