Skip to main content
Glama
README.md
# mcp-secret-broker

A local MCP server that lets an AI agent use an API key without ever seeing it.

The agent asks for a lease: a short-lived, single-slot handle. It then asks the broker to make an HTTPS request
with that handle. The broker adds the key in its own memory, checks the host, method and path against the slot's
rules, sends the request, and censors the reply before the agent reads it. No tool returns a secret.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="diagrams/lease-flow-dark.svg">
  <img alt="The lease flow" src="diagrams/lease-flow-light.svg" width="100%">
</picture>

## At a glance

| | |
|---|---|
| What it is | A pattern, extracted and rewritten from a private tool I use with Claude Code |
| Language | Python 3.12, standard library only, no runtime dependencies |
| Size | 1,376 lines in `secret_broker/`, 775 lines of tests |
| Tests | 76 (75 run on Windows, 76 on Linux), on Windows and Ubuntu in CI |
| Platform | Windows for real use (DPAPI and native dialogs); the tests run anywhere |
| Status | 0.1.0. Small on purpose. Read the threat model before trusting it |

What it does:

- **Leases, not keys.** A lease is `lease_` plus 24 random hex characters. It is bound to one slot and the
  current epoch, lasts 1 to 30 minutes and 1 to 20 uses, and records the agent name it was issued to. The lease
  file stores only the SHA-256 of each handle.
- **Agent names are self-declared.** An MCP server cannot tell one agent from another, so the name an agent gives
  is a label, not proof. The handle is the real capability. The broker still checks that the name presented with
  a handle is the one it was issued to: that catches a handle passed between agents, or found in a log by another
  one, and records the attempt as a violation. It does not stop an agent that knows both the handle and the name.
- **Signed files with generations.** The state, the slot rules, the leases and the audit head are HMAC-signed.
  The HMAC key is sealed with DPAPI. Each signed file also carries a generation number, and a DPAPI-sealed record
  keeps the latest one for each file. An edit made outside the broker fails its signature, and a file copied back
  from an older snapshot fails its generation. Either way the broker locks itself down.
- **Strict requests.** HTTPS only. The host must be on the slot's list; a host that is not locks the broker at
  once. Methods are listed. Path prefixes match whole segments, so `/v1` never allows `/v1evil`. Encoded dots and
  double encoding are refused. Agents cannot set `Authorization`, `Cookie` or `Host`.
- **No blind redirects.** A redirect is followed (at most three hops, secret added again) only if its target passes
  the same rules. Otherwise the 3xx comes back unfollowed and the secret goes nowhere new.
- **A censor on the only way out.** Every reply line is scrubbed of every secret the store has ever held: raw,
  URL-encoded, JSON-escaped once or twice, HTML-escaped, hex, and Base64 at all three byte alignments (so
  `Basic base64("user:" + key)` is caught), then any run of 12 or more of the key's own characters. If the censor
  cannot be built, the output is withheld.
- **Epochs.** `rotate` starts a new epoch and every older lease stops working. I run it at the end of every agent
  session, so a handle copied into a transcript is dead by the time anyone reads it.
- **A circuit breaker.** Three violations in ten minutes (a wrong agent, an unknown lease, a path off the list)
  lock the broker down. Unlocking is a human-only step through the broker's own commands; see the threat model
  for what a program running as you could still do.
- **Human-only steps.** Unlocking and sealing a value each open a native Windows dialog that defaults to No.
  The value itself is typed into Windows' credential dialog, never passed as an argument or a file.
- **An audit chain.** Every issue, use, refusal and rotation is one hash-chained line, and the latest line is
  signed, so a log that was cut short or replaced is found. A missing head, a missing log, or both deleted
  together are treated as tampering: the sealed generation record remembers the head, so the broker locks down
  and the log written afterwards never passes as a fresh one.

## Using it

