# Outil Local — implementation spec

The downloadable local MCP server (`npx @veritia/mcp-server`). It runs on the user's
machine next to Claude Desktop, holds the agent's private key, and is a **generic,
tool-agnostic proxy**: it discovers the PDS's tools at startup and, on every call, signs a
DPoP proof and forwards with the delegation token attached.

**This is the least-mocked component of the POC** — real MCP stdio transport, a real keypair
on disk, real per-request signing, nothing faked ([architecture.md §10](../architecture.md)).
Build it to match the real product; there is no POC-only shortcut here. Shared wire formats:
[`../contracts.md`](../contracts.md).

---

## 1. Scope & build order

Three modes in one package: `init` (global **step 2**), the runtime server (global **step 5**),
and `setup` (global **step 5b**).

| Mode | Global step | Depends on | Before / after |
|---|---|---|---|
| `init` | 2 | [contracts §2](../contracts.md) key format only | Trivial; do it early — it produces the real Ed25519 keypair every later test JWT is bound to. Runs **once per machine** ([contracts §9](../contracts.md), revised 2026-09-19) — not once per AI client |
| runtime | 5 | stub (1) can mint a real JWT · `init` (2) · PDS **MCP route** (4) exists · [contracts §2](../contracts.md) DPoP | Build **after** the PDS MCP route (4) so discovery + calls hit a real server. Wire to the **real** Claude Desktop. The PDS isolated filter (6) is built *after* this, against these real proofs |
| `setup` | 5b | `init` (2) has run (needs an existing `agent.key`) · stub's `/setup-codes/:code/redeem` (1) · [contracts §9](../contracts.md) | Independent of the runtime mode itself — only needs the stub and an existing key. Human runs it once per mandate, between minting the mandate and wiring up an AI client |

Out of scope for the POC: the Integration SDK (component C), multi-provider multiplexing (one
instance = one provider), the `DPoP-Nonce` challenge.

---

## 2. Tech

| Concern | Choice |
|---|---|
| Language | TypeScript, Node 20 LTS |
| MCP | `@modelcontextprotocol/sdk` — `StdioServerTransport` (toward Claude Desktop) + `StreamableHTTPClientTransport` (toward the PDS) |
| Crypto | Node `crypto` (`generateKeyPair('ed25519')`) for keygen; `jose` for the DPoP proof JWS + JWK thumbprint |
| Distribution | `npx` entry point with subcommand: `mcp-server init` / `mcp-server setup <redeem-url>` (§5, step 5b) / `mcp-server` (runtime) |

**Spike-confirmed** ([pds/spike-notes.md](../pds/spike-notes.md), 2026-09-09): pin
`@modelcontextprotocol/sdk@1.30.0`. Per-request header injection works via the transport's
**`fetch` option** — wrap `fetch`, build a fresh DPoP proof, set `Authorization: DPoP …` +
`DPoP: …` on every call (POSTs *and* the GET SSE stream). `requestInit.headers` also exists but
is static — use `fetch`. Negotiated MCP protocol is `2025-11-25` (session-scoped; the SDK
handles `Mcp-Session-Id` itself).

---

## 3. `init` mode

```
$ npx @veritia/mcp-server init
Private key written to ~/.veritia/agent.key  (chmod 600)
Public key — paste this into the mandate form:
{"kty":"OKP","crv":"Ed25519","x":"11qYAeh...Rds"}
Key id (kid / RFC 7638 thumbprint): 3s7Kd...QpM
```

| Step | Detail | Attention |
|---|---|---|
| 1 | `generateKeyPairSync('ed25519')` | — |
| 2 | Write **private** key to `${NP_HOME:-~/.veritia}/agent.key`, PKCS#8 PEM, mode `0600`, dir `0700` | **Refuse to overwrite** an existing file without `--force`. Never an env var, never logged, never transmitted ([spec Phase 1](../../analysis/synthese/specification-v1-authentification.md)) |
| 3 | Print **public** key as the compact JWK one-liner `{"kty":"OKP","crv":"Ed25519","x":"<b64url>"}` — byte-identical to what will land in `cnf.jwk` and in every DPoP proof header | This exact string is what the SPA form expects ([platform §B5](../platform/spec.md)); zero transformation on the platform side |
| 4 | Also print the RFC 7638 thumbprint as `kid` (informational) | |

