@agledger/mcp-server 2.10.1 → 3.0.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,64 @@ All notable changes to the AGLedger MCP Server will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [3.0.0] - 2026-10-05
8
+
9
+ Targets API 2.0 only. The major version follows the API's, and is 3 because this server is at 2.x. 2.12.0 was never published; its changes are part of this release.
10
+
11
+ ### Breaking
12
+
13
+ - **`agledger_verify` takes `requireSuppliedKeys`, not `requireOutOfBandKeys`.** A key the Server serves at `/v1/verification-keys` comes from the same database as the export, so "out of band" promised an independence the argument never gave. Behaviour is unchanged, and the old name is refused as an unknown argument. In the result, `keyProvenance.outOfBand` is `keyProvenance.supplied`, `optionalChecks` carries `key_anchoring`, and every result carries `keyTrust`.
14
+ - **`agledger_verify` reports a verdict, as `@agledger/verify` and `agledger verify` do.** `structuredContent` carries `verdict` beside verify-core's result: `trusted` when the chain is valid and `keyTrust.status` is `walked`, `failed` when it is not valid, and `unanchored` otherwise. The one text block mirrors `structuredContent` as JSON, which also carries `summary`: the verdict in the other verifiers' words (`Verdict: PASS`, `Verdict: VERIFIED, NOT ANCHORED`, `Verdict: FAIL`) with the next step, worded from `valid` and `keyTrust.status` only. `verdict` is the one `@agledger/verify-core` now puts on its result. An unanchored result says it is not a trusted verdict, and `isError` stays false for it. It is unanchored in two cases: without `trustAnchors` (`keyTrust.status` `no_anchor`), where the text names the key the export claims as its Server's (`exportMetadata.anchoredFrom`, which is not an anchor) and says to call the tool again with a pin; and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`), as for an export of unsigned entries pinned on any key. Entries that carry no signature are named as covered by the hash chain only, and agent signatures left unchecked are counted.
15
+
16
+ ### Added
17
+
18
+ - **`agledger_verify` takes `trustAnchors` and `distrustedKeys`**, through `@agledger/verify-core` 2.0.0. `trustAnchors` is the SPKI digests (`sha256:<hex>`) of vault keys the operator took out of band; the signed key statements the export carries, plus the `statements` on keys passed as `publicKeys`, are walked from them. An entry signed by a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails at position 0 with `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`; the tool description names all four, and the compile-time check that it names every export code now covers `KEY_*`. `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries; without `trustAnchors` it is refused (`INVALID_ARGUMENT`) rather than ignored, as is a malformed digest and a pinned key distrusted with no instant, which the Server refuses to start with. A pin beside a dated entry for the same key (`sha256:<hex>@<instant>`) is taken and vouches for what the key signed before the instant; an export accounts for nothing a distrusted key signed (`keyTrust.accounted` is empty), so such entries fail. Any other input verify-core refuses (a supplied key window that is not RFC 3339, an agent key that is not an Ed25519 JWK) is `INVALID_ARGUMENT` rather than `VERIFY_FAILED`. Both publish as flat string arrays. Every export vector in the API 2.0 conformance corpus was driven through the packed server over stdio, unpinned and pinned on the key the export names. Unpinned, each returned its manifest's expected result, a pass as `unanchored` and a failure as `failed` with the manifest's code. Pinned, every failing vector fails with the same code and every passing vector is `trusted`, with two exceptions that are correct: `key-substitution.json` fails `CHAIN_SIGNING_KEY_UNANCHORED` on the substituted key, and `unsigned.json`, which names no Server key and carries no signature to anchor, is `unanchored` (`no_anchored_signature`) pinned on any key.
19
+
20
+ - **`agledger_verify` names the distrust entry an export says the Server applied.** An API 2.0 export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with `distrustedFrom` in `exportMetadata.signingKeyWindows`, which verify-core reads: where that entry cut the listed retirement and the call did not pass the same `distrustedKeys` entry, the `CHAIN_KEY_WINDOW_DRIFT` (or `KEY_CLOSURE_INVALID`) finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`) to confirm with the Server's operator rather than reading as a rewritten column, says when the given entry carries another instant, and an earlier given instant is a `Key note:` in `summary`. The verdict is as before. The wording names `distrustedKeys` and `trustAnchors`, which are this tool's own argument names.
21
+ - **`agledger_verify` reports an unsigned entry written while the vault was signing.** An entry with no signing key fails with the new `CHAIN_ENTRY_UNSIGNED` when an earlier entry in its chain names a key, or when it was written at or after the earliest activation time among the keys the verifier holds. An unsigned history written before the first key stays reduced coverage, as before. An entry that names a key but carries an all-zero signature now fails `CHAIN_SIGNATURE_INVALID`. Both match the Server's own chain verification.
22
+
23
+ ### Changed
24
+
25
+ - **A timeout names the key to retry with, and `--timeout` exists.** The `TIMEOUT` error told an agent to retry the same request and to raise `--timeout`, which the binary rejected as an unknown option; the retry then created a second record, because the generated `Idempotency-Key` was never shown. A POST that times out, or whose connection fails, now returns the key it sent as `idempotencyKey` and says to retry with that exact key. A request with no key (any other method) says so rather than naming one. `--timeout <seconds>` (or `AGLEDGER_TIMEOUT`) sets the wait for each response, default 30, and anything but a positive number up to 2147483 exits 2.
26
+ - **A malformed API URL refuses startup.** An `--api-url` or `AGLEDGER_API_URL` that is not an absolute `http` or `https` URL (`not-a-url`, or `localhost:3000` with no scheme) exits 2 before the server accepts a connection, naming where the URL came from, like the other configuration refusals. It used to start, exit 0 on EOF, and leave every tool call to fail.
27
+ - `agledger_verify` walks an export's key statements in write order (`createdAt`, then `id`), which every API 2.0 export carries, so the key-anchoring findings name the statement row, and a trusted key's later admissions date its window as the Server's do. The write times decide only the order: they are not signed, so a key statement signed by a key in `distrustedKeys` counts for nothing whatever time it carries. A statement that counts for nothing only because its signer is distrusted, dated before the cutoff by the export's own unsigned write time, is a `keyTrust.notes` entry rather than a finding, so an honest rotation away from a key distrusted after it still passes pinned on its successor. The verdict text lists each note as `Key note:`.
28
+ - **A refused OIDC cert exchange reports the Server's `detail`.** API 2.0 removed the top-level `message` from every RFC 9457 error body, leaving `detail` as the one human-readable field. The exchange error read `message`, so against a 2.0 Server an expired or unbound token surfaced as "returned 401" with the Server's reason gone (mcp-server#33). It now reads `detail`. The error body is still forwarded to the tool result as the Server sent it, scrubbed of the token. The server's own errors (`{error, message, code, suggestion}`) keep their `message`; they are not API bodies.
29
+ - **The README says the Server verifies the body signature on every authenticated route** under cert auth and seals it into every chain entry the request writes, rather than recording it on some routes and ignoring it elsewhere (mcp-server#34). The server sends `X-Agent-Signature` only with the OIDC cert credential and only on a request with a body, since the Server refuses the headers with 400 under any other credential (an API key, or an admin or platform OIDC bearer).
30
+ - **`AGLEDGER_OIDC_AGENT_ID` is documented as an assertion, not a choice of agent.** The Server binds a cert to the agent the token names (a mapped `agent_id` claim, else the agent carrying the token's `oidcIss`/`oidcSub`, else an auto-provisioned one), and never to one the request body chooses. When `AGLEDGER_OIDC_AGENT_ID` names a different agent, or the token binds none, the exchange is refused with 403 `CERT_AGENT_BINDING_MISMATCH`; a token bound to a federation shadow agent is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`. `--help` and the README now say so, and point at binding the agent instead: `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub`, or `claimMapping.agent_id` on the trusted issuer. The server still sends the id when it is set, and the refusal reaches the tool result as `OIDC_EXCHANGE_FAILED` with the Server's status, error body, and `recoveryHint` as the `suggestion`, as it did before.
31
+
32
+ ## [2.11.0] - 2026-09-21
33
+
34
+ ### Added
35
+
36
+ - **`agledger_verify` refuses a re-attributed export.** The `actorId`, `actorRole` and `actorOwnerId` an export displays are signature-covered, and they are now cross-checked against the signed actor claim, so an export re-attributed to another actor fails with the new `CHAIN_ACTOR_ATTRIBUTION_MISMATCH` instead of verifying. Requires `@agledger/verify-core` 1.5.0.
37
+ - **The server can authenticate with an OIDC token instead of an API key** (#30). Set `AGLEDGER_OIDC_TOKEN_FILE` (a file holding the token, such as a Kubernetes projected service-account token) or `AGLEDGER_OIDC_TOKEN_CMD` (a shell command that prints one), plus `AGLEDGER_OIDC_AGENT_ID` if the cert should bind to a specific agent. The server generates an Ed25519 key pair in memory, exchanges the token for a short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`) and presents the cert as its bearer. No long-lived secret sits in the MCP client configuration, and nothing is written to disk. An API key still wins when one is set, then the command, then the file; the server prints a note naming any source it ignores.
38
+
39
+ - The token source is consulted on every exchange: the file is re-read and the command re-run, because the Server exchanges a given token id (`jti`) only once and a projected token is rotated on disk under a running process. A file that still holds the token already exchanged is recognised locally and not sent, so an unrotated file costs no request and no warning while the current cert is valid, and produces an error naming the rotation interval once the cert has expired.
40
+ - The cert is re-exchanged once half its lifetime has passed, measured from when it was received so clock skew cannot shorten or stretch it. Concurrent tool calls share one exchange. A refresh that fails while the current cert is still valid keeps it and prints one warning on stderr.
41
+ - A 401 on a cert bearer (a revoked cert) forces exactly one re-exchange and one retry of the request, with the same body bytes and the same `Idempotency-Key`. A second 401 is returned as the answer.
42
+ - Every request body is signed with the key bound to the cert (`X-Agent-Signature-Content-Hash` and `X-Agent-Signature`), so the Server records the agent's own signature in the chain entry (`predicate.on_behalf_of.agent_signature`) on the routes that accept one.
43
+ - A failed exchange reaches the tool result as `code: OIDC_EXCHANGE_FAILED` with the Server's status, error body and `recoveryHint`; a token source that cannot produce a token is `OIDC_TOKEN_SOURCE_FAILED`. Tokens are scrubbed from both, and a failing command's stderr is included with anything shaped like a JWT removed. The command text itself is never echoed, since it can carry a secret of its own.
44
+ - A token command (`AGLEDGER_OIDC_TOKEN_CMD`, and `AGLEDGER_ON_BEHALF_OF_CMD` below) runs in its own process group, and the whole group is killed when the command times out after 60 seconds, prints more than 64 KiB, or exits, so a pipeline or a helper it forks cannot outlive the call and pile up across refreshes in a long-running server.
45
+ - `agledger_discover` fetches `/health` without a credential, so "is the Server up" stays answerable when the credential is what is broken.
46
+ - `--help` and the no-credential startup error list all three credential sources. A token file that cannot be read exits 2 at startup rather than failing on the first tool call.
47
+
48
+ - **The server can act on behalf of a person or another party.** `AGLEDGER_ON_BEHALF_OF_CMD` (a shell command) or `AGLEDGER_ON_BEHALF_OF_FILE` names an RFC 8693 delegation token, which the server sends as `AGLedger-On-Behalf-Of` on every POST; every route that declares the header is a POST. The token comes from the process and never from a tool argument, so a model can neither read nor forge it, and `agledger_discover` reports only whether a delegation is configured and its source. The command wins over the file. A delegation token is not single use, so it is kept until its `exp` (less 30 seconds) and read again after that, or once when the Server answers 401 about the delegation, after which the request is retried a single time; an already-expired token is refused before anything is sent. It is scrubbed from every error and tool result, including a Server response that echoes it. With the OIDC cert credential the Server records the delegation `bound` to the agent's own identity; with an API key, `unbound`.
49
+
50
+ - **`agledger_verify` takes `agentKeys`**, the Ed25519 public keys (JWKs) of agent certs. An entry whose sealed agent signature names one of them by thumbprint has that signature re-verified offline, and a failure is the new `CHAIN_AGENT_SIGNATURE_INVALID`. Without it, the result counts agent signatures in `agentSignatures` without checking them. Requires `@agledger/verify-core` 1.5.0.
51
+
52
+ ### Fixed
53
+
54
+ - **An argument a tool does not declare is refused instead of dropped** (#29). `agledger_api` called with `body` in place of `params` sent the request with no payload, and the agent read the Server's `body must be object` as a problem with its payload rather than with the argument name. Each tool now answers an undeclared argument with `code: UNKNOWN_ARGUMENT`, naming the argument and the ones it accepts, before anything is sent. The published tool schemas are unchanged: required arguments stay required, every description is intact, and no `additionalProperties` keyword appears, which `tests/tool-schema.test.ts` asserts on the `tools/list` document.
55
+
56
+ - **The `agledger_api` description pointed agents at a field the Server does not send.** It said to read `suggestion` on a failed call; the Server's error bodies carry `recoveryHint`. The description and the README now name `recoveryHint` for Server errors and `suggestion` for errors the tool raises itself.
57
+
58
+ - **The `agledger_verify` description listed 16 of the 19 failure codes an audit export can produce.** `CHAIN_OIDC_ACTOR_MISMATCH`, `CHAIN_KEY_EXPIRED` and `CHAIN_KEY_NOT_YET_ACTIVE` were missing. The list is now checked against `@agledger/verify-core`'s `FailureCode` union at compile time, so a new code there fails the build here until the description carries it.
59
+
60
+ ### Changed
61
+
62
+ - `LICENSE` follows SDK License Template 1.9: section 1 says AGLedger LLC does not receive, inspect or use the data you process through your deployment and collects no product usage information from it; section 7 names AGLedger and Settlement Signal as trademarks of AGLedger LLC; section 8 refers to issued or pending U.S. patents.
63
+ - The README states what AGLedger is in current terms: agent memory, approvals, audit trail and notifications on one API and one signed ledger, self-hosted.
64
+
7
65
  ## [2.10.1] - 2026-09-10
8
66
 
9
67
  ### Changed
package/LICENSE CHANGED
@@ -17,16 +17,13 @@ Licensor grants you a limited, non-exclusive, non-transferable, revocable
17
17
  license to install and use the Software solely for the purpose of integrating
18
18
  with a self-hosted AGLedger deployment operated by you or your organization, or
19
19
  by a third party on your behalf with your authorization. The Software is not
20
- designed for, and is not licensed for use with, any AGLedger-hosted service.
21
- AGLedger operates the AGLedger software on a self-hosted model; there is no
22
- hosted AGLedger API.
20
+ licensed for use with any AGLedger-hosted service.
23
21
 
24
- AGLedger LLC operates no service in your data path. AGLedger LLC does not
25
- receive, access, inspect, or judge the records, completions, or deliverable
26
- content you process through your self-hosted deployment, and does not use any
27
- such data to train, fine-tune, evaluate, or benchmark any machine-learning or
28
- artificial-intelligence model, or to develop any product or service. AGLedger
29
- LLC receives no usage data or other data from your self-hosted deployment.
22
+ AGLedger LLC does not receive, access, inspect, or judge the data you process
23
+ through your self-hosted deployment, and does not use any such data to train,
24
+ fine-tune, evaluate, or benchmark any machine-learning or artificial-
25
+ intelligence model, or to develop any product or service. AGLedger LLC does not
26
+ collect product usage information from your self-hosted deployment.
30
27
 
31
28
  2. RESTRICTIONS
32
29
 
@@ -103,14 +100,13 @@ or trade-control laws.
103
100
 
104
101
  7. TRADEMARKS
105
102
 
106
- AGLedger is a trademark of AGLedger LLC, and Settlement Signal is a pending
107
- trademark of AGLedger LLC. All other trademarks are the property of their
108
- respective owners.
103
+ AGLedger and Settlement Signal are trademarks of AGLedger LLC. All other
104
+ trademarks are the property of their respective owners.
109
105
 
110
106
  8. PATENTS
111
107
 
112
- The Software is covered by one or more U.S. patent applications pending before
113
- the U.S. Patent and Trademark Office in AGLedger LLC's patent portfolio.
108
+ The Software is covered by one or more issued or pending U.S. patents in
109
+ AGLedger LLC's patent portfolio.
114
110
 
115
111
  9. RELATIONSHIP TO OTHER AGLEDGER AGREEMENTS
116
112
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @agledger/mcp-server
2
2
 
3
- The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API: change control for AI agents. A self-hosted notary that records every change an agent makes, signed and hash-chained, and gates the ones that matter.
3
+ The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API: change control for AI agents. Agent memory, approvals, audit trail, and notifications: one API, one signed ledger, self-hosted.
4
4
 
5
5
  Connects any MCP-compatible AI agent (Claude, Cursor, Windsurf, etc.) to the AGLedger API with 2 universal API-pass-through tools plus an offline audit verifier. No SDK code required. Just point your agent at this server.
6
6
 
@@ -35,8 +35,11 @@ Add to your MCP client configuration (e.g. `claude_desktop_config.json`):
35
35
  }
36
36
  ```
37
37
 
38
- Both flags are required. AGLedger is self-hosted, so there is no default server
39
- to call: without `--api-url` the server exits before it accepts a connection.
38
+ Both flags are required, unless an OIDC token source stands in for the key (see
39
+ [below](#authenticating-with-oidc-instead-of-an-api-key)). AGLedger is
40
+ self-hosted, so there is no default server to call: without `--api-url`, or
41
+ with one that is not an absolute `http` or `https` URL, the server exits before
42
+ it accepts a connection.
40
43
 
41
44
  Or run directly:
42
45
 
@@ -45,16 +48,122 @@ agledger-mcp --api-key <key> --api-url <url>
45
48
  ```
46
49
 
47
50
  Exit codes: `0` clean, `1` runtime failure, `2` usage or configuration error
48
- (missing flag, unknown flag), so a launcher can tell a misconfiguration from a
51
+ (missing flag, unknown flag, an API URL that is not an `http(s)` URL), so a launcher can tell a misconfiguration from a
49
52
  crash.
50
53
 
54
+ ## Authenticating with OIDC instead of an API key
55
+
56
+ When the operator of your AGLedger Server has registered your identity
57
+ provider as a trusted issuer for agents, the MCP server can run with no API key
58
+ at all. Give it a source of OIDC tokens instead. It exchanges a token for a
59
+ short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`), presents the
60
+ cert as its bearer, and signs each request body with an Ed25519 key that exists
61
+ only in its own memory. The Server verifies that signature and seals it into
62
+ every chain entry the agent writes (`predicate.on_behalf_of.agent_signature`).
63
+ Nothing is written to disk.
64
+
65
+ | Env var | Description |
66
+ |---------|-------------|
67
+ | `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, such as a Kubernetes projected service-account token. Read on every exchange, so a token rotated on disk is picked up. |
68
+ | `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT. Run on every exchange. |
69
+ | `AGLEDGER_OIDC_AGENT_ID` | Optional. An assertion of the agent id the token binds to, sent on the exchange. It never chooses the agent: when it names a different one, or the token binds none, the Server refuses the exchange with 403 `CERT_AGENT_BINDING_MISMATCH` rather than issue a cert for an agent you did not expect. Leave it unset unless you want that check. |
70
+
71
+ An API key wins when one is set, then the command, then the file.
72
+
73
+ **The token decides which agent the cert binds to**, never the MCP server's
74
+ configuration. An administrator binds an agent to the token's identity in one
75
+ of two ways: `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's
76
+ issuer and subject), or a `claimMapping` of `agent_id` on the trusted issuer,
77
+ which reads the agent id from a claim in the token. An issuer that
78
+ auto-provisions agents creates one for an unbound subject instead. A token that
79
+ binds no agent is refused, and the Server's `recoveryHint` says which binding is
80
+ missing. A token bound to a federation shadow agent (one listed at
81
+ `GET /v1/peer-agents`) is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that
82
+ agent authenticates on its own Server.
83
+
84
+ ```bash
85
+ AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
86
+ agledger-mcp --api-url https://your-agledger-instance
87
+ ```
88
+
89
+ In an MCP client configuration, the token source goes in `env`:
90
+
91
+ ```json
92
+ {
93
+ "mcpServers": {
94
+ "agledger": {
95
+ "command": "agledger-mcp",
96
+ "args": ["--api-url", "https://your-agledger-instance"],
97
+ "env": { "AGLEDGER_OIDC_TOKEN_FILE": "/var/run/secrets/agledger/token" }
98
+ }
99
+ }
100
+ }
101
+ ```
102
+
103
+ The cert is re-exchanged once half its lifetime has passed, and once more if
104
+ the Server answers 401 (a revoked cert), after which the request is retried a
105
+ single time. A refresh that fails while the current cert is still valid keeps
106
+ the current cert and prints one warning on stderr. When the exchange itself is
107
+ refused, the tool result carries `code: OIDC_EXCHANGE_FAILED`, the Server's
108
+ status and error body, and its `recoveryHint` as the result's `suggestion`.
109
+
110
+ The Server exchanges a token id (`jti`) only once, so every exchange needs a
111
+ new token. A command runs on every exchange; a file is read on every exchange,
112
+ and while it still holds the token already exchanged, the server keeps using
113
+ the current cert rather than asking. The kubelet rewrites a projected token at
114
+ 80% of `expirationSeconds`, so keep that interval shorter than the trusted
115
+ issuer's `maxCredentialTtlSeconds`, or the cert expires before a new token
116
+ appears:
117
+
118
+ ```yaml
119
+ volumes:
120
+ - name: agledger-token
121
+ projected:
122
+ sources:
123
+ - serviceAccountToken:
124
+ audience: agledger
125
+ expirationSeconds: 600
126
+ path: token
127
+ ```
128
+
129
+ ## Acting on behalf of someone
130
+
131
+ When the agent does work for a person or another party rather than for
132
+ itself, the operator can give the server an RFC 8693 delegation token: the
133
+ token-exchange result your IdP issues, whose `act` claim names the agent. The
134
+ server sends it as the `AGLedger-On-Behalf-Of` header on every POST, and the
135
+ Server validates it against a trusted issuer registered with
136
+ `appliesTo: principal` and seals it into the chain entry as
137
+ `predicate.on_behalf_of`. The token comes from the process, never from a tool
138
+ argument, so the model can neither read nor choose it; `agledger_discover`
139
+ reports only whether a delegation is configured and where it comes from.
140
+
141
+ | Env var | Description |
142
+ |---------|-------------|
143
+ | `AGLEDGER_ON_BEHALF_OF_CMD` | A shell command whose stdout is the delegation token. Wins over the file. |
144
+ | `AGLEDGER_ON_BEHALF_OF_FILE` | A file holding the delegation token. |
145
+
146
+ ```bash
147
+ AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
148
+ AGLEDGER_ON_BEHALF_OF_FILE=/var/run/secrets/agledger/on-behalf-of \
149
+ agledger-mcp --api-url https://your-agledger-instance
150
+ ```
151
+
152
+ A delegation token is not single use, so it is kept until its `exp` and read
153
+ again after that, or when the Server refuses it with a 401 that names the
154
+ delegation (the request is then retried once). With the OIDC cert credential
155
+ the delegation is recorded `bound`: the token's `act.sub` and actor issuer must
156
+ be the cert's own subject and issuer, or the Server answers 403
157
+ `ACTOR_BINDING_MISMATCH`. With an API key there is no validated caller identity
158
+ to compare, and it is recorded `unbound`.
159
+
51
160
  ## Tools
52
161
 
53
162
  | Tool | Description |
54
163
  |------|-------------|
55
164
  | `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
56
165
  | `agledger_api` | Make any AGLedger API call (method, path, params). Every POST carries a generated `Idempotency-Key`; pass `idempotencyKey` to reuse the first attempt's key when retrying a call that may already have landed. The API returns `nextSteps` on every response for self-guided workflow discovery. |
57
- | `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns `valid`, `verifiedEntries`, and a `brokenAt` pointer with a canonical failure `code` on failure. Pass `publicKeys` to supply keys out of band and `requireOutOfBandKeys` for an independent audit that refuses the export's embedded keys. Built on the shared `@agledger/verify-core`. |
166
+ | `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns the verifier's result as one JSON text block (the same object as `structuredContent`), with `summary` stating the verdict and the next step. Pass `trustAnchors` (`["sha256:<digest>"]`, the SPKI digest of a vault key the operator took out of band; the installer prints the first one) so the export's signed key statements are walked from a key you trust: an entry under a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`. The result carries `verdict`: `trusted` (text `Verdict: PASS`) only when the chain is valid and the walk reached a signature, `failed` (`Verdict: FAIL`), or `unanchored` (`Verdict: VERIFIED, NOT ANCHORED`), which is not a trusted verdict. A run is unanchored without `trustAnchors` (`keyTrust.status` `no_anchor`, the keys taken on the export's word) and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`, as for an export of unsigned entries). `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries and needs `trustAnchors`, and a key both pinned and distrusted is refused (`INVALID_ARGUMENT`), as the Server refuses to start with it; a key statement a distrusted key signed counts for nothing at any instant, because the write times an export carries are not signed. Where an export lists a key retired at the instant the Server distrusts it from (`distrustedFrom`), earlier than its signed retirement, a pinned call without the same `distrustedKeys` entry fails on that key's window (`CHAIN_KEY_WINDOW_DRIFT`, or `KEY_CLOSURE_INVALID` where no closure retires it), and the finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`), the listing's unsigned word, to confirm with the operator before passing it. `publicKeys` supplies keys (the `GET /v1/verification-keys` response works as is), `requireSuppliedKeys` refuses the export's embedded keys, and `agentKeys` (the agents' cert public keys as JWKs) re-verifies the agent signatures sealed in the chain. Input verify-core refuses, such as a supplied key window that is not RFC 3339, is `INVALID_ARGUMENT`. Built on the shared `@agledger/verify-core`. |
58
167
 
59
168
  ## Resources
60
169
 
@@ -74,18 +183,21 @@ The `agledger_discover` tool returns a quickstart workflow that guides agents th
74
183
  3. `POST /v1/records` -- create a record
75
184
  4. `POST /v1/records/{id}/completions` -- submit a completion (evidence) when done
76
185
 
77
- Every API error response includes a `suggestion` field with actionable recovery guidance -- agents can self-correct without human intervention.
186
+ Every API error response includes a `recoveryHint` naming the fix, so an agent can correct itself without a human. Errors raised by the MCP server itself (an argument the tool does not declare, a timeout, a credential failure) carry a `code` and a `suggestion` instead.
78
187
 
79
188
  ## Configuration
80
189
 
81
190
  | Flag | Env Var | Description |
82
191
  |------|---------|-------------|
83
- | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key (required) |
192
+ | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key. Required unless an OIDC token source is set (see above). |
84
193
  | `--api-url` | `AGLEDGER_API_URL` | API base URL of your instance (required). AGLedger is self-hosted, so there is no default; the server refuses to start without it. |
194
+ | `--timeout` | `AGLEDGER_TIMEOUT` | Seconds to wait for each API response (default 30). A positive number up to 2147483; anything else exits 2. |
195
+
196
+ A call that times out may still have been applied. On a POST, the `TIMEOUT` error carries the `idempotencyKey` that was sent: retry with exactly that key and the Server returns the original result instead of creating a second record. Reads and other methods carry no key.
85
197
 
86
198
  ## What is AGLedger?
87
199
 
88
- AGLedger is the accountability layer for automated operations. It notarizes what was agreed to, by whom, and when, and tracks the delegation of that agreement through other systems.
200
+ AGLedger is change control for AI agents, delivered as a signed ledger for agentic work. Agents notarize what they intended and what they did, principals approve the work that needs a decision, and every entry is signed, hash-chained and verifiable offline.
89
201
 
90
202
  - **Records** -- structured commitments with acceptance criteria and tolerance bands
91
203
  - **Completions** -- performer evidence recording what was reported to be done
@@ -99,7 +211,7 @@ Each self-hosted AGLedger instance also serves interactive Swagger UI at `{AGLED
99
211
  ## Requirements
100
212
 
101
213
  - Node.js >= 24
102
- - A running self-hosted AGLedger API instance and an API key (see the self-hosted install guide at [agledger.ai](https://www.agledger.ai))
214
+ - A running self-hosted AGLedger API instance, and an API key or a trusted OIDC issuer (see the self-hosted install guide at [agledger.ai](https://www.agledger.ai))
103
215
 
104
216
  ## License
105
217
 
@@ -1,16 +1,33 @@
1
+ import { type Credential } from './credentials.js';
2
+ import { type DelegationSource } from './delegation.js';
1
3
  export interface ApiResponse {
2
4
  status: number;
3
5
  body: unknown;
4
6
  ok: boolean;
5
7
  }
8
+ export interface RequestOptions {
9
+ query?: Record<string, unknown>;
10
+ body?: unknown;
11
+ idempotencyKey?: string;
12
+ /** Send no credential. For public routes whose answer must not depend on the credential working (`/health`). */
13
+ anonymous?: boolean;
14
+ }
6
15
  export declare class ApiClient {
7
16
  private readonly apiUrl;
8
- private readonly apiKey;
17
+ private readonly credential;
9
18
  private readonly timeoutMs;
10
- constructor(apiUrl: string, apiKey: string, timeoutMs?: number);
11
- request(method: string, path: string, options?: {
12
- query?: Record<string, unknown>;
13
- body?: unknown;
14
- idempotencyKey?: string;
15
- }): Promise<ApiResponse>;
19
+ private readonly delegation;
20
+ /**
21
+ * `credential` is an API key string or a {@link Credential} (e.g. an OIDC
22
+ * cert credential). `delegation`, when set, supplies the
23
+ * `AGLedger-On-Behalf-Of` token attached to every POST.
24
+ */
25
+ constructor(apiUrl: string, credential: string | Credential, timeoutMs?: number, delegation?: DelegationSource);
26
+ /** Where the delegation token comes from, or undefined when none is configured. Never the token. */
27
+ get delegationOrigin(): string | undefined;
28
+ request(method: string, path: string, options?: RequestOptions): Promise<ApiResponse>;
29
+ /** The delegation token never comes back to a tool, even if the Server echoes it. */
30
+ private scrubbed;
31
+ private postAnonymous;
32
+ private send;
16
33
  }
@@ -1,4 +1,7 @@
1
+ import { ApiKeyCredential, cutSecret } from './credentials.js';
2
+ import { namesDelegation, ON_BEHALF_OF_HEADER } from './delegation.js';
1
3
  import { SERVER_VERSION } from './version.js';
4
+ const USER_AGENT = `agledger-mcp-server/${SERVER_VERSION}`;
2
5
  // Strip trailing slashes with a single linear scan. A regex like /\/+$/ is
3
6
  // O(n^2) on inputs of many slashes (CodeQL js/polynomial-redos); this is O(n).
4
7
  function stripTrailingSlashes(s) {
@@ -43,19 +46,30 @@ function appendQueryParam(search, key, value) {
43
46
  }
44
47
  export class ApiClient {
45
48
  apiUrl;
46
- apiKey;
49
+ credential;
47
50
  timeoutMs;
48
- constructor(apiUrl, apiKey, timeoutMs = 30_000) {
51
+ delegation;
52
+ /**
53
+ * `credential` is an API key string or a {@link Credential} (e.g. an OIDC
54
+ * cert credential). `delegation`, when set, supplies the
55
+ * `AGLedger-On-Behalf-Of` token attached to every POST.
56
+ */
57
+ constructor(apiUrl, credential, timeoutMs = 30_000, delegation) {
49
58
  this.apiUrl = stripTrailingSlashes(apiUrl);
50
- this.apiKey = apiKey;
59
+ this.credential = typeof credential === 'string' ? new ApiKeyCredential(credential) : credential;
51
60
  this.timeoutMs = timeoutMs;
61
+ this.delegation = delegation;
62
+ }
63
+ /** Where the delegation token comes from, or undefined when none is configured. Never the token. */
64
+ get delegationOrigin() {
65
+ return this.delegation?.origin;
52
66
  }
53
67
  async request(method, path, options) {
54
68
  const url = new URL(path, this.apiUrl);
55
69
  // Defense-in-depth: pin every request to the configured API origin. A
56
70
  // protocol-relative or absolute `path` (e.g. `//evil.com/x`,
57
71
  // `https://evil.com`) resolves against the base to a different origin, which
58
- // would leak the `Authorization: Bearer <apiKey>` header off-host. No caller
72
+ // would leak the `Authorization: Bearer` header off-host. No caller
59
73
  // may steer the client off-origin.
60
74
  if (url.origin !== new URL(this.apiUrl).origin) {
61
75
  throw new Error(`Refusing to send request off-origin: path "${path}" resolves to ${url.origin}, expected ${new URL(this.apiUrl).origin}.`);
@@ -68,40 +82,90 @@ export class ApiClient {
68
82
  }
69
83
  }
70
84
  const headers = {
71
- Authorization: `Bearer ${this.apiKey}`,
72
85
  Accept: 'application/json',
73
- 'User-Agent': `agledger-mcp-server/${SERVER_VERSION}`,
86
+ 'User-Agent': USER_AGENT,
74
87
  };
75
- if (options?.body !== undefined) {
88
+ // Serialized once. The agent signature covers these exact bytes, and a
89
+ // 401 retry resends them, so the body must never be re-stringified.
90
+ const body = options?.body !== undefined ? JSON.stringify(options.body) : undefined;
91
+ if (body !== undefined) {
76
92
  headers['Content-Type'] = 'application/json';
77
93
  }
78
94
  // POST is the only method the API arms for idempotency: all 18 routes that
79
95
  // declare `idempotent: true` are POST, and on any other method the header is
80
96
  // ignored. A generated key makes each write replay-safe by default. An agent
81
97
  // that retries a tool call after a timeout passes the key it used the first
82
- // time, so the retry dedups instead of notarizing the same work twice.
98
+ // time, so the retry dedups instead of notarizing the same work twice. The
99
+ // 401 retry below reuses the same key for the same reason.
83
100
  if (method.toUpperCase() === 'POST') {
84
101
  headers['Idempotency-Key'] = options?.idempotencyKey ?? crypto.randomUUID();
85
102
  }
103
+ if (options?.anonymous) {
104
+ return this.send(url, method, headers, body);
105
+ }
106
+ // A cert credential signs the body with the key bound to its cert. Under
107
+ // cert auth the Server verifies the signature on every authenticated route
108
+ // and seals it into every chain entry the request writes; under any other
109
+ // credential it refuses the headers with 400, so only a cert credential
110
+ // (the one with signBody) sends them, and only with a body.
111
+ if (body !== undefined && this.credential.signBody) {
112
+ Object.assign(headers, this.credential.signBody(body));
113
+ }
114
+ // Every route that declares AGLedger-On-Behalf-Of is a POST.
115
+ let onBehalfOf = this.delegation && method.toUpperCase() === 'POST' ? await this.delegation.token() : undefined;
116
+ const withDelegation = (h) => onBehalfOf ? { ...h, [ON_BEHALF_OF_HEADER]: onBehalfOf } : h;
117
+ const ctx = { postAnonymous: (p, b) => this.postAnonymous(p, b) };
118
+ let bearer = await this.credential.bearer(ctx);
119
+ const first = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
120
+ if (first.status !== 401)
121
+ return this.scrubbed(first, onBehalfOf);
122
+ // At most one retry, renewing whichever credential the 401 is about. A
123
+ // delegation token is re-read only when the Server names it; otherwise a
124
+ // cert can be revoked or expire server-side before our clock says so, and
125
+ // gets exactly one re-exchange. A second 401 is the answer.
126
+ if (onBehalfOf && namesDelegation(first.body)) {
127
+ const refused = onBehalfOf;
128
+ onBehalfOf = await this.delegation.token(refused);
129
+ if (onBehalfOf === refused)
130
+ return this.scrubbed(first, refused);
131
+ }
132
+ else if (this.credential.renewable) {
133
+ bearer = await this.credential.bearer({ ...ctx, rejected: bearer });
134
+ }
135
+ else {
136
+ return this.scrubbed(first, onBehalfOf);
137
+ }
138
+ const second = await this.send(url, method, withDelegation({ ...headers, Authorization: `Bearer ${bearer}` }), body);
139
+ return this.scrubbed(second, onBehalfOf);
140
+ }
141
+ /** The delegation token never comes back to a tool, even if the Server echoes it. */
142
+ scrubbed(res, onBehalfOf) {
143
+ return onBehalfOf ? { ...res, body: cutSecret(res.body, onBehalfOf) } : res;
144
+ }
145
+ async postAnonymous(path, payload) {
146
+ const res = await this.send(new URL(path, this.apiUrl), 'POST', { Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': USER_AGENT }, JSON.stringify(payload));
147
+ return { status: res.status, body: res.body };
148
+ }
149
+ async send(url, method, headers, body) {
86
150
  const controller = new AbortController();
87
151
  const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
88
152
  try {
89
153
  const res = await fetch(url.toString(), {
90
154
  method,
91
155
  headers,
92
- body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
156
+ body,
93
157
  signal: controller.signal,
94
158
  });
95
159
  const contentType = res.headers.get('content-type') ?? '';
96
- let body;
160
+ let parsed;
97
161
  if (contentType.includes('json')) {
98
- body = await res.json();
162
+ parsed = await res.json();
99
163
  }
100
164
  else {
101
165
  const text = await res.text();
102
- body = { _raw: text, _contentType: contentType };
166
+ parsed = { _raw: text, _contentType: contentType };
103
167
  }
104
- return { status: res.status, body, ok: res.ok };
168
+ return { status: res.status, body: parsed, ok: res.ok };
105
169
  }
106
170
  finally {
107
171
  clearTimeout(timeout);
@@ -0,0 +1,144 @@
1
+ /**
2
+ * How the server authenticates to the AGLedger API.
3
+ *
4
+ * Two shapes. An API key is a static bearer. An OIDC cert credential exchanges
5
+ * a customer IdP token for a short-lived, Server-signed cert
6
+ * (`POST /v1/auth/oidc/cert`), re-exchanges before the cert runs out, and signs
7
+ * request bodies with the key bound to it.
8
+ *
9
+ * Nothing here writes to disk. The Ed25519 key pair lives in memory for the
10
+ * life of one credential (one server process) and the cert is cached in memory
11
+ * only. The token source is called for EVERY exchange: the Server refuses a
12
+ * token id it has already exchanged (409), and a projected Kubernetes token is
13
+ * rotated on disk underneath a running process, so a token is never reused.
14
+ *
15
+ * No token, cert or key ever reaches an error message, a log line or tool
16
+ * output. Server error bodies and token-command stderr are scrubbed before
17
+ * they are surfaced, because either can echo a token back.
18
+ */
19
+ /** The env vars the server reads a token source from. The CLI reads the same names. */
20
+ export declare const OIDC_ENV: {
21
+ readonly TOKEN_CMD: 'AGLEDGER_OIDC_TOKEN_CMD';
22
+ readonly TOKEN_FILE: 'AGLEDGER_OIDC_TOKEN_FILE';
23
+ readonly AGENT_ID: 'AGLEDGER_OIDC_AGENT_ID';
24
+ };
25
+ /** Replace anything shaped like a JWT with a placeholder. */
26
+ export declare function redactTokens(text: string): string;
27
+ /**
28
+ * Deep-copy a JSON value with every string passed through `redactTokens`, and
29
+ * any occurrence of `secret` cut out. The Server's validation errors echo the
30
+ * offending input back, which on the exchange route is the OIDC token.
31
+ */
32
+ export declare function scrub(value: unknown, secret?: string): unknown;
33
+ /**
34
+ * Deep-copy a JSON value with every occurrence of `secret` cut out, and
35
+ * nothing else touched. For API responses, which may legitimately carry other
36
+ * JWT-shaped values (an agent can call the exchange route itself).
37
+ */
38
+ export declare function cutSecret(value: unknown, secret: string): unknown;
39
+ /** The token source could not produce a usable token. */
40
+ export declare class OidcTokenSourceError extends Error {
41
+ readonly unrotated: boolean;
42
+ readonly code = "OIDC_TOKEN_SOURCE_FAILED";
43
+ /** @param unrotated the source returned the token it returned last time, which is expected for a file between rotations */
44
+ constructor(message: string, unrotated?: boolean);
45
+ }
46
+ /** The Server refused the exchange. `body` is its error response, scrubbed. */
47
+ export declare class OidcExchangeError extends Error {
48
+ readonly status: number;
49
+ readonly body: unknown;
50
+ readonly code = "OIDC_EXCHANGE_FAILED";
51
+ constructor(message: string, status: number, body: unknown);
52
+ /** The Server's own recovery guidance, when its error body carries one. */
53
+ get recoveryHint(): string | undefined;
54
+ }
55
+ /** A function returning a fresh compact OIDC JWT. Called once per exchange. */
56
+ export type OidcTokenGetter = () => string | Promise<string>;
57
+ /** Reads a token file on every call. Kubernetes rotates projected tokens on disk. */
58
+ export declare function oidcTokenFromFile(path: string, origin?: string): OidcTokenGetter;
59
+ export interface TokenCommandOptions {
60
+ /** Kill the command after this long. Default 60s. */
61
+ timeoutMs?: number;
62
+ /** Refuse more stdout than this. Default 64 KiB; a JWT is a few KiB at most. */
63
+ maxStdoutBytes?: number;
64
+ }
65
+ /**
66
+ * Runs a shell command on every call; its stdout is the token. The command
67
+ * runs in its own process group, which is killed on timeout, on oversized
68
+ * output, and after it exits, so nothing it started outlives the call. The
69
+ * command text is never echoed back, since it can carry a secret of its own.
70
+ */
71
+ export declare function oidcTokenFromCommand(command: string, origin?: string, options?: TokenCommandOptions): OidcTokenGetter;
72
+ /**
73
+ * Validate a compact JWT's shape and return its unverified payload. The Server
74
+ * verifies the signature. Errors never quote the token.
75
+ */
76
+ export declare function jwtPayloadOf(token: string, origin: string): Record<string, unknown>;
77
+ /** What the API client hands a credential when it needs a bearer. */
78
+ export interface CredentialContext {
79
+ /** POST a JSON body without any credential attached. Used for the exchange. */
80
+ postAnonymous(path: string, body: unknown): Promise<{
81
+ status: number;
82
+ body: unknown;
83
+ }>;
84
+ /**
85
+ * The bearer that just drew a 401, when this call is the retry. A credential
86
+ * that has already moved past it returns the newer bearer instead of
87
+ * exchanging again, so concurrent 401s cost one exchange, not one each.
88
+ */
89
+ rejected?: string;
90
+ }
91
+ export interface Credential {
92
+ /** Bearer value for the next request. */
93
+ bearer(ctx: CredentialContext): Promise<string>;
94
+ /** True when a 401 should force a re-exchange and one retry. */
95
+ readonly renewable: boolean;
96
+ /** Extra headers that attest to a request body, exactly as it will be sent. */
97
+ signBody?(body: string): Record<string, string>;
98
+ }
99
+ export declare class ApiKeyCredential implements Credential {
100
+ private readonly apiKey;
101
+ readonly renewable = false;
102
+ constructor(apiKey: string);
103
+ bearer(): Promise<string>;
104
+ }
105
+ export interface OidcCertCredentialOptions {
106
+ /** Returns a fresh OIDC JWT. Called once per exchange, never cached. */
107
+ getOidcToken: OidcTokenGetter;
108
+ /**
109
+ * Optional assertion of the agent the token binds to, sent on the exchange.
110
+ * The token decides the agent; the Server refuses a mismatch with 403
111
+ * CERT_AGENT_BINDING_MISMATCH rather than bind a different one.
112
+ */
113
+ agentId?: string;
114
+ /** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
115
+ refreshFraction?: number;
116
+ /** Names the token source in errors, e.g. `AGLEDGER_OIDC_TOKEN_FILE`. */
117
+ origin?: string;
118
+ /** Receives one line when a refresh fails while the current cert is still valid. Never a token. */
119
+ onWarning?: (message: string) => void;
120
+ /** Injectable clock, for tests. */
121
+ now?: () => number;
122
+ }
123
+ export declare class OidcCertCredential implements Credential {
124
+ readonly renewable = true;
125
+ private readonly getOidcToken;
126
+ private readonly agentId;
127
+ private readonly refreshFraction;
128
+ private readonly origin;
129
+ private readonly onWarning;
130
+ private readonly now;
131
+ private readonly privateKey;
132
+ private readonly publicX;
133
+ private cert;
134
+ private inflight;
135
+ private lastWarned;
136
+ /** The last token the Server accepted. A token carrying a `jti` is exchangeable once. */
137
+ private lastExchangedToken;
138
+ constructor(options: OidcCertCredentialOptions);
139
+ bearer(ctx: CredentialContext): Promise<string>;
140
+ signBody(body: string): Record<string, string>;
141
+ /** Single-flight: concurrent callers share one exchange. */
142
+ private exchange;
143
+ private runExchange;
144
+ }