mandat 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.
Files changed (70) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +293 -3
  3. package/dist/approvals/approvals.d.ts +136 -0
  4. package/dist/approvals/approvals.js +262 -0
  5. package/dist/bridge.d.ts +38 -0
  6. package/dist/bridge.js +117 -0
  7. package/dist/cli/args.d.ts +9 -0
  8. package/dist/cli/args.js +39 -0
  9. package/dist/cli/bin.d.ts +2 -0
  10. package/dist/cli/bin.js +3 -0
  11. package/dist/cli/main.d.ts +1 -0
  12. package/dist/cli/main.js +649 -0
  13. package/dist/cli/templates.d.ts +91 -0
  14. package/dist/cli/templates.js +57 -0
  15. package/dist/client.d.ts +54 -0
  16. package/dist/client.js +88 -0
  17. package/dist/controlplane/config.d.ts +48 -0
  18. package/dist/controlplane/config.js +33 -0
  19. package/dist/controlplane/console/.claude-flow/neural/patterns.json +402 -0
  20. package/dist/controlplane/console/.claude-flow/neural/stats.json +6 -0
  21. package/dist/controlplane/console/.claude-flow/policy/ledger-anchors.json +3 -0
  22. package/dist/controlplane/console/.claude-flow/policy/state.json +54 -0
  23. package/dist/controlplane/console/app.css +93 -0
  24. package/dist/controlplane/console/app.js +330 -0
  25. package/dist/controlplane/console/index.html +70 -0
  26. package/dist/controlplane/server.d.ts +17 -0
  27. package/dist/controlplane/server.js +427 -0
  28. package/dist/guard/guard.d.ts +154 -0
  29. package/dist/guard/guard.js +290 -0
  30. package/dist/guard/pinning.d.ts +46 -0
  31. package/dist/guard/pinning.js +49 -0
  32. package/dist/guard/remote.d.ts +78 -0
  33. package/dist/guard/remote.js +185 -0
  34. package/dist/index.d.ts +43 -0
  35. package/dist/index.js +67 -0
  36. package/dist/ledger/export.d.ts +27 -0
  37. package/dist/ledger/export.js +169 -0
  38. package/dist/ledger/ledger.d.ts +117 -0
  39. package/dist/ledger/ledger.js +139 -0
  40. package/dist/ledger/redact.d.ts +13 -0
  41. package/dist/ledger/redact.js +73 -0
  42. package/dist/ledger/report.d.ts +71 -0
  43. package/dist/ledger/report.js +128 -0
  44. package/dist/mcp/protect.d.ts +8 -0
  45. package/dist/mcp/protect.js +68 -0
  46. package/dist/mcp/server.d.ts +49 -0
  47. package/dist/mcp/server.js +211 -0
  48. package/dist/oidc.d.ts +52 -0
  49. package/dist/oidc.js +194 -0
  50. package/dist/policy/engine.d.ts +135 -0
  51. package/dist/policy/engine.js +243 -0
  52. package/dist/policy/expr.d.ts +56 -0
  53. package/dist/policy/expr.js +506 -0
  54. package/dist/scan/findings.d.ts +32 -0
  55. package/dist/scan/findings.js +105 -0
  56. package/dist/scan/remote.d.ts +7 -0
  57. package/dist/scan/remote.js +225 -0
  58. package/dist/scan/static.d.ts +15 -0
  59. package/dist/scan/static.js +245 -0
  60. package/dist/store.d.ts +14 -0
  61. package/dist/store.js +40 -0
  62. package/dist/sts/jwt.d.ts +64 -0
  63. package/dist/sts/jwt.js +168 -0
  64. package/dist/sts/revocation.d.ts +38 -0
  65. package/dist/sts/revocation.js +52 -0
  66. package/dist/sts/sts.d.ts +83 -0
  67. package/dist/sts/sts.js +239 -0
  68. package/dist/util.d.ts +28 -0
  69. package/dist/util.js +137 -0
  70. package/package.json +47 -4