**`--force` safety check, added 2026-09-19.** Since `agent.key` is now one per machine
([contracts §9](../contracts.md)), regenerating it silently invalidates *every* mandate's PoP
binding at once — every AI client configured on this machine stops working simultaneously, not
just one. So `--force` now first enumerates `${NP_HOME}/*/config.json`, decodes each
`AGENT_DELEGATION_TOKEN`'s payload (no signature check needed — just reading claims already
trusted enough to be sitting on this disk) for its `agent_label`/`exp`, and if any exist:
```
$ npx @veritia/mcp-server init --force
Regenerating the key will break 2 existing mandate(s):
  - claude-desktop-sofie   (expires 2026-09-19 15:02)
  - claude-code-sofie      (expires 2026-09-20 09:00)
Every AI client using them will start failing with pop_key_mismatch until you mint fresh
mandates and re-run `mcp-server setup` for each. Continue? [y/N]
```
Requires an interactive `y` unless `--yes` is also passed (for scripted/non-interactive use —
the warning still prints, only the prompt is skipped). Zero mandate folders found → `--force`
proceeds exactly as before, no prompt.

### 3.1 Scenarios

| # | Case | Expected |
|---|---|---|
| O-1 | `init` twice | second run refuses (file exists) unless `--force` |
| O-1b | `init --force` with existing mandate folders under `NP_HOME`, answer `N` | aborts, key untouched, no folders touched |
| O-1c | `init --force` with existing mandate folders, answer `y` | key regenerated; mandate folders and their now-orphaned `config.json`s are left on disk untouched (still readable, just useless until re-`setup`) |
| O-1d | `init --force --yes` with existing mandate folders | warning printed to stderr, no prompt, proceeds |
| O-1e | `init --force` with zero mandate folders | proceeds exactly as before, no warning |
| O-1f | `init --show`, no key yet | refuses, same message family as runtime's O-2 ("run `mcp-server init` first") |
| O-1g | `init --show`, key exists | re-prints the same public one-liner + kid `init` printed originally; `agent.key`'s content/mtime unchanged |

Real product parity: same paths, same formats, same "refuse to overwrite," same `--force`
safety check — the POC does not diverge.

### 3.2 `--show`, added 2026-10-12

`init` only ever prints the public key at the moment it generates the keypair; run it again
later without `--force` and it just refuses, without re-printing the existing key. That's a real
gap: `agent.key` is one per machine (§9), so a human minting a *new* mandate months after their
first `init` — a different provider, say, with no existing mandate to collide with — still needs
that exact same public key, and had no supported way to get it again short of hand-decoding the
PEM file (found live 2026-10-12, chasing a `pop_key_mismatch` that turned out to be a stale/wrong
paste, not this gap directly, but the same missing capability would have made recovery harder
either way).

```
$ npx @veritia/mcp-server init --show
Public key — paste this into the mandate form:
{"kty":"OKP","crv":"Ed25519","x":"11qYAeh...Rds"}
Key id (kid / RFC 7638 thumbprint): 3s7Kd...QpM
```

