@agentlaw/gateway 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.
@@ -0,0 +1,287 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
3
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import {
6
+ CallToolRequestSchema,
7
+ GetPromptRequestSchema,
8
+ ListPromptsRequestSchema,
9
+ ListResourcesRequestSchema,
10
+ ListResourceTemplatesRequestSchema,
11
+ ListToolsRequestSchema,
12
+ PromptListChangedNotificationSchema,
13
+ ReadResourceRequestSchema,
14
+ ResourceListChangedNotificationSchema,
15
+ ToolListChangedNotificationSchema,
16
+ type ServerCapabilities,
17
+ } from "@modelcontextprotocol/sdk/types.js";
18
+ import { evaluate, lintManifest, type LoadedPolicy, type Verdict } from "@agentlaw/core";
19
+ import { AuditWriter, redactArgs } from "@agentlaw/audit";
20
+ import { scopedEnv } from "./credscope.js";
21
+ import { requestApprovalWithTimeout } from "../approvals/broker.js";
22
+ import { TerminalApprovalChannel } from "../approvals/terminal-channel.js";
23
+ import type { ApprovalChannel } from "../approvals/types.js";
24
+
25
+ const GATEWAY_VERSION = "0.1.0";
26
+ const DEFAULT_REDACT = ["password", "token", "secret", "apiKey"];
27
+
28
+ export interface GatewayOptions {
29
+ loaded: LoadedPolicy;
30
+ /** Server identity used in rule matching (`match.server`). */
31
+ serverName: string;
32
+ /** Downstream MCP server command. */
33
+ command: string;
34
+ args: string[];
35
+ /** Overrides the manifest's audit.dir. */
36
+ auditDir?: string;
37
+ /**
38
+ * Human-in-the-loop channel for `approve` verdicts, used when the manifest
39
+ * sets `approvals.mode: terminal` or `approvals.mode: external`. Defaults
40
+ * to a real terminal prompt for `terminal`; `external` has no built-in
41
+ * default (the CLI wires @agentlaw/sink-supabase's SupabaseApprovalChannel
42
+ * when Supabase is configured) — an `external` mode with nothing injected
43
+ * here stays fail-closed. Tests inject a scripted fake instead of touching
44
+ * a real TTY or network.
45
+ */
46
+ approvalChannel?: ApprovalChannel;
47
+ /**
48
+ * Best-effort mirror of approval events to a remote store (e.g.
49
+ * @agentlaw/sink-supabase's SupabaseAgentLawSink), so a console watching
50
+ * `agentlaw_audit` sees the request/resolution even though the local JSONL
51
+ * file remains the source of truth. Never allowed to affect the verdict:
52
+ * any failure here is swallowed.
53
+ */
54
+ remoteAuditSink?: { append(event: string, fields: Record<string, unknown>): Promise<unknown> };
55
+ }
56
+
57
+ /** Modes with a real channel implementation. Every other/unset value keeps `approve` fail-closed. */
58
+ const WIRED_APPROVAL_MODES = new Set(["terminal", "external"]);
59
+
60
+ async function mirrorAudit(
61
+ sink: GatewayOptions["remoteAuditSink"],
62
+ event: string,
63
+ fields: Record<string, unknown>,
64
+ ): Promise<void> {
65
+ if (!sink) return;
66
+ try {
67
+ await sink.append(event, fields);
68
+ } catch {
69
+ /* best-effort: the local audit file remains the source of truth */
70
+ }
71
+ }
72
+
73
+ function log(message: string): void {
74
+ process.stderr.write(`[agentlaw] ${message}\n`);
75
+ }
76
+
77
+ function denyPayload(code: string, verdict: Verdict) {
78
+ const reason = verdict.reason ? ` reason=${JSON.stringify(verdict.reason)}` : "";
79
+ return {
80
+ content: [{ type: "text" as const, text: `${code} rule=${verdict.ruleId}${reason}` }],
81
+ isError: true,
82
+ };
83
+ }
84
+
85
+ /**
86
+ * The stdio MCP proxy: an MCP server toward the client, an MCP client toward
87
+ * the downstream it spawns. Every tools/call runs through the deterministic
88
+ * evaluator; the audit entry is flushed to disk BEFORE the call is forwarded
89
+ * (write-ahead audit: no action without its record).
90
+ */
91
+ export async function runGateway(options: GatewayOptions): Promise<void> {
92
+ const { loaded, serverName } = options;
93
+ const manifest = loaded.manifest;
94
+ // Session start is stamped by the host here, never taken from a tool call, so
95
+ // `$sessionAgeMs` conditions cannot be spoofed by the agent.
96
+ const sessionStartedAt = Date.now();
97
+ const redactKeys = manifest.audit?.redactArgs ?? DEFAULT_REDACT;
98
+ const auditDir = options.auditDir ?? manifest.audit?.dir ?? "./.agentlaw/audit";
99
+ const approvalChannel =
100
+ options.approvalChannel ?? (manifest.approvals?.mode === "terminal" ? new TerminalApprovalChannel() : undefined);
101
+
102
+ for (const warning of lintManifest(manifest)) log(`warning: ${warning}`);
103
+
104
+ const audit = await AuditWriter.open({ dir: auditDir, policyHash: loaded.hash });
105
+ audit.append("policy_loaded", {
106
+ policy: manifest.metadata.name,
107
+ version: manifest.metadata.version,
108
+ server: serverName,
109
+ ...(loaded.keyId !== undefined ? { keyId: loaded.keyId } : {}),
110
+ ...(loaded.unsigned ? { unsigned: true } : {}),
111
+ });
112
+
113
+ const shutdown = async (code: number): Promise<never> => {
114
+ try {
115
+ await audit.flush();
116
+ } catch (err) {
117
+ log(`audit flush failed: ${(err as Error).message}`);
118
+ }
119
+ process.exit(code);
120
+ };
121
+ process.on("SIGINT", () => void shutdown(0));
122
+ process.on("SIGTERM", () => void shutdown(0));
123
+
124
+ // --- downstream ---------------------------------------------------------
125
+ const downstream = new Client({ name: "agentlaw-gateway", version: GATEWAY_VERSION });
126
+ const downstreamTransport = new StdioClientTransport({
127
+ command: options.command,
128
+ args: options.args,
129
+ env: scopedEnv(manifest.credentials?.[serverName]),
130
+ stderr: "inherit",
131
+ });
132
+ await downstream.connect(downstreamTransport);
133
+ const caps = downstream.getServerCapabilities() ?? {};
134
+ log(`downstream "${serverName}" connected (${options.command})`);
135
+
136
+ downstream.onclose = () => {
137
+ audit.append("server_down", { server: serverName });
138
+ log(`downstream "${serverName}" closed — shutting down (fail-closed)`);
139
+ void shutdown(1);
140
+ };
141
+
142
+ // --- facade --------------------------------------------------------------
143
+ const facadeCaps: ServerCapabilities = { tools: { listChanged: true } };
144
+ if (caps.resources) facadeCaps.resources = { listChanged: true };
145
+ if (caps.prompts) facadeCaps.prompts = { listChanged: true };
146
+
147
+ const facade = new Server(
148
+ { name: "agentlaw", version: GATEWAY_VERSION },
149
+ { capabilities: facadeCaps },
150
+ );
151
+
152
+ facade.setRequestHandler(ListToolsRequestSchema, async () => {
153
+ return await downstream.listTools();
154
+ });
155
+
156
+ const forwardToDownstream = async (tool: string, args: Record<string, unknown>) => {
157
+ try {
158
+ return await downstream.callTool({ name: tool, arguments: args });
159
+ } catch (err) {
160
+ return {
161
+ content: [{ type: "text" as const, text: `DOWNSTREAM_ERROR ${(err as Error).message}` }],
162
+ isError: true,
163
+ };
164
+ }
165
+ };
166
+
167
+ facade.setRequestHandler(CallToolRequestSchema, async (request) => {
168
+ const tool = request.params.name;
169
+ const args = (request.params.arguments ?? {}) as Record<string, unknown>;
170
+ const verdict = evaluate(loaded.compiled, { server: serverName, tool, args }, Date.now(), {
171
+ sessionStartedAt,
172
+ });
173
+
174
+ const { redacted, argsHash } = redactArgs(args, redactKeys);
175
+ audit.append("tool_call", {
176
+ server: serverName,
177
+ tool,
178
+ args: redacted,
179
+ argsHash,
180
+ decision: verdict.decision,
181
+ effect: verdict.effect,
182
+ ruleId: verdict.ruleId,
183
+ ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
184
+ ...(loaded.unsigned ? { unsigned: true } : {}),
185
+ });
186
+ await audit.flush(); // write-ahead: the record exists before the action does
187
+
188
+ switch (verdict.decision) {
189
+ case "deny":
190
+ return denyPayload("POLICY_DENIED", verdict);
191
+ case "allow":
192
+ return await forwardToDownstream(tool, args);
193
+ case "approve": {
194
+ const mode = manifest.approvals?.mode;
195
+ if (!WIRED_APPROVAL_MODES.has(mode ?? "") || !approvalChannel) {
196
+ // Every other/unset approvals.mode keeps this fail-closed stub — and
197
+ // so does a wired mode (e.g. "external") with nothing actually
198
+ // injected via GatewayOptions.approvalChannel: the mode alone never
199
+ // opens the door.
200
+ if (mode && WIRED_APPROVAL_MODES.has(mode) && !approvalChannel) {
201
+ log(`approvals.mode="${mode}" but no approval channel is configured — denying rule=${verdict.ruleId} (fail-closed)`);
202
+ }
203
+ return denyPayload("POLICY_APPROVAL_REQUIRED", verdict);
204
+ }
205
+ const timeoutMs = manifest.approvals!.timeoutMs;
206
+ const requestedFields = {
207
+ server: serverName,
208
+ tool,
209
+ ruleId: verdict.ruleId,
210
+ argsHash,
211
+ timeoutMs,
212
+ };
213
+ audit.append("approval_requested", requestedFields);
214
+ await audit.flush();
215
+ await mirrorAudit(options.remoteAuditSink, "approval_requested", requestedFields);
216
+
217
+ const result = await requestApprovalWithTimeout(
218
+ approvalChannel,
219
+ {
220
+ ruleId: verdict.ruleId,
221
+ server: serverName,
222
+ tool,
223
+ args,
224
+ ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
225
+ },
226
+ timeoutMs,
227
+ );
228
+
229
+ const resolvedFields = {
230
+ server: serverName,
231
+ tool,
232
+ ruleId: verdict.ruleId,
233
+ outcome: result.outcome,
234
+ };
235
+ audit.append("approval_resolved", resolvedFields);
236
+ await audit.flush();
237
+ await mirrorAudit(options.remoteAuditSink, "approval_resolved", resolvedFields);
238
+
239
+ if (result.outcome === "approved") {
240
+ return await forwardToDownstream(tool, args);
241
+ }
242
+ const code = result.outcome === "timeout" ? "POLICY_APPROVAL_TIMEOUT" : "POLICY_APPROVAL_DENIED";
243
+ return denyPayload(code, verdict);
244
+ }
245
+ }
246
+ });
247
+
248
+ if (caps.resources) {
249
+ facade.setRequestHandler(ListResourcesRequestSchema, async (request) => {
250
+ return await downstream.listResources(request.params);
251
+ });
252
+ facade.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) => {
253
+ return await downstream.listResourceTemplates(request.params);
254
+ });
255
+ facade.setRequestHandler(ReadResourceRequestSchema, async (request) => {
256
+ audit.append("resource_read", { server: serverName, uri: request.params.uri });
257
+ return await downstream.readResource(request.params);
258
+ });
259
+ downstream.setNotificationHandler(ResourceListChangedNotificationSchema, async () => {
260
+ await facade.notification({ method: "notifications/resources/list_changed" });
261
+ });
262
+ }
263
+
264
+ if (caps.prompts) {
265
+ facade.setRequestHandler(ListPromptsRequestSchema, async (request) => {
266
+ return await downstream.listPrompts(request.params);
267
+ });
268
+ facade.setRequestHandler(GetPromptRequestSchema, async (request) => {
269
+ return await downstream.getPrompt(request.params);
270
+ });
271
+ downstream.setNotificationHandler(PromptListChangedNotificationSchema, async () => {
272
+ await facade.notification({ method: "notifications/prompts/list_changed" });
273
+ });
274
+ }
275
+
276
+ downstream.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
277
+ await facade.notification({ method: "notifications/tools/list_changed" });
278
+ });
279
+
280
+ const facadeTransport = new StdioServerTransport();
281
+ facadeTransport.onclose = () => {
282
+ log("client disconnected — shutting down");
283
+ void shutdown(0);
284
+ };
285
+ await facade.connect(facadeTransport);
286
+ log(`serving policy ${manifest.metadata.name}@${manifest.metadata.version} (${loaded.hash})`);
287
+ }