@@ -0,0 +1,71 @@
1
+ import { type ActionRecord, type VerifyResult } from "./ledger.ts";
2
+ export interface ReportOptions {
3
+ from?: string;
4
+ to?: string;
5
+ retentionDays?: number;
6
+ title?: string;
7
+ }
8
+ export interface ReportData {
9
+ generated_at: string;
10
+ period: {
11
+ from: string | null;
12
+ to: string | null;
13
+ };
14
+ integrity: VerifyResult;
15
+ retention: {
16
+ configured_days: number | null;
17
+ oldest_record: string | null;
18
+ meets_ai_act_minimum: boolean | null;
19
+ };
20
+ totals: {
21
+ records: number;
22
+ tool_calls: number;
23
+ allowed: number;
24
+ denied: number;
25
+ pending: number;
26
+ shadow_would_deny: number;
27
+ };
28
+ by_agent: Array<{
29
+ agent: string;
30
+ calls: number;
31
+ denied: number;
32
+ approvals: number;
33
+ }>;
34
+ by_tool: Array<{
35
+ tool: string;
36
+ risk: string | null;
37
+ calls: number;
38
+ denied: number;
39
+ }>;
40
+ principals: number;
41
+ approvals: Array<{
42
+ id: string;
43
+ tool: string | null;
44
+ agent: string | null;
45
+ principal: string | null;
46
+ status: string;
47
+ approvers: string[];
48
+ requested_at: string;
49
+ decided_at: string | null;
50
+ wait_s: number | null;
51
+ }>;
52
+ denials: Array<{
53
+ ts: string;
54
+ agent: string | null;
55
+ principal: string | null;
56
+ tool: string | null;
57
+ rules: string[];
58
+ reasons: string[];
59
+ }>;
60
+ admin_events: Array<{
61
+ ts: string;
62
+ type: string;
63
+ details: unknown;
64
+ }>;
65
+ drift_events: Array<{
66
+ ts: string;
67
+ details: unknown;
68
+ }>;
69
+ }
70
+ export declare function buildReport(all: ActionRecord[], opts?: ReportOptions): ReportData;
71
+ export declare function reportToMarkdown(d: ReportData, title?: string): string;
@@ -0,0 +1,128 @@
1
+ // Compliance / DPO evidence report built from the hash chain (US-8).
2
+ // Technical evidence only: qualification of a concrete system remains the operator's responsibility.
3
+ import { verifyRecords } from "./ledger.js";
4
+ const AI_ACT_MIN_RETENTION_DAYS = 183; // Art. 19 / 26(6): at least six months
5
+ export function buildReport(all, opts = {}) {
6
+ const integrity = verifyRecords(all);
7
+ const recs = all.filter((r) => (!opts.from || r.ts >= opts.from) && (!opts.to || r.ts <= opts.to));
8
+ const calls = recs.filter((r) => r.type === "agent.tool_call");
9
+ const byAgent = new Map();
10
+ const byTool = new Map();
11
+ for (const c of calls) {
12
+ const a = c.agent?.id ?? "?";
13
+ const t = c.tool?.name ?? "?";
14
+ const ae = byAgent.get(a) ?? { agent: a, calls: 0, denied: 0, approvals: 0 };
15
+ const te = byTool.get(t) ?? { tool: t, risk: c.tool?.risk ?? null, calls: 0, denied: 0 };
16
+ ae.calls++;
17
+ te.calls++;
18
+ if (c.decision?.final === "deny") {
19
+ ae.denied++;
20
+ te.denied++;
21
+ }
22
+ if (c.approval)
23
+ ae.approvals++;
24
+ byAgent.set(a, ae);
25
+ byTool.set(t, te);
26
+ }
27
+ const requested = new Map(recs.filter((r) => r.type === "approval.requested").map((r) => [r.approval.id, r]));
28
+ const decided = recs.filter((r) => r.type === "approval.decided");
29
+ const approvals = [...requested.values()].map((req) => {
30
+ const d = decided.find((x) => x.approval?.id === req.approval.id);
31
+ return {
32
+ id: req.approval.id,
33
+ tool: req.tool?.name ?? null,
34
+ agent: req.agent?.id ?? null,
35
+ principal: req.principal?.sub ?? null,
36
+ status: d?.approval?.status ?? "pending",
37
+ approvers: d?.approval?.approvers ?? [],
38
+ requested_at: req.ts,
39
+ decided_at: d?.ts ?? null,
40
+ wait_s: d ? Math.round((Date.parse(d.ts) - Date.parse(req.ts)) / 1000) : null,
41
+ };
42
+ });
43
+ const oldest = all[0]?.ts ?? null;
44
+ return {
45
+ generated_at: new Date().toISOString(),
46
+ period: { from: opts.from ?? recs[0]?.ts ?? null, to: opts.to ?? recs.at(-1)?.ts ?? null },
47
+ integrity,
48
+ retention: {
49
+ configured_days: opts.retentionDays ?? null,
50
+ oldest_record: oldest,
51
+ meets_ai_act_minimum: opts.retentionDays === undefined ? null : opts.retentionDays >= AI_ACT_MIN_RETENTION_DAYS,
52
+ },
53
+ totals: {
54
+ records: recs.length,
55
+ tool_calls: calls.length,
56
+ allowed: calls.filter((c) => c.decision?.final === "allow").length,
57
+ denied: calls.filter((c) => c.decision?.final === "deny").length,
58
+ pending: calls.filter((c) => c.decision?.final === "pending").length,
59
+ shadow_would_deny: calls.filter((c) => c.decision?.mode === "shadow" && (c.decision.effect === "deny" || c.decision.effect === "require_approval")).length,
60
+ },
61
+ by_agent: [...byAgent.values()].sort((a, b) => b.calls - a.calls),
62
+ by_tool: [...byTool.values()].sort((a, b) => b.calls - a.calls),
63
+ principals: new Set(calls.map((c) => c.principal?.sub)).size,
64
+ approvals,
65
+ denials: calls.filter((c) => c.decision?.final === "deny").slice(-100).map((c) => ({
66
+ ts: c.ts, agent: c.agent?.id ?? null, principal: c.principal?.sub ?? null, tool: c.tool?.name ?? null,
67
+ rules: c.decision?.rules ?? [], reasons: c.decision?.reasons ?? [],
68
+ })),
69
+ admin_events: recs.filter((r) => r.type.startsWith("policy.") || r.type.startsWith("revocation.") || r.type.startsWith("agent.registered") || r.type === "agent.updated")
70
+ .map((r) => ({ ts: r.ts, type: r.type, details: r.details })),
71
+ drift_events: recs.filter((r) => r.type === "tool.drift").map((r) => ({ ts: r.ts, details: r.details })),
72
+ };
73
+ }
74
+ export function reportToMarkdown(d, title = "Mandat — AI agent activity & oversight report") {
75
+ const L = [];
76
+ const row = (...c) => L.push("| " + c.map((x) => String(x ?? "—").replace(/\|/g, "\\|")).join(" | ") + " |");
77
+ L.push(`# ${title}`, "");
78
+ L.push(`Generated: ${d.generated_at} `, `Period: ${d.period.from ?? "—"} → ${d.period.to ?? "—"}`, "");
79
+ L.push("## 1. Log integrity (hash chain)", "");
80
+ L.push(d.integrity.ok
81
+ ? `**VERIFIED** — ${d.integrity.count} records, chain head \`${d.integrity.head}\`.`
82
+ : `**BROKEN** at record ${d.integrity.broken_at}: ${d.integrity.error}`);
83
+ L.push("", "## 2. Retention", "");
84
+ L.push(`Configured retention: ${d.retention.configured_days ?? "not configured"} days; oldest record: ${d.retention.oldest_record ?? "—"}.`);
85
+ if (d.retention.meets_ai_act_minimum !== null)
86
+ L.push(d.retention.meets_ai_act_minimum ? "Meets the ≥ 6 months log retention expectation (EU AI Act Art. 19/26)." : "**Below** the ≥ 6 months log retention expectation (EU AI Act Art. 19/26).");
87
+ L.push("", "## 3. Activity summary", "");
88
+ const t = d.totals;
89
+ L.push(`Tool calls: **${t.tool_calls}** (allowed ${t.allowed}, denied ${t.denied}, pending ${t.pending}); distinct principals: ${d.principals}.`);
90
+ if (t.shadow_would_deny)
91
+ L.push(`Shadow mode: ${t.shadow_would_deny} calls would have been blocked or escalated under enforcement.`);
92
+ L.push("", "| Agent | Calls | Denied | With approval |", "|---|---|---|---|");
93
+ for (const a of d.by_agent)
94
+ row(a.agent, a.calls, a.denied, a.approvals);
95
+ L.push("", "| Tool | Risk | Calls | Denied |", "|---|---|---|---|");
96
+ for (const x of d.by_tool)
97
+ row(x.tool, x.risk, x.calls, x.denied);
98
+ L.push("", "## 4. Human oversight (approvals)", "");
99
+ if (!d.approvals.length)
100
+ L.push("No approval requests in period.");
101
+ else {
102
+ L.push("| Approval | Tool | Agent | On behalf of | Status | Approvers | Requested | Wait (s) |", "|---|---|---|---|---|---|---|---|");
103
+ for (const a of d.approvals)
104
+ row(a.id, a.tool, a.agent, a.principal, a.status, a.approvers.join(", "), a.requested_at, a.wait_s);
105
+ }
106
+ L.push("", "## 5. Blocked actions", "");
107
+ if (!d.denials.length)
108
+ L.push("No denied calls in period.");
109
+ else {
110
+ L.push("| Time | Agent | On behalf of | Tool | Rules | Reason |", "|---|---|---|---|---|---|");
111
+ for (const x of d.denials)
112
+ row(x.ts, x.agent, x.principal, x.tool, x.rules.join(", "), x.reasons.join("; "));
113
+ }
114
+ L.push("", "## 6. Administrative changes (policies, revocations, agents)", "");
115
+ if (!d.admin_events.length)
116
+ L.push("None.");
117
+ else
118
+ for (const e of d.admin_events)
119
+ L.push(`- ${e.ts} — \`${e.type}\` ${JSON.stringify(e.details)}`);
120
+ L.push("", "## 7. Tool definition drift", "");
121
+ if (!d.drift_events.length)
122
+ L.push("None detected.");
123
+ else
124
+ for (const e of d.drift_events)
125
+ L.push(`- ${e.ts} — ${JSON.stringify(e.details)}`);
126
+ L.push("", "---", "_Technical evidence produced by Mandat. Classification of the AI system under the EU AI Act, GDPR, DORA, SOC 2 or ISO/IEC 42001 is the operator's responsibility._", "");
127
+ return L.join("\n");
128
+ }
@@ -0,0 +1,8 @@
1
+ import { Guard } from "../guard/guard.ts";
2
+ type ToolCallback = (...args: any[]) => unknown;
3
+ export interface McpServerLike {
4
+ registerTool?: (name: string, config: Record<string, unknown>, cb: ToolCallback) => unknown;
5
+ tool?: (name: string, ...rest: unknown[]) => unknown;
6
+ }
7
+ export declare function protect<S extends McpServerLike>(server: S, guard: Guard): S;
8
+ export {};
@@ -0,0 +1,68 @@
1
+ // Adapter for the official MCP TypeScript SDK (@modelcontextprotocol/sdk), duck-typed so Mandat
2
+ // does not depend on it.
3
+ //
4
+ // const guard = await createGuard({ ... });
5
+ // const server = protect(new McpServer({ name: "billing", version: "1.0.0" }), guard);
6
+ // server.registerTool("refund", { description, inputSchema }, handler); // now guarded
7
+ //
8
+ // // HTTP auth: app.use("/mcp", requireBearerAuth({ verifier: guard.sdkTokenVerifier({ InvalidTokenError }) }))
9
+ import { Guard, GuardDenied } from "../guard/guard.js";
10
+ import { deniedResult } from "./server.js";
11
+ export function protect(server, guard) {
12
+ const defs = [];
13
+ let scheduled = false;
14
+ const track = (def) => {
15
+ defs.push(def);
16
+ if (!scheduled) {
17
+ scheduled = true;
18
+ setImmediate(() => { scheduled = false; guard.registerTools(defs); });
19
+ }
20
+ };
21
+ const wrap = (name, cb) => async (...cbArgs) => {
22
+ // SDK calls cb(args, extra) for tools with an input schema and cb(extra) without one.
23
+ const extra = (cbArgs.length >= 2 ? cbArgs[1] : cbArgs[0]);
24
+ const args = (cbArgs.length >= 2 ? cbArgs[0] : {});
25
+ let auth = extra?.authInfo?.extra?.mandat;
26
+ try {
27
+ auth ??= await guard.verify(extra?.authInfo?.token);
28
+ }
29
+ catch (e) {
30
+ return { content: [{ type: "text", text: `Mandat: unauthenticated call (${e.message})` }], isError: true };
31
+ }
32
+ try {
33
+ return await guard.execute({ auth, tool: name, args, sessionId: extra?.sessionId ?? null }, () => cb(...cbArgs));
34
+ }
35
+ catch (e) {
36
+ if (e instanceof GuardDenied)
37
+ return deniedResult(e);
38
+ throw e;
39
+ }
40
+ };
41
+ if (typeof server.registerTool === "function") {
42
+ const orig = server.registerTool.bind(server);
43
+ server.registerTool = (name, config, cb) => {
44
+ track({ name, title: config.title, description: config.description, inputSchema: schemaFingerprint(config.inputSchema), annotations: config.annotations });
45
+ return orig(name, config, wrap(name, cb));
46
+ };
47
+ }
48
+ if (typeof server.tool === "function") {
49
+ const orig = server.tool.bind(server);
50
+ server.tool = (name, ...rest) => {
51
+ const cb = rest.pop();
52
+ const description = typeof rest[0] === "string" ? rest[0] : undefined;
53
+ track({ name, description, inputSchema: schemaFingerprint(rest.find((r) => r && typeof r === "object")) });
54
+ return orig(name, ...rest, wrap(name, cb));
55
+ };
56
+ }
57
+ return server;
58
+ }
59
+ /** Zod shapes are not JSON; pin their keys + each field's description/type name instead. */
60
+ function schemaFingerprint(schema) {
61
+ if (!schema || typeof schema !== "object")
62
+ return schema ?? null;
63
+ const out = {};
64
+ for (const [k, v] of Object.entries(schema)) {
65
+ out[k] = v && typeof v === "object" && "_def" in v ? { type: v._def?.typeName, description: v.description ?? null } : v;
66
+ }
67
+ return out;
68
+ }
@@ -0,0 +1,49 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import { Guard, GuardDenied, type VerifiedAuth } from "../guard/guard.ts";
3
+ import type { ToolDefinition } from "../guard/pinning.ts";
4
+ export declare const SUPPORTED_PROTOCOL_VERSIONS: string[];
5
+ export interface ToolContext {
6
+ auth: VerifiedAuth;
7
+ sessionId: string | null;
8
+ }
9
+ export interface CallToolResult {
10
+ content: Array<{
11
+ type: "text";
12
+ text: string;
13
+ } | Record<string, unknown>>;
14
+ structuredContent?: unknown;
15
+ isError?: boolean;
16
+ _meta?: Record<string, unknown>;
17
+ }
18
+ export interface ToolSpec extends ToolDefinition {
19
+ handler: (args: Record<string, unknown>, ctx: ToolContext) => unknown | Promise<unknown>;
20
+ }
21
+ export interface McpServerOptions {
22
+ name: string;
23
+ version: string;
24
+ guard: Guard;
25
+ tools: ToolSpec[];
26
+ instructions?: string;
27
+ /** Allowed browser origins. Requests with any other Origin header are rejected (403). */
28
+ allowedOrigins?: string[];
29
+ /** Path of the MCP endpoint. Default "/mcp". */
30
+ path?: string;
31
+ }
32
+ export declare class McpHttpServer {
33
+ readonly opts: McpServerOptions;
34
+ readonly path: string;
35
+ private tools;
36
+ private sessions;
37
+ server: Server | null;
38
+ constructor(opts: McpServerOptions);
39
+ private get prmUrl();
40
+ handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
41
+ private dispatch;
42
+ /** Binds to loopback by default; pass host "0.0.0.0" only behind a TLS-terminating proxy. */
43
+ listen(port: number, host?: string): Promise<Server>;
44
+ close(): Promise<void>;
45
+ }
46
+ /** MCP tool result shown to the model when Mandat blocks a call. */
47
+ export declare function deniedResult(e: GuardDenied): CallToolResult;
48
+ /** Small JSON Schema subset check: object, required, primitive types, enum, minimum/maximum. */
49
+ export declare function validateArgs(schema: unknown, args: unknown): string | null;
@@ -0,0 +1,211 @@
1
+ // Minimal MCP server (Streamable HTTP transport, JSON responses) with Mandat Guard on every tools/call.
2
+ // Implements what an authorization-aware MCP server must do:
3
+ // - 401 + `WWW-Authenticate: Bearer resource_metadata=...` for missing/invalid tokens (incl. on tools/list)
4
+ // - RFC 9728 Protected Resource Metadata at /.well-known/oauth-protected-resource[/path]
5
+ // - audience-bound tokens only; the inbound token is never forwarded downstream
6
+ // - Origin validation (DNS rebinding), loopback bind by default
7
+ import { createServer } from "node:http";
8
+ import { AuthError, Guard, GuardDenied } from "../guard/guard.js";
9
+ import { bearerToken, randomId, readBody, sendJson } from "../util.js";
10
+ export const SUPPORTED_PROTOCOL_VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"];
11
+ export class McpHttpServer {
12
+ opts;
13
+ path;
14
+ tools;
15
+ sessions = new Set();
16
+ server = null;
17
+ constructor(opts) {
18
+ this.opts = opts;
19
+ this.path = opts.path ?? "/mcp";
20
+ this.tools = new Map(opts.tools.map((t) => [t.name, t]));
21
+ opts.guard.registerTools(opts.tools.map(({ handler: _h, ...def }) => def));
22
+ }
23
+ get prmUrl() {
24
+ const r = new URL(this.opts.guard.opts.resource);
25
+ return `${r.origin}/.well-known/oauth-protected-resource${r.pathname === "/" ? "" : r.pathname}`;
26
+ }
27
+ handler = async (req, res) => {
28
+ try {
29
+ const url = new URL(req.url ?? "/", "http://localhost");
30
+ if (req.method === "GET" && url.pathname.startsWith("/.well-known/oauth-protected-resource")) {
31
+ return sendJson(res, 200, this.opts.guard.protectedResourceMetadata({ resource_name: this.opts.name }));
32
+ }
33
+ if (url.pathname !== this.path)
34
+ return sendJson(res, 404, { error: "not_found" });
35
+ const origin = req.headers.origin;
36
+ if (origin && !(this.opts.allowedOrigins ?? []).includes(origin))
37
+ return sendJson(res, 403, { error: "forbidden_origin" });
38
+ // Authenticate before anything else: tools/list is protected too.
39
+ let auth;
40
+ try {
41
+ auth = await this.opts.guard.verify(bearerToken(req));
42
+ }
43
+ catch (e) {
44
+ const err = e instanceof AuthError ? e : new AuthError("invalid_token", "Unauthorized");
45
+ const hadToken = Boolean(bearerToken(req));
46
+ const challenge = `Bearer resource_metadata="${this.prmUrl}"` + (hadToken ? `, error="${err.code}", error_description="${headerSafe(err.message)}"` : "");
47
+ return sendJson(res, err.status, { error: err.code, error_description: err.message }, { "www-authenticate": challenge });
48
+ }
49
+ if (req.method === "DELETE") {
50
+ const sid = req.headers["mcp-session-id"];
51
+ if (typeof sid === "string")
52
+ this.sessions.delete(sid);
53
+ res.writeHead(204).end();
54
+ return;
55
+ }
56
+ if (req.method !== "POST")
57
+ return sendJson(res, 405, { error: "method_not_allowed" }, { allow: "POST, DELETE" });
58
+ let body;
59
+ try {
60
+ body = JSON.parse(await readBody(req));
61
+ }
62
+ catch {
63
+ return sendJson(res, 400, rpcError(null, -32700, "Parse error"));
64
+ }
65
+ const sessionHeader = req.headers["mcp-session-id"];
66
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader : null;
67
+ const batch = Array.isArray(body) ? body : [body];
68
+ const headers = {};
69
+ const out = [];
70
+ for (const msg of batch) {
71
+ if (msg?.method === "initialize") {
72
+ sessionId = randomId("mcp_");
73
+ this.sessions.add(sessionId);
74
+ headers["mcp-session-id"] = sessionId;
75
+ }
76
+ const r = await this.dispatch(msg, auth, sessionId);
77
+ if (r !== undefined)
78
+ out.push(r);
79
+ }
80
+ if (!out.length) {
81
+ res.writeHead(202, headers).end();
82
+ return;
83
+ }
84
+ return sendJson(res, 200, Array.isArray(body) ? out : out[0], headers);
85
+ }
86
+ catch (e) {
87
+ return sendJson(res, 500, rpcError(null, -32603, `Internal error: ${e.message}`));
88
+ }
89
+ };
90
+ async dispatch(msg, auth, sessionId) {
91
+ if (!msg || msg.jsonrpc !== "2.0" || typeof msg.method !== "string")
92
+ return rpcError(msg?.id ?? null, -32600, "Invalid Request");
93
+ const isNotification = msg.id === undefined;
94
+ if (isNotification)
95
+ return undefined;
96
+ const id = msg.id ?? null;
97
+ switch (msg.method) {
98
+ case "initialize": {
99
+ const requested = String(msg.params?.protocolVersion ?? "");
100
+ return rpcResult(id, {
101
+ protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0],
102
+ capabilities: { tools: { listChanged: false } },
103
+ serverInfo: { name: this.opts.name, version: this.opts.version },
104
+ ...(this.opts.instructions ? { instructions: this.opts.instructions } : {}),
105
+ });
106
+ }
107
+ case "ping":
108
+ return rpcResult(id, {});
109
+ case "tools/list":
110
+ return rpcResult(id, { tools: [...this.tools.values()].map(({ handler: _h, ...def }) => def) });
111
+ case "tools/call": {
112
+ const name = String(msg.params?.name ?? "");
113
+ const args = (msg.params?.arguments ?? {});
114
+ const tool = this.tools.get(name);
115
+ if (!tool)
116
+ return rpcError(id, -32602, `Unknown tool: ${name}`);
117
+ const invalid = validateArgs(tool.inputSchema, args);
118
+ if (invalid)
119
+ return rpcResult(id, { content: [{ type: "text", text: `Invalid arguments: ${invalid}` }], isError: true });
120
+ try {
121
+ const result = await this.opts.guard.execute({ auth, tool: name, args, sessionId }, () => tool.handler(args, { auth, sessionId }));
122
+ return rpcResult(id, normalizeResult(result));
123
+ }
124
+ catch (e) {
125
+ if (e instanceof GuardDenied)
126
+ return rpcResult(id, deniedResult(e));
127
+ return rpcResult(id, { content: [{ type: "text", text: `Tool error: ${e.message}` }], isError: true });
128
+ }
129
+ }
130
+ default:
131
+ return rpcError(id, -32601, `Method not found: ${msg.method}`);
132
+ }
133
+ }
134
+ /** Binds to loopback by default; pass host "0.0.0.0" only behind a TLS-terminating proxy. */
135
+ listen(port, host = "127.0.0.1") {
136
+ this.server = createServer(this.handler);
137
+ return new Promise((resolve) => this.server.listen(port, host, () => resolve(this.server)));
138
+ }
139
+ close() {
140
+ return new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve()));
141
+ }
142
+ }
143
+ /** MCP tool result shown to the model when Mandat blocks a call. */
144
+ export function deniedResult(e) {
145
+ const text = e.code === "approval_pending"
146
+ ? `Mandat: this action needs human approval. ${e.message}`
147
+ : `Mandat blocked this action: ${e.message}`;
148
+ return {
149
+ content: [{ type: "text", text }],
150
+ isError: true,
151
+ _meta: {
152
+ "mandat/decision": {
153
+ code: e.code,
154
+ effect: e.decision?.effect ?? "deny",
155
+ rules: e.decision?.matched ?? [],
156
+ approval_id: e.approvalId ?? null,
157
+ record_id: e.record ? e.record.id : null,
158
+ },
159
+ },
160
+ };
161
+ }
162
+ function normalizeResult(r) {
163
+ if (typeof r === "string")
164
+ return { content: [{ type: "text", text: r }] };
165
+ if (r && typeof r === "object" && Array.isArray(r.content))
166
+ return r;
167
+ // MCP requires structuredContent to be a JSON object, so arrays and primitives are sent as text only.
168
+ const isObject = r !== null && typeof r === "object" && !Array.isArray(r);
169
+ return { content: [{ type: "text", text: JSON.stringify(r) }], ...(isObject ? { structuredContent: r } : {}) };
170
+ }
171
+ /** Header values must be visible ASCII; quotes would break the auth-param syntax. */
172
+ function headerSafe(s) {
173
+ return s.replace(/[\u2013\u2014]/g, "-").replace(/[^\x20-\x7e]/g, "").replace(/["\\]/g, "'").slice(0, 300);
174
+ }
175
+ function rpcResult(id, result) { return { jsonrpc: "2.0", id, result }; }
176
+ function rpcError(id, code, message) { return { jsonrpc: "2.0", id, error: { code, message } }; }
177
+ /** Small JSON Schema subset check: object, required, primitive types, enum, minimum/maximum. */
178
+ export function validateArgs(schema, args) {
179
+ const s = schema;
180
+ if (!s || s.type !== "object")
181
+ return null;
182
+ if (!args || typeof args !== "object" || Array.isArray(args))
183
+ return "arguments must be an object";
184
+ const a = args;
185
+ for (const k of s.required ?? [])
186
+ if (a[k] === undefined)
187
+ return `missing required '${k}'`;
188
+ for (const [k, v] of Object.entries(a)) {
189
+ const p = s.properties?.[k];
190
+ if (!p) {
191
+ if (s.additionalProperties === false)
192
+ return `unexpected property '${k}'`;
193
+ continue;
194
+ }
195
+ const t = p.type;
196
+ const ok = !t
197
+ || (t === "integer" ? Number.isInteger(v) : t === "number" ? typeof v === "number" && Number.isFinite(v)
198
+ : t === "array" ? Array.isArray(v) : t === "object" ? v !== null && typeof v === "object" && !Array.isArray(v) : typeof v === t);
199
+ if (!ok)
200
+ return `'${k}' must be ${t}`;
201
+ if (p.enum && !p.enum.includes(v))
202
+ return `'${k}' must be one of ${JSON.stringify(p.enum)}`;
203
+ if (typeof v === "number" && p.minimum !== undefined && v < p.minimum)
204
+ return `'${k}' must be >= ${p.minimum}`;
205
+ if (typeof v === "number" && p.maximum !== undefined && v > p.maximum)
206
+ return `'${k}' must be <= ${p.maximum}`;
207
+ if (t === "array" && p.items?.type === "string" && v.some((x) => typeof x !== "string"))
208
+ return `'${k}' must be an array of strings`;
209
+ }
210
+ return null;
211
+ }
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ export interface OidcMetadata {
2
+ issuer: string;
3
+ authorization_endpoint: string;
4
+ token_endpoint: string;
5
+ jwks_uri: string;
6
+ end_session_endpoint?: string;
7
+ code_challenge_methods_supported?: string[];
8
+ }
9
+ export interface Session {
10
+ issuer: string;
11
+ client_id: string;
12
+ id_token: string;
13
+ refresh_token?: string;
14
+ /** ID token expiry (unix seconds). */
15
+ expires_at: number;
16
+ user: {
17
+ sub: string;
18
+ email?: string;
19
+ name?: string;
20
+ };
21
+ created_at: string;
22
+ }
23
+ export interface LoginOptions {
24
+ issuer: string;
25
+ clientId: string;
26
+ /** Loopback port registered as callback in the IdP: http://127.0.0.1:<port>/callback */
27
+ port?: number;
28
+ scopes?: string[];
29
+ /** Extra authorize parameters (e.g. { organization: "org_123" } for Auth0 Organizations). */
30
+ extraParams?: Record<string, string>;
31
+ /** How to show the login URL. Default: open the system browser. */
32
+ openBrowser?: (url: string) => Promise<void> | void;
33
+ timeoutMs?: number;
34
+ }
35
+ export declare class OidcError extends Error {
36
+ }
37
+ export declare function discover(issuer: string): Promise<OidcMetadata>;
38
+ export declare function pkcePair(): {
39
+ verifier: string;
40
+ challenge: string;
41
+ };
42
+ /** Interactive browser login. Resolves with a verified session. */
43
+ export declare function login(o: LoginOptions): Promise<Session>;
44
+ /** Uses the refresh token to obtain a fresh ID token. */
45
+ export declare function refreshSession(s: Session): Promise<Session>;
46
+ export declare function sessionPath(): string;
47
+ export declare function saveSession(s: Session): void;
48
+ export declare function loadSession(): Session | null;
49
+ export declare function clearSession(): boolean;
50
+ /** Returns a valid ID token from the cached session, refreshing (and re-saving) it when it is about to expire. */
51
+ export declare function currentIdToken(minValiditySec?: number): Promise<string>;
52
+ export declare function openSystemBrowser(url: string): void;