Read-only — loads `agent.key` the same way `runtime` does ([`agent-key.ts`](src/agent-key.ts)),
re-derives the public JWK, and prints the *exact* same two lines a fresh `init` would have
printed (byte-identical one-liner, shared code path — see O-1g). Never writes, never touches
`agent.key`'s mtime. Refuses with the same "run `mcp-server init` first" message family if no
key exists yet. Takes priority over `--force` if both are passed (shows, doesn't regenerate).

---

## 4. Runtime mode

### 4.1 Configuration

Revised 2026-09-19 ([contracts §9](../contracts.md)) — `NP_HOME` is now machine-wide (one
`agent.key`, shared by every mandate); which mandate to run under is a **separate** selection:

| Key | Meaning |
|---|---|
| `NP_HOME` | directory holding `agent.key` and one subfolder per mandate (default `~/.veritia`) |
| `NP_MANDATE` | which subfolder's `config.json` to load — see resolution table below |
| `AGENT_DELEGATION_TOKEN` / `PROVIDER_API_ENDPOINT` | not normally set directly — these live inside the selected mandate's `config.json`, written by `setup` (§5). An env var override still wins if present, for manual testing |

`NP_MANDATE` resolution, in order:

| `NP_MANDATE` | Mandate folders found under `NP_HOME` | Result |
|---|---|---|
| unset | exactly one | use it — the common single-mandate case needs no extra config |
| unset | zero | refuse: "no mandate configured — run `mcp-server setup <url>` first" |
| unset | more than one | refuse: "multiple mandates configured — set NP_MANDATE to one of: `<list>`" |
| set to `<name>` | — | use `${NP_HOME}/<name>/config.json`; refuse if that folder doesn't exist |

Refuse to start if `agent.key` is missing/readable by others, or if the resolved
`config.json` is missing or either of its values is absent.

### 4.2 Startup — discovery

1. Open `StreamableHTTPClientTransport` to `PROVIDER_API_ENDPOINT`; MCP `initialize`.
2. `tools/list` → keep the result **verbatim** (names, descriptions, `inputSchema`,
   `annotations`).
3. Start `StdioServerTransport` toward Claude Desktop and register **exactly those** tools,
   unchanged — no hardcoded list, no filtering. New PDS tools appear with no change here.
4. If discovery fails: exit non-zero with a clear stderr message (Claude Desktop shows the
   server as failed). Do **not** serve a stale/empty tool list.

### 4.3 Per tool call (Phase 4)

| Step | Detail |
|---|---|
| 1 | Claude Desktop → stdio: `tools/call { name, arguments }` |
| 2 | Build the JSON-RPC request body for the PDS exactly as received; serialize once to bytes `B` |
| 3 | Read the private key from disk (not cached in a way that survives the process; never into logs) |
| 4 | Build the **DPoP proof JWS** per [contracts §2](../contracts.md): header `{typ:"dpop+jwt",alg:"EdDSA",jwk:<agent public JWK>}`; claims `jti`=UUIDv4, `htm`="POST", `htu`=canonical `PROVIDER_API_ENDPOINT` (no query/fragment), `iat`=now, `bsha`=`base64url(sha256(B))` |
| 5 | POST `B` to `PROVIDER_API_ENDPOINT` with headers `Authorization: DPoP <AGENT_DELEGATION_TOKEN>` + `DPoP: <proof>` + `Content-Type: application/json` |
| 6 | On `2xx`: relay the MCP result to Claude Desktop unchanged |
| 7 | On `401`/`403`: parse the `error` code from body / `WWW-Authenticate`; return an MCP tool error whose message names the reason (`token_expired`, `revoked_or_unknown`, `pop_key_mismatch`, …) so the human sees *why* |
| 8 | On network error: MCP tool error `provider_unreachable` |

`htu` is always the single canonical endpoint (same every call); the proof `jti` and `iat`
change per request. One proof per request — never reuse.

### 4.4 Scenarios

| # | Case | Expected |
|---|---|---|
| O-1 | `init` twice | second run refuses (file exists) unless `--force` |
| O-2 | runtime, key file missing | refuse to start, clear message |
| O-3 | runtime, key file world-readable | refuse to start (perm check) — **POSIX only** (`process.platform !== "win32"`): Windows/NTFS has no group/other mode bits, `fs.stat()` reports a uniform 0666/0444 there regardless of real ACLs, so the check is skipped on native Windows and the %USERPROFILE%-inherited NTFS ACL is relied on instead (found live 2026-10-09, first real native-Windows dry run — this refused to start on *every* launch before the fix, `agent-key.ts`) |
| S2 | JWT present but wrong/absent private key | PDS `403 pop_key_mismatch` → surfaced as a readable MCP error |
| S3 | expired token | PDS `401 token_expired` → readable error |
| S4 | revoked mandate | PDS `403 revoked_or_unknown` → readable error |
| O-4 | discovery fails at startup | non-zero exit, stderr message, no tools served |
| O-5 | Claude Desktop calls a tool not offered by the PDS | MCP "unknown tool" from the stdio server (never forwarded) |
| S6 | (verifies PDS) two identical forwarded requests | each call builds a fresh proof `jti`; a *verbatim* network replay is what S6 tests on the PDS side |
| O-6 | runtime, zero mandate folders under `NP_HOME`, `NP_MANDATE` unset | refuse, "run `mcp-server setup <url>` first" |
| O-7 | runtime, ≥2 mandate folders under `NP_HOME`, `NP_MANDATE` unset | refuse, lists the available folder names |
| O-8 | runtime, `NP_MANDATE=<name>` but that folder doesn't exist | refuse, names the missing folder |

### 4.5 Claude Desktop wiring

`claude_desktop_config.json` (Windows). **Primary (2026-09-25, revised from "launch via
`wsl.exe`")**: Node runs **natively on Windows**, from a Windows-native copy of
`poc-code/outil-local/` (its own `npm install && npm run build`, Windows Node) — not the WSL2
checkout. `NP_HOME`/`agent.key`/every mandate's `config.json` then live under the Windows
homedir, not WSL2's. Full rationale + setup detail: [architecture.md §12.0](../architecture.md).
**No secret in this file** — the mandate's `config.json` already holds it (§5); the client only
needs to know which mandate folder to load:
```json
{ "mcpServers": { "banque-test": {
  "command": "node",
  "args": ["C:\\Users\\<you>\\outil-local\\dist\\index.js"],
  "env": { "NP_MANDATE": "claude-desktop-sofie" }
}}}
```
It still reaches the PDS/stub at `localhost:8081`/`:3000` — WSL2 forwards those ports to
Windows. If `NP_HOME` has only ever been used for this one mandate, `NP_MANDATE` can be omitted
entirely (§4.1).

**Alternative, kept as a documented fallback, not the default**: launch through WSL2 instead,
keeping Node + the agent key file Linux-side:
```json
{ "mcpServers": { "banque-test": {
  "command": "wsl.exe",
  "args": ["-d","Ubuntu","--","node","/home/<user>/mandat/poc-code/outil-local/dist/index.js"],
  "env": { "NP_MANDATE": "claude-desktop-sofie" }
}}}
```
Reach for this only if the native-Windows path hits something unexpected (e.g. a Windows-side
`npm install` issue) close to a demo.

### 4.6 Attention points

- **stdio hygiene**: only JSON-RPC on stdout. All logs/diagnostics → stderr, or Claude Desktop
  breaks.
- Private key bytes never go to: env vars, stdout, log files, the LLM, telemetry. The only
  consumer is the in-process signer.
- The spec §6 reserve (can the "AI brain" reach the key?) is satisfied *by configuration
  here*: Claude Desktop runs each MCP server as a subprocess and the LLM can only call the
  tools a server exposes — with only this server wired, there is no filesystem/shell tool in
  reach. **Do not also configure a filesystem/shell MCP server on the demo machine.**
- One running instance ⇒ one mandate ⇒ one provider ⇒ one token. Never several mandates
  loaded into the same process, and never a fallback that guesses which one to use when more
  than one folder exists (§4.1's O-7) — see [contracts §9.4](../contracts.md) for why that was
  deliberately rejected rather than built.
- Canonicalize `htu` yourself (lowercase scheme+host, keep path, drop query/fragment) — don't
  trust the transport to hand you a canonical URL.

---

## 5. `setup` mode

The onboarding step between minting a mandate and wiring up an AI client. Fetches the token
via a one-time code instead of the human ever pasting the raw JWT into a terminal command or
hand-editing JSON, and writes it into a **named mandate folder** under the shared `NP_HOME` —
see [contracts §9](../contracts.md) for the full design rationale, including the two revisions
made 2026-09-19 (one `agent.key` per machine, not per client; no flat default folder).

```
$ npx @veritia/mcp-server setup http://localhost:3000/setup-codes/f3a8b2.../redeem
Mandate "claude-desktop-sofie" written to ~/.veritia/claude-desktop-sofie/config.json  (chmod 600)
Point your AI client at this outil-local install with NP_MANDATE=claude-desktop-sofie — see
the platform's per-client instructions. No client config needs the raw token.
```

| Step | Detail | Attention |
|---|---|---|
| 1 | Refuse if `${NP_HOME}/agent.key` doesn't exist | Same message family as runtime's O-2: "run `mcp-server init` first" — `init` runs once, ever, per machine (§9 revision 1), not once per client |
| 2 | `POST <redeem-url>` ([contracts §9.1](../contracts.md) / §5.9) — the URL is the whole argument, not a bare code; outil-local never hardcodes a platform address, so it works against any platform instance | |
| 3 | On `200`: slugify the response's `agent_label` (lowercase, non-alphanumeric → `-`, repeats collapsed) into a folder name; write `{AGENT_DELEGATION_TOKEN, PROVIDER_API_ENDPOINT}` to `${NP_HOME}/<slug>/config.json`, mode `0600`, dir `0700` — **always overwrites that one folder**, no `--force` gate | `config.json` is the replaceable half of a mandate; `agent.key` never moves. Never printed to stdout beyond a short confirmation, never logged |
| 4 | On `404 unknown_code`: refuse — "this setup link was already used, or never existed — get a new one from the platform" | |
| 5 | On `410 code_expired`: refuse — names the TTL | |
| 6 | On network error: refuse — names the endpoint, mirrors runtime's O-4 style | |

### 5.1 Scenarios

| # | Case | Expected |
|---|---|---|
| U-1 | `setup <url>` with no `agent.key` yet | refuse, "run `mcp-server init` first", exit 1 |
| U-2 | `setup <url>` with a valid, unredeemed code | `${NP_HOME}/<slug>/config.json` written, mode `0600`; prints confirmation naming the mandate folder |
| U-3 | `setup <url>` run twice with the same URL | first succeeds; second → `404 unknown_code` (already burned), exit 1 |
| U-4 | `setup <url>` past the code's TTL | `410 code_expired`, exit 1 |
| U-5 | `setup <url>`, platform unreachable | refuse, names the endpoint, exit 1 |
| U-6 | two different mandates, two different `agent_label`s, `setup` run once each | two separate folders under `NP_HOME`, both usable, `runtime` requires `NP_MANDATE` to pick between them (§4.1) |
| U-7 | a second mandate minted with the *same* `agent_label` as an existing one, then `setup <url>` for it | overwrites that one folder's `config.json` — this is expected to be rare in practice since the platform's pre-submit check (§9.4) already offered to revoke the old mandate before minting the new one |

### 5.2 Attention points

- `setup` never touches `agent.key` — only one mandate folder's `config.json`. Re-running it
  for the *same* `agent_label` (e.g. after a token expires — §4.4 scenario S3, no refresh flow
  exists) is the intended recovery path: mint a fresh mandate on the platform, get a fresh
  setup URL, re-run `setup`. The agent's identity (the key) doesn't change, only the token does.
- **One shared `agent.key` per machine, one named folder per mandate** ([contracts §9](../contracts.md),
  revised 2026-09-19 from an earlier one-keypair-per-client design that didn't survive
  scrutiny — see §9's "Revision 1" for why). Adding a second AI client no longer means
  generating a new keypair: paste the *same* already-printed public key into a new mandate
  form, `setup` the result, done. What still must stay one-per-client is the **mandate**
  (imputability and least-privilege live in the token's `jti`/`allowed_tools`/`agent_label`,
  not in the key) — `runtime` refuses to guess between several mandate folders (§4.1's O-7)
  rather than silently picking one.
- Real product parity: same files, same permissions, same "one command, one mandate" pattern —
  the POC does not diverge.