```sh
python -m secret_broker init                 # an empty, locked store under %LOCALAPPDATA%\secret-broker
python -m secret_broker seal example.json    # asks Yes/No, then asks Windows for the value
python -m secret_broker unlock               # asks Yes/No, showing every slot's rules
python -m secret_broker serve                # the MCP server, on stdio
python -m secret_broker rotate --reason "end of session"
python -m secret_broker audit-verify
```

`example.json` holds a slot's rules, never its value:

```json
{
  "slot_id": "example_api",
  "label": "Example API",
  "allowed_agents": ["researcher"],
  "allowed_hosts": ["api.example.com"],
  "allowed_methods": ["GET"],
  "allowed_paths": ["/v1"],
  "inject": {"kind": "bearer"}
}
```

`inject` is `bearer`, `header` (with `name`), `basic` (with `user`) or `query` (with `name`).

Register it with Claude Code as a user-scoped MCP server that runs `python -m secret_broker serve`. The tools are
`status`, `list_slots`, `request_lease`, `http_request` and `rotate`. `http_request` takes the same `agent_slug`
the lease was issued to.

Tests: `python -m pytest -q` from the repository root.

## Threat model and limits

What it is for: keeping secrets out of the places an agent's work ends up. Prompts, session transcripts, tool
results, logs, shell history, command-line arguments, git and screenshots.

What it does protect against:

- An agent that pastes a key into a file, a commit or a chat, because it never has the key.
- A reply that echoes the key back in a common encoding.
- An agent, or a prompt injection inside a fetched page, trying to send the key to another host, directly or
  through a redirect.
- A copied lease being reused later: it expires, runs out of uses, and dies at the next epoch.
- Someone editing the rules file to widen a slot: the signature fails and the broker locks.
- Copying back an older signed state or lease file to end a lockdown or revive a lease: its generation is stale
  and the broker locks.

What it does not protect against, and does not claim to:

- **Code running as you.** DPAPI seals values to your Windows account, so the blobs are useless on another
  machine or account. Any program running as you can call DPAPI too, and can import this package and pass its own
  `confirm` function. It can also send keystrokes to a dialog. The dialogs stop an agent that only has the MCP
  tools. They are not a security boundary against malware or an agent with an unrestricted shell. Pair the broker
  with tool permissions that deny the agent a general shell or file reads in the store's folder.
- **Restoring the whole folder.** The generation record lives in the same folder. Someone who copies back every
  file at once, the record included, restores a consistent older store, and the broker cannot tell. A test pins
  this limit (`test_known_limit_a_whole_folder_snapshot_is_not_caught`). Only a record they cannot roll back
  would catch it: one kept by another account, a service or a hardware counter.
- **Agent identity.** Agent names are self-declared. An agent that learns another's handle and name can use it.
- **A dishonest allowed host.** If a slot allows a host, that host receives the key. The broker cannot know what
  the host does with it.
- **Transformations the censor does not know.** A key reversed, hashed, split with other characters, encrypted or
  written out in words passes the censor. So does a fragment shorter than 12 characters.
- **Memory.** Python cannot promise its string copies are wiped. The dialog's own buffer is.
- **Side channels.** Timing, response sizes and error codes from an allowed host can still say something.

If you need a boundary against same-user code, use a separate account, a service under another identity, or a
hardware token.

## How this was made

Claude Code wrote most of the code under my direction. I set the design, made the decisions, reviewed the
results and approved each step. Nothing landed without its tests passing. This repository is a rewrite of the
pattern from a private tool. The structure and several algorithms follow the original closely (the Base64 cores,
the fragment search, the redirect loop), with new names, new tests, and the private parts removed: the private
one holds real slot names and host lists, and has a few parts left out here (below). The generation record and
the agent check on use were added here after a review of this public version by separate AI reviewer agents,
whose findings I then read and ruled on.

Left out of this public version:

- Registered runners (handing a secret to a pinned local program by environment variable or stdin).
- Provider rotation hooks (asking an upstream service for a new key).
- Rules specific to my own setup.

## Licence

MIT. See [LICENSE](LICENSE).