lugh-lang 0.7.1 → 0.7.3

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/README.md CHANGED
@@ -15,6 +15,8 @@ npx lugh-lang run program.lugh --decline # answer every approval with no
15
15
  npx lugh-lang test program.lugh # run test blocks
16
16
  npx lugh-lang check program.lugh # compile only
17
17
  npx lugh-lang sandbox # what the simulated world contains
18
+ npx lugh-lang guard --policy <file|pack> -- <mcp server command> # guard a real MCP server
19
+ npx lugh-lang protect [--yes] [--undo] # guard every MCP server in your client configs
18
20
  ```
19
21
 
20
22
  Commands exit with status 1 when a goal, test or compile step fails.
@@ -34,6 +36,23 @@ person the policy log before anything runs for real.
34
36
  }
35
37
  ```
36
38
 
39
+ ## Guard mode: a policy in front of any MCP server
40
+
41
+ Keep the MCP servers you already use and put Lugh's policy gate in front of them:
42
+
43
+ ```bash
44
+ npx -y lugh-lang guard --policy filesystem -- npx -y @modelcontextprotocol/server-filesystem ~/projects
45
+ ```
46
+
47
+ Each tool call gets an effect (from the server's annotations or your policy),
48
+ then passes the gate: budgets, deny, allow, otherwise your client asks you.
49
+ Refused calls never reach the server, and every decision goes to an audit log.
50
+ Bundled policies: `default`, `filesystem`, `github`, `supabase`, `stripe`.
51
+ `npx lugh-lang protect` does this for every server in your Claude Code, Claude
52
+ Desktop, Cursor, VS Code and Windsurf configs at once (it asks first; `--undo`
53
+ reverts). Details:
54
+ [docs/GUARD.md](https://github.com/Ashutosh3142857/lugh-lang/blob/main/docs/GUARD.md).
55
+
37
56
  ## Running for real
38
57
 
39
58
  To act on real files, APIs and MCP servers, install Lugh Core (Rust) from the
package/bin/lugh-lang.mjs CHANGED
@@ -10,6 +10,10 @@ const HELP = `lugh-lang: Lugh, the programming language for AI agents
10
10
  npx lugh-lang check <file|-> compile only
11
11
  npx lugh-lang sandbox what the simulated world contains
12
12
  npx lugh-lang mcp MCP server (stdio) for AI agents
13
+ npx lugh-lang guard --policy <file.lugh> -- <mcp server command>
14
+ put a Lugh policy in front of any MCP server
15
+ npx lugh-lang protect [--yes] [--undo] guard every MCP server in your Claude, Cursor,
16
+ VS Code and Windsurf configs (asks first)
13
17
 
14
18
  The sandbox simulates files, an HTTP API and MCP servers, and every call
15
19
  passes the real policy gate. To act on real systems, install Lugh Core:
@@ -21,6 +25,13 @@ if (cmd === "--version" || cmd === "-v") {
21
25
  console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
22
26
  process.exit(0);
23
27
  }
28
+ if (cmd === "guard") {
29
+ const { main } = await import("../lib/guard.mjs");
30
+ main(process.argv.slice(3));
31
+ } else if (cmd === "protect") {
32
+ const { main } = await import("../lib/protect.mjs");
33
+ await main(process.argv.slice(3));
34
+ } else {
24
35
  const run = await load();
25
36
  if (cmd === "mcp") {
26
37
  const { serve } = await import("../lib/mcp.mjs");
@@ -37,3 +48,4 @@ if (cmd === "mcp") {
37
48
  console.error(`unknown command '${cmd}'\n\n${HELP}`);
38
49
  process.exit(2);
39
50
  }
51
+ }
package/lib/guard.mjs ADDED
@@ -0,0 +1,314 @@
1
+ // lugh-lang guard: put a Lugh policy in front of any MCP server.
2
+ //
3
+ // npx lugh-lang guard --policy github.lugh -- npx -y @modelcontextprotocol/server-github
4
+ //
5
+ // The guard is a stdio MCP proxy. It starts the real server as a child process
6
+ // and relays every message, except that each tools/call first passes the same
7
+ // policy gate Lugh programs use:
8
+ //
9
+ // time budget → call budget → deny → allow → otherwise ask a human
10
+ //
11
+ // A tool's effect comes from its MCP annotations (readOnlyHint → read,
12
+ // destructiveHint → delete, otherwise submit), unless the policy file's `tools`
13
+ // block names it. "Ask" uses the client's approval prompt (MCP elicitation)
14
+ // when the client supports it; otherwise the call is held back and the agent is
15
+ // told why. Every decision is appended to a JSONL audit log.
16
+
17
+ import { spawn } from "node:child_process";
18
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
19
+ import { fileURLToPath } from "node:url";
20
+ import { dirname, join } from "node:path";
21
+ import { homedir } from "node:os";
22
+
23
+ export const EFFECTS = ["read", "write", "send", "submit", "spend", "delete", "execute"];
24
+
25
+ // ───────── policy file ─────────
26
+ // A Lugh header (agent, budget, policy) plus an optional guard-only `tools`
27
+ // block that sets a tool's effect by name (`*` matches anything):
28
+ //
29
+ // agent GitHubGuard
30
+ // budget calls 200, time 2h
31
+ // policy
32
+ // allow read
33
+ // ask human before submit, write
34
+ // deny delete
35
+ // tools
36
+ // "delete_*" is delete
37
+ // "search_*" is read
38
+ export function parsePolicy(src) {
39
+ const p = { agent: "guard", allow: new Set(), deny: new Set(), ask: new Set(), calls: Infinity, time: Infinity, tools: [] };
40
+ let section = null;
41
+ src.split(/\r?\n/).forEach((raw, i) => {
42
+ const no = i + 1;
43
+ const line = raw.replace(/\s+#.*$/, "").replace(/^\s*#.*$/, "");
44
+ if (!line.trim()) return;
45
+ const indent = line.length - line.trimStart().length;
46
+ const t = line.trim();
47
+ const fail = (m) => { throw new Error(`policy line ${no}: ${m}`); };
48
+ if (indent === 0) {
49
+ const m = t.match(/^(agent|guard)\s+(\S+)$/);
50
+ if (!m) fail("expected `agent <Name>` at the top");
51
+ p.agent = m[2];
52
+ section = null;
53
+ return;
54
+ }
55
+ if (indent === 2) {
56
+ const [head, ...restWords] = t.split(/\s+/);
57
+ const rest = restWords.join(" ");
58
+ section = null;
59
+ if (head === "budget") {
60
+ for (const part of rest.split(",").map((s) => s.trim()).filter(Boolean)) {
61
+ const [key, val] = part.split(/\s+/);
62
+ if (key === "calls") {
63
+ if (!/^\d+$/.test(val || "")) fail("bad call budget");
64
+ p.calls = Number(val);
65
+ } else if (key === "time") {
66
+ const m = (val || "").match(/^(\d+(?:\.\d+)?)([smh]?)$/);
67
+ if (!m) fail("bad time budget, e.g. 30s, 10m, 2h");
68
+ p.time = Number(m[1]) * ({ m: 60, h: 3600 }[m[2]] || 1);
69
+ } // spend / tokens: accepted, not metered (as in Lugh Core)
70
+ }
71
+ } else if (head === "policy" || head === "tools") {
72
+ section = head;
73
+ } else if (head === "use" || head === "goal" || head === "test") {
74
+ section = "skip"; // a full program can double as a guard file
75
+ } else {
76
+ fail(`expected budget / policy / tools, got '${head}'`);
77
+ }
78
+ return;
79
+ }
80
+ if (section === "skip") return;
81
+ if (section === "policy") {
82
+ let bucket, list;
83
+ if (t.startsWith("allow ")) [bucket, list] = [p.allow, t.slice(6)];
84
+ else if (t.startsWith("deny ")) [bucket, list] = [p.deny, t.slice(5)];
85
+ else if (t.startsWith("ask human before ")) [bucket, list] = [p.ask, t.slice(17)];
86
+ else fail("policy rules are allow / deny / ask human before");
87
+ for (const e of list.split(",").map((s) => s.trim())) {
88
+ if (!EFFECTS.includes(e)) fail(`unknown effect '${e}' (effects: ${EFFECTS.join(", ")})`);
89
+ bucket.add(e);
90
+ }
91
+ return;
92
+ }
93
+ if (section === "tools") {
94
+ const m = t.match(/^"([^"]+)"(?:\s+when\s+([\w.]+)\s+matches\s+"((?:[^"\\]|\\.)*)")?\s+is\s+(\w+)$/);
95
+ if (!m) fail('tool rules look like: "delete_*" is delete, or "execute_sql" when query matches "drop|truncate" is delete');
96
+ const [, pattern, arg, argPattern, effect] = m;
97
+ if (!EFFECTS.includes(effect)) fail(`unknown effect '${effect}'`);
98
+ const re = new RegExp("^" + pattern.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
99
+ let when = null;
100
+ if (arg) {
101
+ try { when = { arg, re: new RegExp(argPattern.replace(/\\"/g, '"'), "i") }; } catch (e) { fail(`bad pattern: ${e.message}`); }
102
+ }
103
+ p.tools.push({ pattern, re, when, effect });
104
+ return;
105
+ }
106
+ fail("unexpected indentation");
107
+ });
108
+ return p;
109
+ }
110
+
111
+ // The effect of one call: the first matching `tools` rule wins, then MCP annotations.
112
+ // A rule with `when <arg> matches "<regex>"` applies only when that argument
113
+ // (a dotted path; objects are matched as JSON) matches, case-insensitively.
114
+ export function effectOf(policy, name, tool, args = {}) {
115
+ const rule = policy.tools.find((r) => r.re.test(name) && (!r.when || argMatches(args, r.when)));
116
+ if (rule) return rule.effect;
117
+ const a = (tool && tool.annotations) || {};
118
+ if (a.readOnlyHint === true) return "read";
119
+ if (a.destructiveHint === true) return "delete";
120
+ return "submit";
121
+ }
122
+
123
+ // What the gate decides before asking anyone: allow, deny or ask (with a reason).
124
+ export function decide(policy, state, effect) {
125
+ if ((Date.now() - state.started) / 1000 > policy.time) return { verdict: "budget", reason: `time budget of ${fmtTime(policy.time)} used up` };
126
+ if (state.calls + 1 > policy.calls) return { verdict: "budget", reason: `call budget of ${policy.calls} used up` };
127
+ if (policy.deny.has(effect)) return { verdict: "deny", reason: `policy denies '${effect}'` };
128
+ if (policy.allow.has(effect)) return { verdict: "allow" };
129
+ return { verdict: "ask" };
130
+ }
131
+
132
+ function argMatches(args, when) {
133
+ let v = args;
134
+ for (const k of when.arg.split(".")) v = v == null ? undefined : v[k];
135
+ if (v === undefined) return false;
136
+ return when.re.test(typeof v === "string" ? v : JSON.stringify(v));
137
+ }
138
+
139
+ function fmtTime(s) { return s >= 3600 ? `${s / 3600}h` : s >= 60 ? `${s / 60}m` : `${s}s`; }
140
+
141
+ function note(policy, effect) {
142
+ if (policy.deny.has(effect)) return `[Lugh policy: ${effect}, denied]`;
143
+ if (policy.allow.has(effect)) return `[Lugh policy: ${effect}, allowed]`;
144
+ return `[Lugh policy: ${effect}, needs human approval]`;
145
+ }
146
+
147
+ // ───────── the proxy ─────────
148
+ export function guard({ policy, command, args, audit, hideDenied = false, onExit = () => {}, stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, env = process.env }) {
149
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], env });
150
+ const state = { started: Date.now(), calls: 0, tools: new Map(), elicitation: false, nextId: 1 };
151
+ const pendingList = new Set(); // ids of tools/list requests we forwarded
152
+ const waiting = new Map(); // our elicitation request id → resolve
153
+ const ownReplies = new Map(); // our own requests to the server → handler
154
+ const log = (kind, fields) => {
155
+ if (!audit) return;
156
+ try {
157
+ mkdirSync(dirname(audit), { recursive: true });
158
+ appendFileSync(audit, JSON.stringify({ t: Date.now() / 1000, agent: policy.agent, kind, ...fields }) + "\n");
159
+ } catch (e) { stderr.write(`lugh guard: cannot write audit log: ${e.message}\n`); }
160
+ };
161
+ const toClient = (msg) => stdout.write(JSON.stringify(msg) + "\n");
162
+ const toServer = (msg) => child.stdin.write(JSON.stringify(msg) + "\n");
163
+ const blocked = (id, text) => toClient({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text }], isError: true } });
164
+
165
+ async function approve(question) {
166
+ if (!state.elicitation) return null; // client cannot ask; caller decides
167
+ const id = `lugh-guard-${state.nextId++}`;
168
+ const answer = new Promise((resolve) => waiting.set(id, resolve));
169
+ toClient({
170
+ jsonrpc: "2.0", id, method: "elicitation/create",
171
+ params: {
172
+ message: question,
173
+ requestedSchema: { type: "object", properties: { approve: { type: "boolean", title: "Allow this action", default: true } } },
174
+ },
175
+ });
176
+ const res = await answer;
177
+ return !!(res && res.action === "accept" && (!res.content || res.content.approve !== false));
178
+ }
179
+
180
+ // Ask the server for its tool list ourselves (used when a call names a tool we haven't seen).
181
+ function refreshTools() {
182
+ const id = `lugh-guard-list-${state.nextId++}`;
183
+ return new Promise((resolve) => {
184
+ ownReplies.set(id, (res) => {
185
+ for (const tool of (res && res.tools) || []) state.tools.set(tool.name, tool);
186
+ resolve();
187
+ });
188
+ toServer({ jsonrpc: "2.0", id, method: "tools/list", params: {} });
189
+ setTimeout(() => { if (ownReplies.delete(id)) resolve(); }, 10000);
190
+ });
191
+ }
192
+
193
+ async function onToolCall(msg) {
194
+ const name = msg.params && msg.params.name;
195
+ if (!state.tools.has(name) && state.initialized) await refreshTools();
196
+ const effect = effectOf(policy, name, state.tools.get(name), (msg.params && msg.params.arguments) || {});
197
+ const shown = JSON.stringify((msg.params && msg.params.arguments) || {});
198
+ const action = `${name} ${shown.length > 300 ? shown.slice(0, 300) + "…" : shown}`;
199
+ const d = decide(policy, state, effect);
200
+ if (d.verdict !== "budget") state.calls++; // as in Lugh Core, every gated call counts, even a denied one
201
+ if (d.verdict === "budget") {
202
+ log("budget", { effect, action, reason: d.reason });
203
+ return blocked(msg.id, `Lugh guard blocked ${name}: ${d.reason}.`);
204
+ }
205
+ if (d.verdict === "deny") {
206
+ log("denied", { effect, action });
207
+ return blocked(msg.id, `Lugh guard blocked ${name}: ${d.reason}. This action is not allowed by the policy; do not retry it another way. Tell the user what you were trying to do.`);
208
+ }
209
+ if (d.verdict === "ask") {
210
+ const ok = await approve(`Lugh guard: allow ${name} (${effect})?\n${shown}`);
211
+ if (ok === null) {
212
+ log("held", { effect, action });
213
+ return blocked(msg.id, `Lugh guard held ${name}: '${effect}' needs a person's approval and this client cannot show an approval prompt. Ask the user; they can allow it in the guard policy.`);
214
+ }
215
+ log("human", { effect, action, answer: ok ? "yes" : "no" });
216
+ if (!ok) return blocked(msg.id, `Lugh guard: the user declined ${name}. Do not retry it.`);
217
+ }
218
+ log("effect", { effect, action });
219
+ toServer(msg);
220
+ }
221
+
222
+ function fromClient(msg) {
223
+ if (Array.isArray(msg)) {
224
+ // JSON-RPC batches are not part of current MCP; never let one carry a call past the gate.
225
+ if (msg.some((m) => m && m.method === "tools/call")) {
226
+ for (const m of msg) if (m && m.id !== undefined) toClient({ jsonrpc: "2.0", id: m.id, error: { code: -32600, message: "Lugh guard does not accept batched tool calls" } });
227
+ return;
228
+ }
229
+ return toServer(msg);
230
+ }
231
+ if (msg.id !== undefined && waiting.has(msg.id) && !msg.method) {
232
+ const resolve = waiting.get(msg.id);
233
+ waiting.delete(msg.id);
234
+ return resolve(msg.error ? null : msg.result);
235
+ }
236
+ if (msg.method === "initialize") {
237
+ state.elicitation = !!(msg.params && msg.params.capabilities && msg.params.capabilities.elicitation);
238
+ }
239
+ if (msg.method === "tools/list" && msg.id !== undefined) pendingList.add(msg.id);
240
+ if (msg.method === "tools/call") return void onToolCall(msg);
241
+ toServer(msg);
242
+ }
243
+
244
+ function fromServer(msg) {
245
+ if (!Array.isArray(msg) && msg.id !== undefined && ownReplies.has(msg.id)) {
246
+ const handle = ownReplies.get(msg.id);
247
+ ownReplies.delete(msg.id);
248
+ return handle(msg.result);
249
+ }
250
+ if (!Array.isArray(msg) && msg.result && msg.result.serverInfo) state.initialized = true;
251
+ if (!Array.isArray(msg) && msg.id !== undefined && pendingList.has(msg.id) && msg.result && Array.isArray(msg.result.tools)) {
252
+ pendingList.delete(msg.id);
253
+ const tools = [];
254
+ for (const tool of msg.result.tools) {
255
+ state.tools.set(tool.name, tool);
256
+ const effect = effectOf(policy, tool.name, tool);
257
+ if (hideDenied && policy.deny.has(effect)) continue;
258
+ tools.push({ ...tool, description: `${tool.description || ""} ${note(policy, effect)}`.trim() });
259
+ }
260
+ msg = { ...msg, result: { ...msg.result, tools } };
261
+ }
262
+ toClient(msg);
263
+ }
264
+
265
+ lines(stdin, fromClient, (bad) => stderr.write(`lugh guard: ignoring a non-JSON line from the client: ${bad.slice(0, 80)}\n`));
266
+ lines(child.stdout, fromServer, (bad) => stderr.write(`lugh guard: server wrote a non-JSON line: ${bad.slice(0, 80)}\n`));
267
+ child.stderr.on("data", (d) => stderr.write(d));
268
+ child.on("exit", (code) => { log("server_exit", { code }); onExit(code ?? 0); });
269
+ child.on("error", (e) => { stderr.write(`lugh guard: cannot start the server: ${e.message}\n`); onExit(1); });
270
+ stdin.on("end", () => child.stdin.end());
271
+ log("start", { command: [command, ...args].join(" ") });
272
+ return child;
273
+ }
274
+
275
+ function lines(stream, onMessage, onBad) {
276
+ let buf = "";
277
+ stream.on("data", (chunk) => {
278
+ buf += chunk.toString("utf8");
279
+ let i;
280
+ while ((i = buf.indexOf("\n")) >= 0) {
281
+ const line = buf.slice(0, i).trim();
282
+ buf = buf.slice(i + 1);
283
+ if (!line) continue;
284
+ let msg;
285
+ try { msg = JSON.parse(line); } catch { onBad(line); continue; }
286
+ onMessage(msg);
287
+ }
288
+ });
289
+ }
290
+
291
+ // A policy is a file path, or the name of a bundled pack (default, filesystem, github, supabase, stripe).
292
+ export const PACKS = ["default", "filesystem", "github", "supabase", "stripe"];
293
+ export function resolvePolicy(name) {
294
+ if (existsSync(name)) return name;
295
+ if (PACKS.includes(name)) return fileURLToPath(new URL(`../policies/${name}.lugh`, import.meta.url));
296
+ throw new Error(`no policy file '${name}' (bundled packs: ${PACKS.join(", ")})`);
297
+ }
298
+
299
+ // CLI entry: lugh-lang guard --policy <file> [--audit <file>] [--hide-denied] -- <command> [args...]
300
+ export function main(argv) {
301
+ const sep = argv.indexOf("--");
302
+ const opts = sep >= 0 ? argv.slice(0, sep) : argv;
303
+ const cmd = sep >= 0 ? argv.slice(sep + 1) : [];
304
+ const get = (flag) => { const i = opts.indexOf(flag); return i >= 0 ? opts[i + 1] : undefined; };
305
+ const file = get("--policy");
306
+ if (!file || !cmd.length) {
307
+ process.stderr.write("usage: npx lugh-lang guard --policy <file.lugh | default | filesystem | github | supabase | stripe> [--audit <log.jsonl>] [--hide-denied] -- <server command> [args...]\n");
308
+ process.exit(2);
309
+ }
310
+ let policy;
311
+ try { policy = parsePolicy(readFileSync(resolvePolicy(file), "utf8")); } catch (e) { process.stderr.write(`lugh guard: ${e.message}\n`); process.exit(2); }
312
+ const audit = get("--audit") || join(homedir(), ".lugh", "guard-audit.jsonl");
313
+ guard({ policy, command: cmd[0], args: cmd.slice(1), audit, hideDenied: opts.includes("--hide-denied"), onExit: (code) => process.exit(code) });
314
+ }
@@ -0,0 +1,173 @@
1
+ // lugh-lang protect: put every local MCP server you already use behind Lugh guard.
2
+ //
3
+ // npx lugh-lang protect show the plan, then ask before changing anything
4
+ // npx lugh-lang protect --yes apply without asking
5
+ // npx lugh-lang protect --undo put every config back the way it was
6
+ //
7
+ // It finds MCP configs for Claude Code, Claude Desktop, Cursor, VS Code and
8
+ // Windsurf, and rewrites each local (stdio) server entry from
9
+ // "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "~/docs"]
10
+ // to
11
+ // "command": "npx", "args": ["-y", "lugh-lang", "guard", "--policy", "filesystem", "--",
12
+ // "npx", "-y", "@modelcontextprotocol/server-filesystem", "~/docs"]
13
+ // Nothing else in the file changes. A copy of each file is saved next to it
14
+ // first (<file>.lugh-backup), and --undo unwraps the entries in place, so later
15
+ // edits you made to the file are kept.
16
+
17
+ import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join, resolve } from "node:path";
20
+ import { createInterface } from "node:readline";
21
+
22
+ // Where each client keeps its MCP servers. `key` is the object holding the
23
+ // servers; `projects` marks Claude Code's per-project ("local") servers.
24
+ export function configLocations({ home = homedir(), cwd = process.cwd(), platform = process.platform, env = process.env } = {}) {
25
+ const appData = env.APPDATA || join(home, "AppData", "Roaming");
26
+ const appSupport = platform === "darwin" ? join(home, "Library", "Application Support")
27
+ : platform === "win32" ? appData : join(home, ".config");
28
+ const list = [
29
+ { client: "Claude Code (user and local)", file: join(home, ".claude.json"), key: "mcpServers", projects: true },
30
+ { client: "Claude Code (this project)", file: join(cwd, ".mcp.json"), key: "mcpServers" },
31
+ { client: "Claude Desktop", file: join(appSupport, "Claude", "claude_desktop_config.json"), key: "mcpServers" },
32
+ { client: "Cursor", file: join(home, ".cursor", "mcp.json"), key: "mcpServers" },
33
+ { client: "Cursor (this project)", file: join(cwd, ".cursor", "mcp.json"), key: "mcpServers" },
34
+ { client: "VS Code", file: join(appSupport, "Code", "User", "mcp.json"), key: "servers" },
35
+ { client: "VS Code (this project)", file: join(cwd, ".vscode", "mcp.json"), key: "servers" },
36
+ { client: "Windsurf", file: join(home, ".codeium", "windsurf", "mcp_config.json"), key: "mcpServers" },
37
+ ];
38
+ const seen = new Set();
39
+ return list.filter((l) => { const f = resolve(l.file); if (seen.has(f)) return false; seen.add(f); return true; });
40
+ }
41
+
42
+ // Which bundled policy fits a server, from its command line.
43
+ export function packFor(entry) {
44
+ const s = [entry.command, ...(entry.args || [])].join(" ").toLowerCase();
45
+ if (s.includes("server-filesystem")) return "filesystem";
46
+ if (s.includes("github-mcp-server") || s.includes("server-github") || s.includes("githubcopilot.com/mcp")) return "github";
47
+ if (s.includes("supabase")) return "supabase";
48
+ if (s.includes("mcp.stripe.com") || s.includes("@stripe/mcp")) return "stripe";
49
+ return "default";
50
+ }
51
+
52
+ const isLugh = (e) => [e.command, ...(e.args || [])].some((a) => typeof a === "string" && /(^|[/@])lugh-lang(@[\w.]+)?$/.test(a));
53
+
54
+ // The guard's own arguments inside a wrapped entry: [... "guard", "--policy", P, (flags), "--", cmd, ...args]
55
+ function unwrapArgs(entry) {
56
+ const args = entry.args || [];
57
+ const g = args.indexOf("guard");
58
+ const sep = args.indexOf("--", g);
59
+ if (g < 0 || sep < 0 || !args.slice(0, g).some((a) => /lugh-lang/.test(a))) return null;
60
+ const inner = args.slice(sep + 1);
61
+ if (!inner.length) return null;
62
+ return { command: inner[0], args: inner.slice(1) };
63
+ }
64
+
65
+ export function wrapEntry(entry, pack, platform = process.platform) {
66
+ const inner = [entry.command, ...(entry.args || [])];
67
+ const guard = ["-y", "lugh-lang", "guard", "--policy", pack, "--", ...inner];
68
+ return platform === "win32"
69
+ ? { ...entry, command: "cmd", args: ["/c", "npx", ...guard] }
70
+ : { ...entry, command: "npx", args: guard };
71
+ }
72
+
73
+ export function unwrapEntry(entry) {
74
+ const inner = unwrapArgs(entry);
75
+ return inner ? { ...entry, ...inner } : null;
76
+ }
77
+
78
+ // Every server block in one parsed config, with a path for messages.
79
+ function blocks(json, loc) {
80
+ const out = [];
81
+ if (json && typeof json[loc.key] === "object" && json[loc.key]) out.push({ where: "", servers: json[loc.key] });
82
+ if (loc.projects && json && typeof json.projects === "object") {
83
+ for (const [path, p] of Object.entries(json.projects)) {
84
+ if (p && typeof p.mcpServers === "object" && p.mcpServers && Object.keys(p.mcpServers).length) out.push({ where: ` [${path}]`, servers: p.mcpServers });
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+
90
+ // Work out what would change. Returns one item per config file that has servers.
91
+ export function plan({ undo = false, platform = process.platform, ...where } = {}) {
92
+ const files = [];
93
+ for (const loc of configLocations({ platform, ...where })) {
94
+ if (!existsSync(loc.file)) continue;
95
+ let json;
96
+ try { json = JSON.parse(readFileSync(loc.file, "utf8")); } catch (e) {
97
+ files.push({ ...loc, error: `not valid JSON (${e.message}); left alone` });
98
+ continue;
99
+ }
100
+ const changes = [];
101
+ for (const b of blocks(json, loc)) {
102
+ for (const [name, entry] of Object.entries(b.servers)) {
103
+ if (!entry || typeof entry !== "object") continue;
104
+ if (undo) {
105
+ const un = unwrapEntry(entry);
106
+ if (un) changes.push({ name: name + b.where, servers: b.servers, key: name, to: un, note: "guard removed" });
107
+ continue;
108
+ }
109
+ if (entry.url || (entry.type && entry.type !== "stdio")) { changes.push({ name: name + b.where, skip: "remote server: guard runs local (stdio) servers; see docs/GUARD.md for mcp-remote" }); continue; }
110
+ if (!entry.command) continue;
111
+ if (unwrapArgs(entry)) { changes.push({ name: name + b.where, skip: "already guarded" }); continue; }
112
+ if (isLugh(entry)) { changes.push({ name: name + b.where, skip: "Lugh's own server" }); continue; }
113
+ const pack = packFor(entry);
114
+ changes.push({ name: name + b.where, servers: b.servers, key: name, to: wrapEntry(entry, pack, platform), note: `guard, policy ${pack}` });
115
+ }
116
+ }
117
+ if (changes.length) files.push({ ...loc, json, changes });
118
+ }
119
+ return files;
120
+ }
121
+
122
+ // Write the planned changes: backup first, then an atomic replace.
123
+ export function apply(files) {
124
+ let changed = 0;
125
+ for (const f of files) {
126
+ const todo = (f.changes || []).filter((c) => c.to);
127
+ if (!todo.length) continue;
128
+ for (const c of todo) c.servers[c.key] = c.to;
129
+ const backup = f.file + ".lugh-backup";
130
+ copyFileSync(f.file, backup);
131
+ const tmp = f.file + ".lugh-tmp";
132
+ writeFileSync(tmp, JSON.stringify(f.json, null, 2) + "\n");
133
+ renameSync(tmp, f.file);
134
+ changed += todo.length;
135
+ }
136
+ return changed;
137
+ }
138
+
139
+ function describe(files, undo) {
140
+ if (!files.length) return "No MCP servers found in Claude Code, Claude Desktop, Cursor, VS Code or Windsurf configs.";
141
+ const lines = [];
142
+ for (const f of files) {
143
+ lines.push(`${f.client}: ${f.file}`);
144
+ if (f.error) { lines.push(` ! ${f.error}`); continue; }
145
+ for (const c of f.changes) lines.push(c.to ? ` ✓ ${c.name}: ${c.note}` : ` · ${c.name}: ${c.skip}`);
146
+ }
147
+ return lines.join("\n");
148
+ }
149
+
150
+ export async function main(argv) {
151
+ const undo = argv.includes("--undo");
152
+ const yes = argv.includes("--yes") || argv.includes("-y");
153
+ const files = plan({ undo });
154
+ const count = files.flatMap((f) => f.changes || []).filter((c) => c.to).length;
155
+ console.log(describe(files, undo));
156
+ if (!count) {
157
+ console.log(undo ? "\nNothing to undo." : "\nNothing to change.");
158
+ return;
159
+ }
160
+ console.log(undo
161
+ ? `\n${count} server(s) will go back to running without guard.`
162
+ : `\n${count} server(s) will run behind Lugh guard. Reads run, risky actions ask you, destructive ones are refused.\nA copy of each file is saved as <file>.lugh-backup; undo any time with: npx lugh-lang protect --undo`);
163
+ if (!yes) {
164
+ if (!process.stdin.isTTY) { console.log("\nRun again with --yes to apply."); return; }
165
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
166
+ const answer = await new Promise((r) => rl.question("\nApply these changes? [y/N] ", r));
167
+ rl.close();
168
+ if (!/^y(es)?$/i.test(answer.trim())) { console.log("No changes made."); return; }
169
+ }
170
+ const n = apply(files);
171
+ console.log(`\nDone: ${n} server(s) ${undo ? "unguarded" : "guarded"}. Restart your MCP clients to pick up the change.`);
172
+ if (!undo) console.log("Every decision is logged to ~/.lugh/guard-audit.jsonl. Policies: https://github.com/Ashutosh3142857/lugh-lang/blob/main/docs/GUARD.md");
173
+ }
package/lugh.wasm CHANGED
Binary file
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "lugh-lang",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Lugh, the programming language for AI agents: check and dry-run programs where policy, budgets and human approval are part of the code. Includes an MCP server.",
5
5
  "mcpName": "io.github.Ashutosh3142857/lugh",
6
6
  "type": "module",
7
7
  "bin": { "lugh-lang": "bin/lugh-lang.mjs" },
8
8
  "exports": { ".": "./lib/runtime.mjs", "./mcp": "./lib/mcp.mjs" },
9
- "files": ["bin/", "lib/", "lugh.wasm", "REFERENCE.md", "README.md"],
9
+ "files": ["bin/", "lib/", "policies/", "lugh.wasm", "REFERENCE.md", "README.md"],
10
10
  "engines": { "node": ">=18" },
11
- "scripts": { "test": "node test/mcp.test.mjs" },
12
- "keywords": ["ai-agents", "agents", "mcp", "model-context-protocol", "mcp-server", "programming-language", "guardrails", "human-in-the-loop", "agent-safety", "policy", "webassembly"],
11
+ "scripts": { "test": "node test/mcp.test.mjs && node --test --test-timeout=15000 test/guard.test.mjs test/protect.test.mjs" },
12
+ "keywords": ["ai-agents", "mcp-proxy", "mcp-guard", "mcp-security", "agents", "mcp", "model-context-protocol", "mcp-server", "programming-language", "guardrails", "human-in-the-loop", "agent-safety", "policy", "webassembly"],
13
13
  "homepage": "https://ashutosh3142857.github.io/lugh-lang/",
14
14
  "repository": { "type": "git", "url": "git+https://github.com/Ashutosh3142857/lugh-lang.git", "directory": "npm" },
15
15
  "bugs": "https://github.com/Ashutosh3142857/lugh-lang/issues",
@@ -0,0 +1,12 @@
1
+ # Lugh guard policy for any MCP server without a pack of its own.
2
+ # npx -y lugh-lang guard --policy default -- <server command>
3
+ #
4
+ # Reads run freely. Anything that writes, sends, submits, spends money or runs
5
+ # commands asks first. Anything the server marks destructive is refused. Tools
6
+ # that carry no annotations count as submit, so they ask.
7
+ agent DefaultGuard
8
+ budget calls 500
9
+ policy
10
+ allow read
11
+ ask human before write, send, submit, spend, execute
12
+ deny delete
@@ -0,0 +1,17 @@
1
+ # Lugh guard policy for @modelcontextprotocol/server-filesystem
2
+ # npx -y lugh-lang guard --policy filesystem -- npx -y @modelcontextprotocol/server-filesystem <dir>
3
+ #
4
+ # Reads run freely. Writing, editing and moving ask first (the server marks
5
+ # them destructive, which would otherwise make them deletes). Nothing is ever
6
+ # deleted, and a runaway loop stops after 500 calls.
7
+ agent FilesystemGuard
8
+ budget calls 500
9
+ policy
10
+ allow read
11
+ ask human before write, submit
12
+ deny delete
13
+ tools
14
+ "write_file" is write
15
+ "edit_file" is write
16
+ "move_file" is write
17
+ "create_directory" is write
@@ -0,0 +1,24 @@
1
+ # Lugh guard policy for the GitHub MCP server (github/github-mcp-server)
2
+ # npx -y lugh-lang guard --policy github -- docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN ghcr.io/github/github-mcp-server
3
+ #
4
+ # Reading code, issues and pull requests runs freely. Anything that writes,
5
+ # comments, pushes or merges asks first. Deleting repositories and files is
6
+ # never allowed. Multi-purpose tools (issue_write, projects_write,
7
+ # pull_request_review_write) can delete through a method argument, so they
8
+ # always ask.
9
+ agent GitHubGuard
10
+ budget calls 300
11
+ policy
12
+ allow read
13
+ ask human before write, submit, send
14
+ deny delete
15
+ tools
16
+ "delete_repository" is delete
17
+ "delete_file" is delete
18
+ "merge_pull_request" is write
19
+ "push_files" is write
20
+ "create_or_update_file" is write
21
+ "update_pull_request_branch" is write
22
+ "get_*" is read
23
+ "list_*" is read
24
+ "search_*" is read
@@ -0,0 +1,23 @@
1
+ # Lugh guard policy for the Stripe MCP server
2
+ # npx -y lugh-lang guard --policy stripe -- npx -y mcp-remote https://mcp.stripe.com
3
+ #
4
+ # Looking things up runs freely. Every write to Stripe asks first, and money
5
+ # movement (Treasury sends, transfers and conversions) asks too. Stripe adds
6
+ # its own human confirmation for refunds; this policy adds one in your client
7
+ # for everything else that changes your account.
8
+ agent StripeGuard
9
+ budget calls 200
10
+ policy
11
+ allow read
12
+ ask human before write, spend, submit
13
+ deny delete
14
+ tools
15
+ "stripe_api_read" is read
16
+ "stripe_api_search" is read
17
+ "stripe_api_details" is read
18
+ "search_stripe_documentation" is read
19
+ "get_*" is read
20
+ "stripe_api_write" is write
21
+ "send_money" is spend
22
+ "transfer_money" is spend
23
+ "convert_currency" is spend
@@ -0,0 +1,31 @@
1
+ # Lugh guard policy for the Supabase MCP server
2
+ # npx -y lugh-lang guard --policy supabase -- npx -y mcp-remote "https://mcp.supabase.com/mcp?project_ref=<ref>"
3
+ #
4
+ # The production-database rule: SQL that drops, truncates or deletes is
5
+ # refused before it reaches the database, every other statement asks first,
6
+ # and so do migrations, branch merges and deploys. Pattern rules are a speed
7
+ # bump, not a parser: pair this with Supabase's own read_only=true wherever
8
+ # writes are not needed.
9
+ agent SupabaseGuard
10
+ budget calls 200
11
+ policy
12
+ allow read
13
+ ask human before write, execute, submit, spend
14
+ deny delete
15
+ tools
16
+ "execute_sql" when query matches "\b(drop|truncate|delete|alter\s+table\s+\S+\s+drop|revoke)\b" is delete
17
+ "execute_sql" is execute
18
+ "apply_migration" when query matches "\b(drop|truncate|delete)\b" is delete
19
+ "apply_migration" is write
20
+ "delete_*" is delete
21
+ "reset_branch" is delete
22
+ "pause_project" is delete
23
+ "merge_branch" is write
24
+ "rebase_branch" is write
25
+ "deploy_edge_function" is write
26
+ "create_project" is spend
27
+ "create_branch" is spend
28
+ "list_*" is read
29
+ "get_*" is read
30
+ "search_docs" is read
31
+ "query_logs" is read