mandat 0.1.0 → 0.1.1

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
@@ -1,293 +1,320 @@
1
- # Mandat
2
-
3
- **Authorization, delegation and audit for AI agent actions — MCP first.**
4
-
5
- Mandat answers three questions about every tool call an AI agent makes:
6
-
7
- 1. **May it?** A policy is checked on *every* call, including its arguments (`refund ≤ €50 → auto · €50–500 → ask a human · > €500 → deny`).
8
- 2. **On whose behalf?** Agents get short-lived, single-task tokens that carry the whole delegation chain: `human → agent → sub-agent` (RFC 8693 `act` and RFC 9396 `authorization_details`).
9
- 3. **What happened?** One tamper-evident Action Record per call (hash chain), exportable to a SIEM (OCSF, OpenTelemetry), with a DPO/auditor report.
10
-
11
- It also ships a **scanner** that checks MCP servers and client configs for the auth and supply-chain mistakes found in most public MCP servers.
12
-
13
- This repo is the **MVP** (PRD phase 0–3 months, plus the core of delegation from phase 3–6). The spec it implements is in [`specs/rpd.md`](specs/rpd.md).
14
-
15
- > Zero runtime dependencies. The npm package ships compiled JavaScript (Node ≥ 20). For development, Node ≥ 23.6 runs the TypeScript sources directly.
16
-
17
- ---
18
-
19
- ## 60-second demo
20
-
21
- ```bash
22
- node examples/demo.ts # full scenario, then exit
23
- node examples/demo.ts --keep # …and keep the console running at the printed URL
24
- ```
25
-
26
- The demo starts a control plane and a protected "Acme Support" MCP server, then plays out this story:
27
-
28
- | Step | What happens | Mandat feature |
29
- |---|---|---|
30
- | Scan | `mandat scan` finds the protected server clean; an anonymous request gets `401` + `resource_metadata` | Scanner, PRM (RFC 9728) |
31
- | Delegate | Maria signs in. `support-bot` exchanges her token for a 5-minute token that covers only 4 tools | STS, RFC 8693 + RAR |
32
- | €20 refund | Allowed automatically | PDP on arguments |
33
- | €120 refund | The agent waits while "Alice" approves, then the call runs | Human approval bound to this exact call |
34
- | €900 refund | Denied by the `refund-limit` rule | Deny overrides |
35
- | `delete_customer` | Denied: the tool is outside the task's delegated capability | Capability in token |
36
- | Prompt injection | After `read_inbox`, e-mail to `archive@exfil.test` is blocked; internal mail still works | Session taint ("lethal trifecta") |
37
- | Sub-agent | `billing-bot` receives a narrower mandate (refund ≤ €30) with a nested `act` chain | Delegation can only narrow |
38
- | Kill switch | `support-bot` and every token it delegated stop working in < 1 s; new tokens are refused | Revocation |
39
- | Audit | The chain verifies. Editing one past record ("€900" → "€9") is detected | Hash-chained ledger |
40
-
41
- ---
42
-
43
- ## Quick start (your own setup)
44
-
45
- ```bash
46
- mandat init # config, starter policy + tests, keys (.mandat/credentials.json)
47
- mandat policy test # 7/7 starter decision tests
48
- mandat serve # control plane + console on http://127.0.0.1:7400/console
49
-
50
- mandat agents add support-bot --tools "lookup_*,refund,send_email,read_inbox" \
51
- --resources http://127.0.0.1:7401/mcp --versions 1.4.0 # prints the client secret once
52
- node examples/refund-server/server.ts # protected MCP server on :7401
53
- ```
54
-
55
- (`mandat` is `node bin/mandat.ts`. Run `npm link` once to get the short name.)
56
-
57
- Then, as an agent:
58
-
59
- ```bash
60
- TOKEN=$(mandat token --agent support-bot --secret <secret> --user user:maria --resource http://127.0.0.1:7401/mcp --version 1.4.0)
61
- curl -s http://127.0.0.1:7401/mcp -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
62
- -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"refund","arguments":{"order_id":"A-1002","amount":150,"currency":"EUR"}}}'
63
- mandat approvals list # in another terminal
64
- mandat approvals approve apr_… # the waiting call completes
65
- mandat revoke --agent support-bot --reason "incident 42"
66
- mandat ledger verify && mandat ledger report --retention 365
67
- ```
68
-
69
- ### Protecting your MCP server
70
-
71
- With the official TypeScript SDK:
72
-
73
- ```ts
74
- import { createGuard, protect } from "mandat";
75
-
76
- const guard = await createGuard({
77
- resource: "https://mcp.example.com/mcp", // token audience
78
- controlPlane: process.env.MANDAT_URL!,
79
- apiKey: process.env.MANDAT_SERVICE_KEY!, // role: service
80
- pinning: { lockfile: "mandat.lock.json", mode: "block" },
81
- });
82
- const server = protect(new McpServer({ name: "billing", version: "1.0.0" }), guard); // every registerTool is guarded
83
- app.get("/.well-known/oauth-protected-resource/mcp", (_q, r) => r.json(guard.protectedResourceMetadata()));
84
- app.use("/mcp", requireBearerAuth({ verifier: guard.sdkTokenVerifier({ InvalidTokenError }) }));
85
- ```
86
-
87
- Without dependencies, use the built-in server: `new McpHttpServer({ name, version, guard, tools }).listen(7401)` (see [`examples/refund-server`](examples/refund-server)).
88
-
89
- On the agent side, use `exchangeToken()` and `McpHttpClient` from `mandat`.
90
-
91
- ---
92
-
93
- ## Connecting real agents (Claude Code, Codex, Cursor, Claude Desktop)
94
-
95
- These clients start a browser login when an MCP server answers `401`. Mandat's control plane only does token exchange, not that login flow, so connect them through **`mandat bridge`**. The bridge is a local stdio MCP server: it acts as a registered agent, exchanges the user's identity for 5-minute task tokens, and gets a new one before the old one expires.
96
-
97
- ```bash
98
- mandat agents add claude-code --tools "lookup_*,refund,read_inbox,send_email,delete_*" --resources http://127.0.0.1:7401/mcp
99
- # → copy the client_secret
100
- ```
101
-
102
- **Claude Code**
103
-
104
- ```bash
105
- claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
106
- node D:/Projects/Mandat1/bin/mandat.ts bridge --url http://127.0.0.1:7401/mcp \
107
- --mandat http://127.0.0.1:7400 --agent claude-code --user user:maria --email maria@acme.example
108
- ```
109
-
110
- Equivalent `.mcp.json`:
111
-
112
- ```json
113
- { "mcpServers": { "acme": { "command": "node",
114
- "args": ["D:/Projects/Mandat1/bin/mandat.ts", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
115
- "--agent", "claude-code", "--user", "user:maria", "--email", "maria@acme.example"],
116
- "env": { "MANDAT_AGENT_SECRET": "<secret>" } } } }
117
- ```
118
-
119
- **Codex** (`~/.codex/config.toml`)
120
-
121
- ```toml
122
- [mcp_servers.acme]
123
- command = "node"
124
- args = ["D:/Projects/Mandat1/bin/mandat.ts", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
125
- "--agent", "codex", "--user", "user:maria", "--email", "maria@acme.example"]
126
- env = { MANDAT_AGENT_SECRET = "<secret>" }
127
-
128
- # Codex has its own approval gate for MCP tools that aren't read-only. Pass these tools through
129
- # so that Mandat's policy decides (allow / deny / human approval):
130
- [mcp_servers.acme.tools.refund]
131
- approval_mode = "approve"
132
- [mcp_servers.acme.tools.send_email]
133
- approval_mode = "approve"
134
- [mcp_servers.acme.tools.read_inbox]
135
- approval_mode = "approve"
136
- [mcp_servers.acme.tools.delete_customer]
137
- approval_mode = "approve"
138
- ```
139
-
140
- **Notes**
141
-
142
- - **Approvals.** A call that needs approval blocks for up to `approvalWaitMs` (15 s in the example server) while a human approves in the console, Slack or `mandat approvals approve <id>`. If nobody answers in time, the agent gets "approval required (request apr_…). Retry the same call once it is approved", and the approval is honoured when the agent retries the identical call.
143
- - **Real users.** `--user` uses the dev IdP. With a real IdP, put the user's token in `MANDAT_SUBJECT_TOKEN` and configure `trustedIssuers`.
144
- - **Narrower tasks.** Add `--tools a,b` to give a session less than everything the agent is allowed.
145
- - **Tested with:** Claude Code 2.1.302 and codex-cli 0.166.0. Both attributed every call in the ledger; Mandat denied over-limit refunds, blocked exfiltration after a prompt injection, and held mid-size refunds and deletes for human approval.
146
-
147
- ---
148
-
149
- ## Real users with Auth0 (or any OIDC provider)
150
-
151
- By default, `mandat init` turns on a dev IdP: anyone can claim to be any user. To have agents act for **real, signed-in people**, connect your identity provider. Auth0 is shown here; Okta, Entra ID and Keycloak work the same way, because Mandat only relies on standard OIDC discovery, JWKS and PKCE.
152
-
153
- **1. Create an Auth0 application** (Dashboard → Applications → *Create Application*)
154
-
155
- - **Type:** *Native*. It's a CLI, so there's no client secret; PKCE protects the login instead.
156
- - **Settings → Allowed Callback URLs:** `http://127.0.0.1:8765/callback`
157
- - **Settings → Advanced → Grant Types:** *Authorization Code* and *Refresh Token* (both on by default for Native apps).
158
- - Copy the **Domain** and **Client ID**. You need at least one user (User Management → Users) or a social connection.
159
-
160
- **2. Trust it on the control plane**, then restart `mandat serve`:
161
-
162
- ```bash
163
- mandat idp add --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID --disable-dev-idp
164
- # Auth0 Organizations: add --tenant-claim org_id
165
- ```
166
-
167
- **3. Sign in once** (this opens your browser):
168
-
169
- ```bash
170
- mandat login --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID
171
- mandat login status
172
- ```
173
-
174
- The session is stored in `~/.mandat/session.json` (mode 0600) and refreshed automatically when Auth0 issues a refresh token. `login status` tells you whether it did.
175
-
176
- **4. Let your agent act for you:** in the bridge command, replace `--user …` with `--login`:
177
-
178
- ```bash
179
- claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
180
- node D:/Projects/Mandat1/bin/mandat.ts bridge --url http://127.0.0.1:7401/mcp --mandat http://127.0.0.1:7400 --agent claude-code --login
181
- ```
182
-
183
- Every call is now attributed to the Auth0 user, for example `principal.sub = "auth0|…"`, with their e-mail and `org_id` as tenant. That identity is what policies, approvals and the ledger see. The STS accepts only ID tokens issued by the trusted tenant **to that client ID**, so tokens issued to your other Auth0 apps are rejected.
184
-
185
- ---
186
-
187
- ## Architecture
188
-
189
- ```
190
- Human (IdP: Okta/Entra/Auth0/Keycloak via JWKS; dev IdP for local use)
191
- │ ID / access token
192
- ▼
193
- Agent ──RFC 8693 (sub=user, act=agent) + RAR──▶ Mandat STS ──▶ 5-min task token (aud = one MCP server)
194
- │
195
- ▼ MCP (Streamable HTTP)
196
- MCP server + Mandat Guard (PEP + in-process PDP) ◀── policy (ETag poll, offline snapshot) ── Control plane
197
- │ allow / deny / require_approval ───────── approvals API ──▶ Slack · webhook · console · CLI
198
- │ revocations (2 s poll) ◀──────────────────────────────────── kill switch
199
- │ Action Records (async, batched, at-least-once, deduped) ──▶ hash-chained ledger ──▶ OCSF / OTLP
200
- ▼
201
- Downstream services (the user's token is never forwarded)
202
- ```
203
-
204
- | Path | What lives there |
205
- |---|---|
206
- | `src/policy/` | Expression language (CEL subset, no `eval`) and the PDP (deny-overrides, fail-closed on errors) |
207
- | `src/sts/` | JWT/JWKS (ES256/RS256/PS256/EdDSA, no `none`/HMAC), token exchange, revocation model |
208
- | `src/guard/` | Guard (PEP), tool pinning, remote clients for the control plane |
209
- | `src/mcp/` | Zero-dep MCP HTTP server with Guard, and the `protect()` adapter for the official SDK |
210
- | `src/approvals/` | Approval service, Slack (Block Kit + signed interactions), signed webhooks |
211
- | `src/ledger/` | Hash chain, PII redaction, OCSF/OTel export, OTLP exporter, compliance report |
212
- | `src/scan/` | Remote scanner and config/source scanner; text/JSON/SARIF/HTML output |
213
- | `src/controlplane/` | HTTP control plane and web console |
214
- | `src/cli/` | `mandat` CLI |
215
-
216
- ### Decision semantics
217
-
218
- - **Deny overrides.** Any matching `deny` wins. Otherwise any `require_approval` wins. Otherwise `allow` (obligations are merged). Otherwise the policy `default` applies, which is `deny`. Rule order doesn't matter.
219
- - **Errors fail closed.** If a condition can't be evaluated (type error, missing data), it counts as a match for `deny`/`require_approval` rules and as no match for `allow` rules.
220
- - **Capability first.** A call outside the token's `authorization_details` (tool, location, argument limits) is denied before any rule runs.
221
- - **Taint.** A tool marked `taints: true` (e-mail, web, tickets) marks the session. Rules can then check `session.tainted`.
222
- - **Approvals.** Each approval is bound to `sha256(user, agent, tool, server, args)` and can be used once. Self-approval is refused, `approvers: 2` means four-eyes, and a timeout means deny.
223
- - **Fail modes.** If revocations can't be refreshed for 15 s, `financial`/`destructive` tools fail closed. Policy keeps working from the last snapshot.
224
- - **Shadow mode** (`mode: "shadow"`) records the decision but never blocks. Use it to roll out new policies.
225
-
226
- ### Policy language
227
-
228
- ```jsonc
229
- {
230
- "version": 1,
231
- "default": "deny",
232
- "tools": { "refund": { "risk": "financial" }, "read_inbox": { "risk": "read", "taints": true },
233
- "send_email": { "risk": "external_comm", "redact": ["body"] } },
234
- "rules": [
235
- { "id": "refund-approval", "tool": "refund", "when": "args.amount > 50 && args.amount <= 500",
236
- "effect": "require_approval", "approval": { "approvers": 1, "timeout": "15m", "channels": ["slack"] } },
237
- { "id": "no-exfil", "tool": "send_email",
238
- "when": "session.tainted && !args.to.all(r, r.endsWith('@example.com'))", "effect": "deny" }
239
- ]
240
- }
241
- ```
242
-
243
- - **Context:** `principal.{sub,tenant,email,scope}`, `agent.{id,version,prompt_hash}`, `actor_chain[]`, `tool.{name,server,risk}`, `args.*`, `session.{tainted,taint_sources,calls}`, `task.{id,authorization_details}`, `env.{hour_utc,weekday_utc}`.
244
- - **Operators:** `== != < <= > >= in && || ! ?: + - * / %`.
245
- - **Functions:** `size has int double string lower upper abs min max`.
246
- - **Methods:** `startsWith endsWith contains matches size lower upper trim keys`.
247
- - **Macros:** `all exists filter`.
248
- - **Effects:** `allow`, `deny`, `require_approval`, `allow_with_obligations` (obligations: `redact` fields, `annotate` tags).
249
-
250
- Tooling: `mandat policy check|test|eval` and `mandat bench`. On this machine the PDP measures p50 ≈ 14 µs and p99 ≈ 70 µs (the PRD targets are 0.5 ms and 5 ms).
251
-
252
- ---
253
-
254
- ## PRD coverage
255
-
256
- | PRD item | MVP status |
257
- |---|---|
258
- | **US-1** `mandat scan <url>`: auth on `tools/list`, invalid token, PRM, PKCE S256/`plain`, DCR vs CIMD, `iss` (RFC 9207), CORS, transport, tool poisoning, opt-in redirect-URI probe (`--active`); fixes include code | ✅ |
259
- | Static scan of client configs (unpinned `npx`/`uvx`, known-malicious versions, typosquats, shell/stdio commands, `curl\|sh`, plaintext secrets, static bearer tokens, `0.0.0.0`, broad filesystem roots, privileged Docker) and server source (eval, shell exec, token passthrough); JSON/SARIF/HTML output; GitHub Action | ✅ |
260
- | **US-2** `protect(server)` for the TS SDK | ✅ (duck-typed adapter, tested against an SDK-shaped fake; not yet run against the real SDK or MCP Inspector) · Python ❌ |
261
- | **US-3** Argument policies with p99 < 5 ms; approval in Slack with context | ✅ (Slack: Block Kit message + signed interactivity endpoint `/slack/interactions`) |
262
- | **US-4** Single-task token via RFC 8693 with `sub` = user, `act` = agent, RAR, 5 min | ✅ for Mandat-protected MCP servers · downstream tokens for Stripe/CRM ❌ |
263
- | **US-5** ID-JAG / Okta XAA | ❌ |
264
- | Real IdP users (PRD Must: Auth0, Okta, Entra, Keycloak) | ✅ OIDC login with PKCE (`mandat login`), `mandat idp add`, ID-token exchange. Covered by tests against an Auth0-like fake IdP |
265
- | **US-6** OCSF event with the delegation chain | ✅ export via `/api/ledger/export`; OTLP push of spans (`ledger.otlp`) · direct SIEM connectors (Splunk HEC and others) ❌ |
266
- | **US-7** Revocation by agent, version, user, task, tenant or token in ≤ 10 s | ✅ < 1 s in tests; issuance blocked until lifted |
267
- | **US-8** DPO report from the hash chain, retention check | ✅ `mandat ledger report`, console |
268
- | **US-9** Tool description/schema drift | ✅ server-side lockfile (warn/block) and client-side `mandat pin --check` |
269
- | Attribution model, local ledger, shadow mode, taint, policy tests | ✅ |
270
- | Control plane: agents registry, roles (admin / approver / auditor / service), policy change log, console | ✅ |
271
- | Cloud Free, hosted multi-tenant ledger, CIBA, Teams, Transaction Tokens, SPIFFE, Gateway, other language SDKs | ❌ out of MVP scope |
272
-
273
- ## Security notes and known limitations
274
-
275
- - **Dev IdP.** `devIdp: true` (the `mandat init` default) lets anyone mint user tokens on `/dev/login`. Disable it with `mandat idp add … --disable-dev-idp` before any real use.
276
- - **Approver identity.** Approvers still authenticate with API keys (console/CLI) or Slack, not through the IdP, so self-approval is only detected when the approver id matches the user's `sub` or e-mail.
277
- - **Storage.** The control plane keeps state in JSON files under `dataDir` (single process, no HA). The `JsonCollection` interface is the seam for a database.
278
- - **Ledger.** The ledger is tamper-*evident*, not tamper-*proof*: someone with write access could rewrite the whole chain. For that threat, anchor the head hash externally (WORM storage, a transparency log, or an eIDAS timestamp; see open question 8). Records are ordered by `seq`, which is arrival order; `ts` is event time.
279
- - **Auth failures** (bad or revoked token → `401`) are returned to the caller but not yet written to the ledger.
280
- - **Slack identity.** Slack approvers are recorded as `slack:<username>`. They are not yet mapped to IdP identities, so the self-approval check covers only the API, console and CLI.
281
- - **MCP server scope.** The built-in MCP server implements the JSON response mode of Streamable HTTP (no SSE stream, no server→client requests).
282
- - **OWASP mappings.** Mappings to OWASP Agentic (ASI) and MCP Top 10 are best effort.
283
-
284
- ## Development
285
-
286
- ```bash
287
- npm test # 46 tests: expression language, PDP, STS, guard, approvals, ledger, scanner, end-to-end over HTTP
288
- npm run typecheck # tsc --strict (dev dependency only)
289
- npm run build # dist/ (plain JS + .d.ts) for the npm package; Node >= 20
290
- npm run demo
291
- ```
292
-
293
- License: Apache-2.0.
1
+ # Mandat
2
+
3
+ **Authorization, delegation and audit for AI agent actions — MCP first.**
4
+
5
+ Mandat answers three questions about every tool call an AI agent makes:
6
+
7
+ 1. **May it?** A policy is checked on *every* call, including its arguments (`refund ≤ €50 → auto · €50–500 → ask a human · > €500 → deny`).
8
+ 2. **On whose behalf?** Agents get short-lived, single-task tokens that carry the whole delegation chain: `human → agent → sub-agent` (RFC 8693 `act` and RFC 9396 `authorization_details`).
9
+ 3. **What happened?** One tamper-evident Action Record per call (hash chain), exportable to a SIEM (OCSF, OpenTelemetry), with a DPO/auditor report.
10
+
11
+ It also ships a **scanner** that checks MCP servers and client configs for the auth and supply-chain mistakes found in most public MCP servers.
12
+
13
+ This is the **MVP** (PRD phase 0–3 months, plus the core of delegation from phase 3–6). The spec it implements is in [`specs/rpd.md`](specs/rpd.md).
14
+
15
+ [![ci](https://github.com/vosidov-msaid/Mandat/actions/workflows/ci.yml/badge.svg)](https://github.com/vosidov-msaid/Mandat/actions/workflows/ci.yml)
16
+ [![npm](https://img.shields.io/npm/v/mandat)](https://www.npmjs.com/package/mandat)
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install -g mandat # the `mandat` CLI (control plane, scanner, bridge for agents)
22
+ npm install mandat # the library, inside your MCP server or agent project
23
+ npx mandat scan <url> # or run any command without installing
24
+ ```
25
+
26
+ Requires Node ≥ 20. Zero runtime dependencies and no install scripts.
27
+
28
+ ---
29
+
30
+ ## 60-second demo
31
+
32
+ The demo and the example MCP server live in the repository, not in the npm package:
33
+
34
+ ```bash
35
+ git clone https://github.com/vosidov-msaid/Mandat.git && cd Mandat
36
+ node examples/demo.ts # full scenario, then exit (Node ≥ 23.6; no npm install needed)
37
+ node examples/demo.ts --keep # …and keep the console running at the printed URL
38
+ ```
39
+
40
+ The demo starts a control plane and a protected "Acme Support" MCP server, then plays out this story:
41
+
42
+ | Step | What happens | Mandat feature |
43
+ |---|---|---|
44
+ | Scan | `mandat scan` finds the protected server clean; an anonymous request gets `401` + `resource_metadata` | Scanner, PRM (RFC 9728) |
45
+ | Delegate | Maria signs in. `support-bot` exchanges her token for a 5-minute token that covers only 4 tools | STS, RFC 8693 + RAR |
46
+ | €20 refund | Allowed automatically | PDP on arguments |
47
+ | €120 refund | The agent waits while "Alice" approves, then the call runs | Human approval bound to this exact call |
48
+ | €900 refund | Denied by the `refund-limit` rule | Deny overrides |
49
+ | `delete_customer` | Denied: the tool is outside the task's delegated capability | Capability in token |
50
+ | Prompt injection | After `read_inbox`, e-mail to `archive@exfil.test` is blocked; internal mail still works | Session taint ("lethal trifecta") |
51
+ | Sub-agent | `billing-bot` receives a narrower mandate (refund ≤ €30) with a nested `act` chain | Delegation can only narrow |
52
+ | Kill switch | `support-bot` and every token it delegated stop working in < 1 s; new tokens are refused | Revocation |
53
+ | Audit | The chain verifies. Editing one past record ("€900" → "€9") is detected | Hash-chained ledger |
54
+
55
+ ---
56
+
57
+ ## Quick start (your own setup)
58
+
59
+ ```bash
60
+ mandat init # config, starter policy + tests, keys (.mandat/credentials.json)
61
+ mandat policy test # 7/7 starter decision tests
62
+ mandat serve # control plane + console on http://127.0.0.1:7400/console
63
+
64
+ mandat agents add support-bot --tools "lookup_*,refund,send_email,read_inbox" \
65
+ --resources http://127.0.0.1:7401/mcp --versions 1.4.0 # prints the client secret once
66
+ node examples/refund-server/server.ts # in a clone: protected example MCP server on :7401
67
+ ```
68
+
69
+ These commands assume `npm install -g mandat`. Inside a clone of the repo, use `node bin/mandat.ts` instead of `mandat`.
70
+
71
+ Then, as an agent:
72
+
73
+ ```bash
74
+ TOKEN=$(mandat token --agent support-bot --secret <secret> --user user:maria --resource http://127.0.0.1:7401/mcp --version 1.4.0)
75
+ curl -s http://127.0.0.1:7401/mcp -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
76
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"refund","arguments":{"order_id":"A-1002","amount":150,"currency":"EUR"}}}'
77
+ mandat approvals list # in another terminal
78
+ mandat approvals approve apr_… # the waiting call completes
79
+ mandat revoke --agent support-bot --reason "incident 42"
80
+ mandat ledger verify && mandat ledger report --retention 365
81
+ ```
82
+
83
+ ### Protecting your MCP server
84
+
85
+ With the official TypeScript SDK:
86
+
87
+ ```ts
88
+ import { createGuard, protect } from "mandat";
89
+
90
+ const guard = await createGuard({
91
+ resource: "https://mcp.example.com/mcp", // token audience
92
+ controlPlane: process.env.MANDAT_URL!,
93
+ apiKey: process.env.MANDAT_SERVICE_KEY!, // role: service
94
+ pinning: { lockfile: "mandat.lock.json", mode: "block" },
95
+ });
96
+ const server = protect(new McpServer({ name: "billing", version: "1.0.0" }), guard); // every registerTool is guarded
97
+ app.get("/.well-known/oauth-protected-resource/mcp", (_q, r) => r.json(guard.protectedResourceMetadata()));
98
+ app.use("/mcp", requireBearerAuth({ verifier: guard.sdkTokenVerifier({ InvalidTokenError }) }));
99
+ ```
100
+
101
+ Without dependencies, use the built-in server: `new McpHttpServer({ name, version, guard, tools }).listen(7401)` (see [`examples/refund-server`](examples/refund-server)).
102
+
103
+ On the agent side, use `exchangeToken()` and `McpHttpClient` from `mandat`.
104
+
105
+ ---
106
+
107
+ ## Connecting real agents (Claude Code, Codex, Cursor, Claude Desktop)
108
+
109
+ These clients start a browser login when an MCP server answers `401`. Mandat's control plane only does token exchange, not that login flow, so connect them through **`mandat bridge`**. The bridge is a local stdio MCP server: it acts as a registered agent, exchanges the user's identity for 5-minute task tokens, and gets a new one before the old one expires.
110
+
111
+ ```bash
112
+ mandat agents add claude-code --tools "lookup_*,refund,read_inbox,send_email,delete_*" --resources http://127.0.0.1:7401/mcp
113
+ # → copy the client_secret
114
+ ```
115
+
116
+ The examples pin an exact version (`mandat@0.1.1`). Use the version you have reviewed: an unpinned `npx -y` runs whatever is published next, and `mandat scan-config` flags that.
117
+
118
+ **Claude Code**
119
+
120
+ ```bash
121
+ claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
122
+ npx -y mandat@0.1.1 bridge --url http://127.0.0.1:7401/mcp \
123
+ --mandat http://127.0.0.1:7400 --agent claude-code --user user:maria --email maria@acme.example
124
+ ```
125
+
126
+ On Windows, start the command with `cmd /c`: `… -- cmd /c npx -y mandat@0.1.1 bridge …`
127
+
128
+ Equivalent `.mcp.json` (on Windows: `"command": "cmd"`, and put `"/c", "npx"` at the start of `args`):
129
+
130
+ ```json
131
+ { "mcpServers": { "acme": { "command": "npx",
132
+ "args": ["-y", "mandat@0.1.1", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
133
+ "--agent", "claude-code", "--user", "user:maria", "--email", "maria@acme.example"],
134
+ "env": { "MANDAT_AGENT_SECRET": "<secret>" } } } }
135
+ ```
136
+
137
+ **Codex** (`~/.codex/config.toml`; on Windows use `command = "cmd"` and `args = ["/c", "npx", "-y", …]`)
138
+
139
+ ```toml
140
+ [mcp_servers.acme]
141
+ command = "npx"
142
+ args = ["-y", "mandat@0.1.1", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
143
+ "--agent", "codex", "--user", "user:maria", "--email", "maria@acme.example"]
144
+ env = { MANDAT_AGENT_SECRET = "<secret>" }
145
+
146
+ # Codex has its own approval gate for MCP tools that aren't read-only. Pass these tools through
147
+ # so that Mandat's policy decides (allow / deny / human approval):
148
+ [mcp_servers.acme.tools.refund]
149
+ approval_mode = "approve"
150
+ [mcp_servers.acme.tools.send_email]
151
+ approval_mode = "approve"
152
+ [mcp_servers.acme.tools.read_inbox]
153
+ approval_mode = "approve"
154
+ [mcp_servers.acme.tools.delete_customer]
155
+ approval_mode = "approve"
156
+ ```
157
+
158
+ **Notes**
159
+
160
+ - **Approvals.** A call that needs approval blocks for up to `approvalWaitMs` (15 s in the example server) while a human approves in the console, Slack or `mandat approvals approve <id>`. If nobody answers in time, the agent gets "approval required (request apr_…). Retry the same call once it is approved", and the approval is honoured when the agent retries the identical call.
161
+ - **Real users.** `--user` uses the dev IdP. With a real IdP, put the user's token in `MANDAT_SUBJECT_TOKEN` and configure `trustedIssuers`.
162
+ - **Narrower tasks.** Add `--tools a,b` to give a session less than everything the agent is allowed.
163
+ - **Tested with:** Claude Code 2.1.302 and codex-cli 0.166.0. Both attributed every call in the ledger; Mandat denied over-limit refunds, blocked exfiltration after a prompt injection, and held mid-size refunds and deletes for human approval.
164
+
165
+ ---
166
+
167
+ ## Real users with Auth0 (or any OIDC provider)
168
+
169
+ By default, `mandat init` turns on a dev IdP: anyone can claim to be any user. To have agents act for **real, signed-in people**, connect your identity provider. Auth0 is shown here; Okta, Entra ID and Keycloak work the same way, because Mandat only relies on standard OIDC discovery, JWKS and PKCE.
170
+
171
+ **1. Create an Auth0 application** (Dashboard → Applications → *Create Application*)
172
+
173
+ - **Type:** *Native*. It's a CLI, so there's no client secret; PKCE protects the login instead.
174
+ - **Settings → Allowed Callback URLs:** `http://127.0.0.1:8765/callback`
175
+ - **Settings → Advanced → Grant Types:** *Authorization Code* and *Refresh Token* (both on by default for Native apps).
176
+ - Copy the **Domain** and **Client ID**. You need at least one user (User Management → Users) or a social connection.
177
+
178
+ **2. Trust it on the control plane**, then restart `mandat serve`:
179
+
180
+ ```bash
181
+ mandat idp add --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID --disable-dev-idp
182
+ # Auth0 Organizations: add --tenant-claim org_id
183
+ ```
184
+
185
+ **3. Sign in once** (this opens your browser):
186
+
187
+ ```bash
188
+ mandat login --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID
189
+ mandat login status
190
+ ```
191
+
192
+ The session is stored in `~/.mandat/session.json` (mode 0600) and refreshed automatically when Auth0 issues a refresh token. `login status` tells you whether it did.
193
+
194
+ **4. Let your agent act for you:** in the bridge command, replace `--user …` with `--login`:
195
+
196
+ ```bash
197
+ claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
198
+ npx -y mandat@0.1.1 bridge --url http://127.0.0.1:7401/mcp --mandat http://127.0.0.1:7400 --agent claude-code --login
199
+ ```
200
+
201
+ Every call is now attributed to the Auth0 user, for example `principal.sub = "auth0|…"`, with their e-mail and `org_id` as tenant. That identity is what policies, approvals and the ledger see. The STS accepts only ID tokens issued by the trusted tenant **to that client ID**, so tokens issued to your other Auth0 apps are rejected.
202
+
203
+ ---
204
+
205
+ ## Architecture
206
+
207
+ ```
208
+ Human (IdP: Okta/Entra/Auth0/Keycloak via JWKS; dev IdP for local use)
209
+ │ ID / access token
210
+ ▼
211
+ Agent ──RFC 8693 (sub=user, act=agent) + RAR──▶ Mandat STS ──▶ 5-min task token (aud = one MCP server)
212
+ │
213
+ ▼ MCP (Streamable HTTP)
214
+ MCP server + Mandat Guard (PEP + in-process PDP) ◀── policy (ETag poll, offline snapshot) ── Control plane
215
+ │ allow / deny / require_approval ───────── approvals API ──▶ Slack · webhook · console · CLI
216
+ │ revocations (2 s poll) ◀──────────────────────────────────── kill switch
217
+ │ Action Records (async, batched, at-least-once, deduped) ──▶ hash-chained ledger ──▶ OCSF / OTLP
218
+ ▼
219
+ Downstream services (the user's token is never forwarded)
220
+ ```
221
+
222
+ | Path | What lives there |
223
+ |---|---|
224
+ | `src/policy/` | Expression language (CEL subset, no `eval`) and the PDP (deny-overrides, fail-closed on errors) |
225
+ | `src/sts/` | JWT/JWKS (ES256/RS256/PS256/EdDSA, no `none`/HMAC), token exchange, revocation model |
226
+ | `src/guard/` | Guard (PEP), tool pinning, remote clients for the control plane |
227
+ | `src/mcp/` | Zero-dep MCP HTTP server with Guard, and the `protect()` adapter for the official SDK |
228
+ | `src/approvals/` | Approval service, Slack (Block Kit + signed interactions), signed webhooks |
229
+ | `src/ledger/` | Hash chain, PII redaction, OCSF/OTel export, OTLP exporter, compliance report |
230
+ | `src/scan/` | Remote scanner and config/source scanner; text/JSON/SARIF/HTML output |
231
+ | `src/controlplane/` | HTTP control plane and web console |
232
+ | `src/cli/` | `mandat` CLI |
233
+
234
+ ### Decision semantics
235
+
236
+ - **Deny overrides.** Any matching `deny` wins. Otherwise any `require_approval` wins. Otherwise `allow` (obligations are merged). Otherwise the policy `default` applies, which is `deny`. Rule order doesn't matter.
237
+ - **Errors fail closed.** If a condition can't be evaluated (type error, missing data), it counts as a match for `deny`/`require_approval` rules and as no match for `allow` rules.
238
+ - **Capability first.** A call outside the token's `authorization_details` (tool, location, argument limits) is denied before any rule runs.
239
+ - **Taint.** A tool marked `taints: true` (e-mail, web, tickets) marks the session. Rules can then check `session.tainted`.
240
+ - **Approvals.** Each approval is bound to `sha256(user, agent, tool, server, args)` and can be used once. Self-approval is refused, `approvers: 2` means four-eyes, and a timeout means deny.
241
+ - **Fail modes.** If revocations can't be refreshed for 15 s, `financial`/`destructive` tools fail closed. Policy keeps working from the last snapshot.
242
+ - **Shadow mode** (`mode: "shadow"`) records the decision but never blocks. Use it to roll out new policies.
243
+
244
+ ### Policy language
245
+
246
+ ```jsonc
247
+ {
248
+ "version": 1,
249
+ "default": "deny",
250
+ "tools": { "refund": { "risk": "financial" }, "read_inbox": { "risk": "read", "taints": true },
251
+ "send_email": { "risk": "external_comm", "redact": ["body"] } },
252
+ "rules": [
253
+ { "id": "refund-approval", "tool": "refund", "when": "args.amount > 50 && args.amount <= 500",
254
+ "effect": "require_approval", "approval": { "approvers": 1, "timeout": "15m", "channels": ["slack"] } },
255
+ { "id": "no-exfil", "tool": "send_email",
256
+ "when": "session.tainted && !args.to.all(r, r.endsWith('@example.com'))", "effect": "deny" }
257
+ ]
258
+ }
259
+ ```
260
+
261
+ - **Context:** `principal.{sub,tenant,email,scope}`, `agent.{id,version,prompt_hash}`, `actor_chain[]`, `tool.{name,server,risk}`, `args.*`, `session.{tainted,taint_sources,calls}`, `task.{id,authorization_details}`, `env.{hour_utc,weekday_utc}`.
262
+ - **Operators:** `== != < <= > >= in && || ! ?: + - * / %`.
263
+ - **Functions:** `size has int double string lower upper abs min max`.
264
+ - **Methods:** `startsWith endsWith contains matches size lower upper trim keys`.
265
+ - **Macros:** `all exists filter`.
266
+ - **Effects:** `allow`, `deny`, `require_approval`, `allow_with_obligations` (obligations: `redact` fields, `annotate` tags).
267
+
268
+ Tooling: `mandat policy check|test|eval` and `mandat bench`. On this machine the PDP measures p50 ≈ 14 µs and p99 ≈ 70 µs (the PRD targets are 0.5 ms and 5 ms).
269
+
270
+ ---
271
+
272
+ ## PRD coverage
273
+
274
+ | PRD item | MVP status |
275
+ |---|---|
276
+ | **US-1** `mandat scan <url>`: auth on `tools/list`, invalid token, PRM, PKCE S256/`plain`, DCR vs CIMD, `iss` (RFC 9207), CORS, transport, tool poisoning, opt-in redirect-URI probe (`--active`); fixes include code | ✅ |
277
+ | Static scan of client configs (unpinned `npx`/`uvx`, known-malicious versions, typosquats, shell/stdio commands, `curl\|sh`, plaintext secrets, static bearer tokens, `0.0.0.0`, broad filesystem roots, privileged Docker) and server source (eval, shell exec, token passthrough); JSON/SARIF/HTML output; GitHub Action | ✅ |
278
+ | **US-2** `protect(server)` for the TS SDK | ✅ (duck-typed adapter, tested against an SDK-shaped fake; not yet run against the real SDK or MCP Inspector) · Python ❌ |
279
+ | **US-3** Argument policies with p99 < 5 ms; approval in Slack with context | ✅ (Slack: Block Kit message + signed interactivity endpoint `/slack/interactions`) |
280
+ | **US-4** Single-task token via RFC 8693 with `sub` = user, `act` = agent, RAR, 5 min | ✅ for Mandat-protected MCP servers · downstream tokens for Stripe/CRM ❌ |
281
+ | **US-5** ID-JAG / Okta XAA | ❌ |
282
+ | Real IdP users (PRD Must: Auth0, Okta, Entra, Keycloak) | ✅ OIDC login with PKCE (`mandat login`), `mandat idp add`, ID-token exchange. Covered by tests against an Auth0-like fake IdP |
283
+ | **US-6** OCSF event with the delegation chain | ✅ export via `/api/ledger/export`; OTLP push of spans (`ledger.otlp`) · direct SIEM connectors (Splunk HEC and others) ❌ |
284
+ | **US-7** Revocation by agent, version, user, task, tenant or token in ≤ 10 s | ✅ < 1 s in tests; issuance blocked until lifted |
285
+ | **US-8** DPO report from the hash chain, retention check | ✅ `mandat ledger report`, console |
286
+ | **US-9** Tool description/schema drift | ✅ server-side lockfile (warn/block) and client-side `mandat pin --check` |
287
+ | Attribution model, local ledger, shadow mode, taint, policy tests | ✅ |
288
+ | Control plane: agents registry, roles (admin / approver / auditor / service), policy change log, console | ✅ |
289
+ | Cloud Free, hosted multi-tenant ledger, CIBA, Teams, Transaction Tokens, SPIFFE, Gateway, other language SDKs | ❌ out of MVP scope |
290
+
291
+ ## Security notes and known limitations
292
+
293
+ - **Dev IdP.** `devIdp: true` (the `mandat init` default) lets anyone mint user tokens on `/dev/login`. Disable it with `mandat idp add … --disable-dev-idp` before any real use.
294
+ - **Approver identity.** Approvers still authenticate with API keys (console/CLI) or Slack, not through the IdP, so self-approval is only detected when the approver id matches the user's `sub` or e-mail.
295
+ - **Storage.** The control plane keeps state in JSON files under `dataDir` (single process, no HA). The `JsonCollection` interface is the seam for a database.
296
+ - **Ledger.** The ledger is tamper-*evident*, not tamper-*proof*: someone with write access could rewrite the whole chain. For that threat, anchor the head hash externally (WORM storage, a transparency log, or an eIDAS timestamp; see open question 8). Records are ordered by `seq`, which is arrival order; `ts` is event time.
297
+ - **Auth failures** (bad or revoked token → `401`) are returned to the caller but not yet written to the ledger.
298
+ - **Slack identity.** Slack approvers are recorded as `slack:<username>`. They are not yet mapped to IdP identities, so the self-approval check covers only the API, console and CLI.
299
+ - **MCP server scope.** The built-in MCP server implements the JSON response mode of Streamable HTTP (no SSE stream, no server→client requests).
300
+ - **OWASP mappings.** Mappings to OWASP Agentic (ASI) and MCP Top 10 are best effort.
301
+
302
+ ## Development
303
+
304
+ ```bash
305
+ npm test # 46 tests: expression language, PDP, STS, guard, approvals, ledger, scanner, OIDC, end-to-end over HTTP
306
+ npm run typecheck # tsc --strict (dev dependency only)
307
+ npm run build # dist/ (plain JS + .d.ts) for the npm package; Node >= 20
308
+ npm run demo
309
+ ```
310
+
311
+ ## Releasing
312
+
313
+ Releases are published from GitHub Actions ([`release.yml`](.github/workflows/release.yml)) using npm Trusted Publishing, so no npm token is stored anywhere:
314
+
315
+ ```bash
316
+ npm version patch # bumps package.json, commits, tags vX.Y.Z
317
+ git push --follow-tags # CI checks the tag, runs typecheck and tests, then publishes with provenance
318
+ ```
319
+
320
+ License: Apache-2.0.
package/dist/cli/main.js CHANGED
@@ -18,53 +18,53 @@ import { hashApiKey, loadConfig } from "../controlplane/config.js";
18
18
  import { Bridge } from "../bridge.js";
19
19
  import { clearSession, currentIdToken, discover, loadSession, login, openSystemBrowser, saveSession } from "../oidc.js";
20
20
  import { readJson, writeJsonAtomic } from "../util.js";
21
- const VERSION = "0.1.0";
21
+ import { VERSION } from "../version.js";
22
22
  const BOOLEANS = ["version", "login", "no-browser", "disable-dev-idp", "active", "check", "force", "json", "tainted", "help", "h", "follow", "frozen", "no-color", "shadow"];
23
- const HELP = `mandat ${VERSION} — authorization, delegation and audit for AI agent actions
24
-
25
- Setup
26
- mandat init [--resource URL] [--force] Create config, starter policy, keys and API credentials
27
- mandat serve [--config mandat.config.json] Run the control plane (STS, approvals, ledger, console)
28
-
29
- Scan (US-1)
30
- mandat scan <url> [--active] Check a remote MCP server's authorization surface
31
- mandat scan-config [files...] [--src DIR] Static scan of MCP client configs (auto-detects known paths) and server source
32
- --format text|json|sarif|html --out FILE --fail-on critical|high|medium|low|none (default high)
33
-
34
- Tool pinning (US-9)
35
- mandat pin <url> [--token T] [--lock mandat.lock.json] [--check] Pin / verify tool definitions of an MCP server
36
-
37
- Policy
38
- mandat policy check [mandat.policy.json]
39
- mandat policy test [policy] [tests.json] Run decision tests (writes mandat.policy.test.json on first run)
40
- mandat policy eval [policy] --tool T --args JSON [--agent A] [--tainted]
41
- mandat bench [policy] PDP latency (p50/p99)
42
-
43
- Agents, approvals, revocation (talk to the control plane: --url, --key or MANDAT_URL / MANDAT_API_KEY)
44
- mandat agents list
45
- mandat agents add <id> --tools a,b [--resources URL,...] [--versions 1.0.0,...] [--name N]
46
- mandat approvals list [--status pending]
47
- mandat approvals approve|deny <id> [--comment C]
48
- mandat revoke --agent ID [--version V] | --user SUB | --task ID | --tenant T | --jti ID [--reason R]
49
- mandat token --agent ID --secret S --user SUB --resource URL [--tools a,b] [--version V] Dev: mint a task token
50
-
51
- Real users (OIDC: Auth0, Okta, Entra ID, Keycloak)
52
- mandat idp add --issuer URL --client-id ID [--tenant-claim CLAIM] [--disable-dev-idp] Trust an IdP (edits mandat.config.json)
53
- mandat idp list
54
- mandat login --issuer URL --client-id ID [--port 8765] [--organization ORG] [--no-browser] Browser login (PKCE)
55
- mandat login status | mandat logout
56
-
57
- Connect real agents (Claude Code, Codex, Cursor, Claude Desktop)
58
- mandat bridge --url MCP_URL --agent ID [--mandat URL] [--login | --user SUB] [--version V] [--tools a,b]
59
- stdio MCP server that acts as agent ID and refreshes task tokens automatically.
60
- --login acts for the user signed in with "mandat login"; --user uses the dev IdP.
61
- Secret: env MANDAT_AGENT_SECRET (or --secret). Raw IdP token instead: env MANDAT_SUBJECT_TOKEN.
62
-
63
- Ledger (US-6, US-8)
64
- mandat ledger verify [file] Verify the hash chain
65
- mandat ledger tail [file] [-n 20]
66
- mandat ledger report [file] [--from ISO] [--to ISO] [--format md|json] [--retention DAYS]
67
- mandat ledger export [file] --format ocsf|otel
23
+ const HELP = `mandat ${VERSION} — authorization, delegation and audit for AI agent actions
24
+
25
+ Setup
26
+ mandat init [--resource URL] [--force] Create config, starter policy, keys and API credentials
27
+ mandat serve [--config mandat.config.json] Run the control plane (STS, approvals, ledger, console)
28
+
29
+ Scan (US-1)
30
+ mandat scan <url> [--active] Check a remote MCP server's authorization surface
31
+ mandat scan-config [files...] [--src DIR] Static scan of MCP client configs (auto-detects known paths) and server source
32
+ --format text|json|sarif|html --out FILE --fail-on critical|high|medium|low|none (default high)
33
+
34
+ Tool pinning (US-9)
35
+ mandat pin <url> [--token T] [--lock mandat.lock.json] [--check] Pin / verify tool definitions of an MCP server
36
+
37
+ Policy
38
+ mandat policy check [mandat.policy.json]
39
+ mandat policy test [policy] [tests.json] Run decision tests (writes mandat.policy.test.json on first run)
40
+ mandat policy eval [policy] --tool T --args JSON [--agent A] [--tainted]
41
+ mandat bench [policy] PDP latency (p50/p99)
42
+
43
+ Agents, approvals, revocation (talk to the control plane: --url, --key or MANDAT_URL / MANDAT_API_KEY)
44
+ mandat agents list
45
+ mandat agents add <id> --tools a,b [--resources URL,...] [--versions 1.0.0,...] [--name N]
46
+ mandat approvals list [--status pending]
47
+ mandat approvals approve|deny <id> [--comment C]
48
+ mandat revoke --agent ID [--version V] | --user SUB | --task ID | --tenant T | --jti ID [--reason R]
49
+ mandat token --agent ID --secret S --user SUB --resource URL [--tools a,b] [--version V] Dev: mint a task token
50
+
51
+ Real users (OIDC: Auth0, Okta, Entra ID, Keycloak)
52
+ mandat idp add --issuer URL --client-id ID [--tenant-claim CLAIM] [--disable-dev-idp] Trust an IdP (edits mandat.config.json)
53
+ mandat idp list
54
+ mandat login --issuer URL --client-id ID [--port 8765] [--organization ORG] [--no-browser] Browser login (PKCE)
55
+ mandat login status | mandat logout
56
+
57
+ Connect real agents (Claude Code, Codex, Cursor, Claude Desktop)
58
+ mandat bridge --url MCP_URL --agent ID [--mandat URL] [--login | --user SUB] [--version V] [--tools a,b]
59
+ stdio MCP server that acts as agent ID and refreshes task tokens automatically.
60
+ --login acts for the user signed in with "mandat login"; --user uses the dev IdP.
61
+ Secret: env MANDAT_AGENT_SECRET (or --secret). Raw IdP token instead: env MANDAT_SUBJECT_TOKEN.
62
+
63
+ Ledger (US-6, US-8)
64
+ mandat ledger verify [file] Verify the hash chain
65
+ mandat ledger tail [file] [-n 20]
66
+ mandat ledger report [file] [--from ISO] [--to ISO] [--format md|json] [--retention DAYS]
67
+ mandat ledger export [file] --format ocsf|otel
68
68
  `;
69
69
  export async function main(argv) {
70
70
  const args = parseArgs(argv, BOOLEANS);
@@ -147,18 +147,18 @@ function init(args) {
147
147
  const giText = existsSync(gi) ? readFileSync(gi, "utf8") : "";
148
148
  if (!/^\.mandat\/?$/m.test(giText))
149
149
  appendFileSync(gi, (giText && !giText.endsWith("\n") ? "\n" : "") + ".mandat/\n");
150
- console.log(`✓ Created mandat.config.json, mandat.policy.json, mandat.policy.test.json
151
- ✓ API keys written to .mandat/credentials.json (git-ignored; shown once below)
152
-
153
- admin ${keys.admin}
154
- approver ${keys.approver} (identity "alice")
155
- auditor ${keys.auditor}
156
- service ${keys.service} (for Guards in your MCP servers)
157
-
158
- Next:
159
- 1. mandat policy test # check the starter policy
160
- 2. mandat serve # control plane + console at ${issuer}/console
161
- 3. mandat agents add support-bot --tools "lookup_*,refund,send_email" --resources ${resource}
150
+ console.log(`✓ Created mandat.config.json, mandat.policy.json, mandat.policy.test.json
151
+ ✓ API keys written to .mandat/credentials.json (git-ignored; shown once below)
152
+
153
+ admin ${keys.admin}
154
+ approver ${keys.approver} (identity "alice")
155
+ auditor ${keys.auditor}
156
+ service ${keys.service} (for Guards in your MCP servers)
157
+
158
+ Next:
159
+ 1. mandat policy test # check the starter policy
160
+ 2. mandat serve # control plane + console at ${issuer}/console
161
+ 3. mandat agents add support-bot --tools "lookup_*,refund,send_email" --resources ${resource}
162
162
  ${readmeSnippet(resource, issuer)}`);
163
163
  return 0;
164
164
  }
@@ -173,11 +173,11 @@ async function serve(args) {
173
173
  cfg.port = args.num("port", cfg.port);
174
174
  const cp = createControlPlane(cfg);
175
175
  const addr = await cp.listen();
176
- console.log(`Mandat control plane listening on ${addr}
177
- issuer ${cfg.issuer}
178
- console ${cfg.issuer}/console
179
- token ${cfg.issuer}/oauth/token (RFC 8693 token exchange)
180
- jwks ${cfg.issuer}/.well-known/jwks.json
176
+ console.log(`Mandat control plane listening on ${addr}
177
+ issuer ${cfg.issuer}
178
+ console ${cfg.issuer}/console
179
+ token ${cfg.issuer}/oauth/token (RFC 8693 token exchange)
180
+ jwks ${cfg.issuer}/.well-known/jwks.json
181
181
  ledger ${cp.ledger.path} (${cp.ledger.length} records)${cfg.devIdp ? "\n ⚠ dev IdP enabled (POST /dev/login) — disable `devIdp` in production" : ""}`);
182
182
  await new Promise((r) => { process.once("SIGINT", r); process.once("SIGTERM", r); });
183
183
  await cp.close();
@@ -566,9 +566,9 @@ async function loginCmd(args) {
566
566
  return 1;
567
567
  }
568
568
  const left = s.expires_at - Math.floor(Date.now() / 1000);
569
- console.log(`Logged in as ${s.user.email ?? s.user.sub} (${s.user.sub})
570
- issuer ${s.issuer}
571
- client ${s.client_id}
569
+ console.log(`Logged in as ${s.user.email ?? s.user.sub} (${s.user.sub})
570
+ issuer ${s.issuer}
571
+ client ${s.client_id}
572
572
  id token ${left > 0 ? `valid ${Math.round(left / 60)} min` : "expired"}${s.refresh_token ? ", refresh token stored" : ", no refresh token (log in again when it expires)"}`);
573
573
  return 0;
574
574
  }
@@ -585,7 +585,7 @@ async function loginCmd(args) {
585
585
  issuer, clientId, port,
586
586
  extraParams: args.str("organization") ? { organization: args.str("organization") } : undefined,
587
587
  openBrowser: (url) => {
588
- console.error(`If the browser does not open, visit:
588
+ console.error(`If the browser does not open, visit:
589
589
  ${url}`);
590
590
  if (!args.bool("no-browser"))
591
591
  openSystemBrowser(url);
@@ -615,7 +615,7 @@ async function idpCmd(sub, args) {
615
615
  if (!list.length)
616
616
  console.log("No trusted identity providers.");
617
617
  for (const t of list)
618
- console.log(`● ${t.issuer}
618
+ console.log(`● ${t.issuer}
619
619
  audience ${JSON.stringify(t.audience)} jwks ${t.jwks_uri}${t.tenant_claim ? ` tenant claim ${t.tenant_claim}` : ""}`);
620
620
  console.log(`Dev IdP: ${raw.devIdp ? "ENABLED (anyone can mint user tokens)" : "disabled"}`);
621
621
  return 0;
@@ -640,7 +640,7 @@ async function idpCmd(sub, args) {
640
640
  if (args.bool("disable-dev-idp"))
641
641
  raw.devIdp = false;
642
642
  writeJsonAtomic(cfgPath, raw);
643
- console.log(`✓ Trusting ${meta.issuer} (ID tokens for client ${clientId})${args.bool("disable-dev-idp") ? "; dev IdP disabled" : ""}
643
+ console.log(`✓ Trusting ${meta.issuer} (ID tokens for client ${clientId})${args.bool("disable-dev-idp") ? "; dev IdP disabled" : ""}
644
644
  Restart \`mandat serve\` to apply.`);
645
645
  return 0;
646
646
  }
package/dist/client.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Agent-side helpers: obtain a per-task token (RFC 8693) and call an MCP server over Streamable HTTP.
2
2
  import { GRANT_TOKEN_EXCHANGE, TT_ID_TOKEN } from "./sts/sts.js";
3
3
  import { sha256 } from "./util.js";
4
+ import { VERSION } from "./version.js";
4
5
  export async function exchangeToken(o) {
5
6
  const form = new URLSearchParams({
6
7
  grant_type: GRANT_TOKEN_EXCHANGE,
@@ -77,7 +78,7 @@ export class McpHttpClient {
77
78
  return msg.result;
78
79
  }
79
80
  initialize() {
80
- return this.request("initialize", { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "mandat-client", version: "0.1.0" } });
81
+ return this.request("initialize", { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "mandat-client", version: VERSION } });
81
82
  }
82
83
  async listTools() {
83
84
  return (await this.request("tools/list")).tools;
@@ -3,6 +3,7 @@
3
3
  // - OpenTelemetry spans following the GenAI semantic conventions (`execute_tool`) + `mandat.*` attributes,
4
4
  // shipped over OTLP/HTTP JSON. Delivery is asynchronous, batched and retried (at-least-once).
5
5
  import { sha256 } from "../util.js";
6
+ import { VERSION } from "../version.js";
6
7
  const OCSF_VERSION = "1.3.0";
7
8
  export function toOcsf(r) {
8
9
  const activity = r.tool?.risk === "read" ? 2 : r.tool?.risk === "destructive" ? 4 : r.tool?.risk === "write" ? 3 : 99;
@@ -26,7 +27,7 @@ export function toOcsf(r) {
26
27
  uid: r.id,
27
28
  correlation_uid: r.task_id ?? undefined,
28
29
  labels: [r.type, ...(r.tags ?? [])],
29
- product: { name: "Mandat", vendor_name: "Mandat", version: "0.1.0" },
30
+ product: { name: "Mandat", vendor_name: "Mandat", version: VERSION },
30
31
  sequence: r.seq,
31
32
  },
32
33
  actor: {
@@ -139,7 +140,7 @@ export class OtlpExporter {
139
140
  const body = {
140
141
  resourceSpans: [{
141
142
  resource: { attributes: [attr("service.name", this.opts.serviceName)] },
142
- scopeSpans: [{ scope: { name: "mandat", version: "0.1.0" }, spans: batch.map(toOtelSpan) }],
143
+ scopeSpans: [{ scope: { name: "mandat", version: VERSION }, spans: batch.map(toOtelSpan) }],
143
144
  }],
144
145
  };
145
146
  const res = await fetch(this.opts.endpoint.replace(/\/$/, "") + "/v1/traces", {
@@ -1,4 +1,5 @@
1
1
  // Finding model + output formats (text, JSON, SARIF 2.1.0, HTML).
2
+ import { VERSION } from "../version.js";
2
3
  export const SEVERITIES = ["critical", "high", "medium", "low", "info"];
3
4
  export function severityRank(s) {
4
5
  return SEVERITIES.indexOf(s);
@@ -53,7 +54,7 @@ export function formatSarif(reports) {
53
54
  tool: {
54
55
  driver: {
55
56
  name: "mandat-scan",
56
- version: "0.1.0",
57
+ version: VERSION,
57
58
  rules: [...rules.values()].map((f) => ({
58
59
  id: f.rule,
59
60
  name: f.title.replace(/[^A-Za-z0-9]+/g, ""),
@@ -79,27 +80,27 @@ export function formatSarif(reports) {
79
80
  }
80
81
  const esc = (s) => s.replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
81
82
  export function formatHtml(reports) {
82
- const body = reports.map((r) => `
83
- <section>
84
- <h2>${esc(r.kind)} · ${esc(r.target)}</h2>
85
- <p class="meta">Scanned ${esc(r.scanned_at)} · ${r.findings.length} findings · passed: ${esc(r.passed.join(", ") || "—")}</p>
86
- ${sortFindings(r.findings).map((f) => `
87
- <article class="f ${f.severity}">
88
- <header><span class="sev">${f.severity}</span> <code>${esc(f.rule)}</code> <strong>${esc(f.title)}</strong></header>
89
- <p>${esc(f.detail)}</p>
90
- <p><b>Fix:</b> ${esc(f.fix)}</p>
91
- ${f.fixCode ? `<pre>${esc(f.fixCode)}</pre>` : ""}
92
- ${f.owasp.length ? `<p class="meta">OWASP: ${esc(f.owasp.join(", "))}</p>` : ""}
93
- </article>`).join("")}
83
+ const body = reports.map((r) => `
84
+ <section>
85
+ <h2>${esc(r.kind)} · ${esc(r.target)}</h2>
86
+ <p class="meta">Scanned ${esc(r.scanned_at)} · ${r.findings.length} findings · passed: ${esc(r.passed.join(", ") || "—")}</p>
87
+ ${sortFindings(r.findings).map((f) => `
88
+ <article class="f ${f.severity}">
89
+ <header><span class="sev">${f.severity}</span> <code>${esc(f.rule)}</code> <strong>${esc(f.title)}</strong></header>
90
+ <p>${esc(f.detail)}</p>
91
+ <p><b>Fix:</b> ${esc(f.fix)}</p>
92
+ ${f.fixCode ? `<pre>${esc(f.fixCode)}</pre>` : ""}
93
+ ${f.owasp.length ? `<p class="meta">OWASP: ${esc(f.owasp.join(", "))}</p>` : ""}
94
+ </article>`).join("")}
94
95
  </section>`).join("");
95
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
96
- <title>Mandat scan report</title>
97
- <style>
98
- body{font:15px/1.5 system-ui,sans-serif;max-width:960px;margin:2rem auto;padding:0 1rem;color:#1d1d1f;background:#fafafa}
99
- h1{font-size:1.6rem}h2{font-size:1.15rem;margin-top:2rem}.meta{color:#666;font-size:.85rem}
100
- .f{background:#fff;border:1px solid #e3e3e3;border-left:5px solid #999;border-radius:6px;padding:.75rem 1rem;margin:.75rem 0}
101
- .f.critical{border-left-color:#b00020}.f.high{border-left-color:#e53935}.f.medium{border-left-color:#f9a825}.f.low{border-left-color:#039be5}
102
- .sev{text-transform:uppercase;font-size:.75rem;font-weight:700;letter-spacing:.04em}
103
- pre{background:#f3f3f3;padding:.6rem;border-radius:4px;overflow-x:auto;font-size:.82rem}
96
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
97
+ <title>Mandat scan report</title>
98
+ <style>
99
+ body{font:15px/1.5 system-ui,sans-serif;max-width:960px;margin:2rem auto;padding:0 1rem;color:#1d1d1f;background:#fafafa}
100
+ h1{font-size:1.6rem}h2{font-size:1.15rem;margin-top:2rem}.meta{color:#666;font-size:.85rem}
101
+ .f{background:#fff;border:1px solid #e3e3e3;border-left:5px solid #999;border-radius:6px;padding:.75rem 1rem;margin:.75rem 0}
102
+ .f.critical{border-left-color:#b00020}.f.high{border-left-color:#e53935}.f.medium{border-left-color:#f9a825}.f.low{border-left-color:#039be5}
103
+ .sev{text-transform:uppercase;font-size:.75rem;font-weight:700;letter-spacing:.04em}
104
+ pre{background:#f3f3f3;padding:.6rem;border-radius:4px;overflow-x:auto;font-size:.82rem}
104
105
  </style></head><body><h1>Mandat scan report</h1>${body}</body></html>`;
105
106
  }
@@ -1,6 +1,7 @@
1
1
  // External scan of a remote MCP server's authorization surface (MCP Authorization rev. 2026-07-28):
2
2
  // unauthenticated tools, token validation, PRM (RFC 9728), AS metadata (RFC 8414), PKCE S256,
3
3
  // DCR vs CIMD, `iss` (RFC 9207), CORS, transport. Passive by default; `active` adds a DCR redirect probe.
4
+ import { VERSION } from "../version.js";
4
5
  const FIX_PROTECT = `// npm i mandat — then wrap your server:
5
6
  import { createGuard, protect } from "mandat";
6
7
  const guard = await createGuard({ resource: "https://mcp.example.com/mcp", controlPlane: process.env.MANDAT_URL, apiKey: process.env.MANDAT_API_KEY });
@@ -33,7 +34,7 @@ export async function scanRemote(target, opts = {}) {
33
34
  const rpc = (method, id, token) => req(target, {
34
35
  method: "POST",
35
36
  headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": "2026-07-28", ...(token ? { authorization: `Bearer ${token}` } : {}) },
36
- body: JSON.stringify({ jsonrpc: "2.0", id, method, params: method === "initialize" ? { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "mandat-scan", version: "0.1.0" } } : {} }),
37
+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params: method === "initialize" ? { protocolVersion: "2026-07-28", capabilities: {}, clientInfo: { name: "mandat-scan", version: VERSION } } : {} }),
37
38
  });
38
39
  // 1. Transport
39
40
  const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
@@ -24,6 +24,8 @@ const RUNNERS = {
24
24
  pipx: { pinned: (s) => /==\d/.test(s), eco: "pypi" },
25
25
  };
26
26
  const SHELLS = ["sh", "bash", "zsh", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh", "pwsh.exe"];
27
+ const SHELL_FLAGS = ["-c", "/c", "-command", "-encodedcommand", "/k"];
28
+ const baseName = (command) => command.split(/[\\/]/).pop().toLowerCase();
27
29
  const SECRET_ENV = /(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_KEY|ACCESS_KEY|CLIENT_SECRET|CREDENTIALS?)/i;
28
30
  export function scanConfigFile(path) {
29
31
  const text = readFileSync(path, "utf8");
@@ -46,9 +48,23 @@ export function scanServers(servers, file, rawText = "") {
46
48
  for (const [name, s] of Object.entries(servers)) {
47
49
  const location = { file, server: name, line: lineOf(`"${name}"`) };
48
50
  const add = (f) => findings.push({ ...f, location });
49
- const cmd = (s.command ?? "").split(/[\\/]/).pop().toLowerCase();
50
- const args = (s.args ?? []).map(String);
51
+ let cmd = baseName(s.command ?? "");
52
+ let args = (s.args ?? []).map(String);
51
53
  const all = [s.command ?? "", ...args].join(" ");
54
+ // `cmd /c npx -y pkg@1.2.3` is the documented way to start stdio servers on Windows. When a shell only
55
+ // wraps a plain command (separate tokens, no metacharacters), analyse the inner command instead.
56
+ let shellString = false;
57
+ const flagIdx = SHELLS.includes(cmd) ? args.findIndex((a) => SHELL_FLAGS.includes(a.toLowerCase())) : -1;
58
+ if (flagIdx >= 0) {
59
+ const rest = args.slice(flagIdx + 1);
60
+ const plain = rest.length > 0 && !rest.some((a) => /[|&;<>`$()]/.test(a)) && !(rest.length === 1 && /\s/.test(rest[0]));
61
+ if (plain) {
62
+ cmd = baseName(rest[0]);
63
+ args = rest.slice(1);
64
+ }
65
+ else
66
+ shellString = true;
67
+ }
52
68
  // Package runners: pinning, malicious versions, typosquats
53
69
  const runner = RUNNERS[cmd.replace(/\.(cmd|exe)$/, "")];
54
70
  if (runner) {
@@ -73,7 +89,7 @@ export function scanServers(servers, file, rawText = "") {
73
89
  }
74
90
  }
75
91
  // Shell interpreters / remote code
76
- if (SHELLS.includes(cmd) && args.some((a) => ["-c", "/c", "-command", "-encodedcommand", "/k"].includes(a.toLowerCase()))) {
92
+ if (shellString) {
77
93
  add({ rule: "MDT-C004", severity: "high", title: "MCP server launched through a shell", detail: `'${all.slice(0, 120)}' runs an arbitrary shell string. stdio transports execute whatever command they are given (CVE-2026-30623 class).`, fix: "Invoke the server binary directly with an argument array; never build stdio commands from untrusted input.", owasp: ["ASI05", "MCP05"] });
78
94
  }
79
95
  if (/(curl|wget|iwr|invoke-webrequest)[^|]*\|\s*(sh|bash|iex|python)/i.test(all) || /\beval\b/.test(all)) {
@@ -0,0 +1 @@
1
+ export declare const VERSION: string;
@@ -0,0 +1,3 @@
1
+ // Single source of truth for the version: package.json (one level up from both src/ and dist/).
2
+ import { readFileSync } from "node:fs";
3
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "mandat",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Authorization, delegation and audit for AI agent actions (MCP-first). Policy on every tool call, per-task delegated tokens, hash-chained audit ledger, MCP scanner.",
5
5
  "license": "Apache-2.0",
6
+ "author": "Muhammadsaid Vosidov",
7
+ "homepage": "https://github.com/vosidov-msaid/Mandat#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vosidov-msaid/Mandat.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/vosidov-msaid/Mandat/issues"
14
+ },
6
15
  "type": "module",
7
16
  "engines": {
8
17
  "node": ">=20"