@agledger/mcp-server 2.11.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,330 +4,295 @@ 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
- ## [2.11.0] - 2026-09-21
7
+ ## [3.1.0] - 2026-11-05
8
8
 
9
9
  ### Added
10
10
 
11
- - **`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.
12
- - **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.
11
+ - **`agledger_verify` re-binds inlined evidence.** On an export fetched with `?evidence=true`, each completion's evidence body and each dispute's filed payload is hashed (SHA-256 over RFC 8785) against the hash its entry signs; an edited body fails `CHAIN_EVIDENCE_BINDING_MISMATCH` where it used to pass. `result.evidenceBinding` counts them, the summary names a failed or encrypted-mode body, and the tool description says how to fetch the export with its evidence. Built on `@agledger/verify-core` 2.1.0.
12
+ - **`federationKeys` on `agledger_verify`:** verifies the peer messages a receiving Server seals from federation, against the keys you supply. `result.federationWire` reports `present`, `verified`, `failed` and `afterRetirement` counts, and a failure is `CHAIN_FEDERATION_WIRE_INVALID`. An array entry's `history`, the peer's `GET /.well-known/agledger-federation-keys.json`, trusts every key it links to that entry's key, so entries sealed before the peer changed its federation key verify; each message is placed by its signed `wire.timestamp`, and a hub may be named again for a key the history does not list. Requires `@agledger/verify-core` 2.1.0.
13
13
 
14
- - 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.
15
- - 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.
16
- - 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.
17
- - 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.
18
- - 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.
19
- - 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.
20
- - `agledger_discover` fetches `/health` without a credential, so "is the Server up" stays answerable when the credential is what is broken.
21
- - `--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.
14
+ ### Fixed
22
15
 
23
- - **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`.
16
+ - The `agledger_api` description now states that listing pages, `GET /v1/schemas` and `GET /v1/admin/orgs` carry no `nextSteps`, and that the discovery documents and `/a2a` sit at the root rather than under `/v1/`.
24
17
 
25
- - **`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.
18
+ ### Changed
26
19
 
27
- ### Fixed
20
+ - The README states that the package needs an AGLedger Server 2.0 or later and names the last release for a 1.x Server.
28
21
 
29
- - **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.
22
+ ## [3.0.0] - 2026-10-05
30
23
 
31
- - **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.
24
+ Targets API 2.0 only.
32
25
 
33
- - **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.
26
+ ### Breaking
34
27
 
35
- ### Changed
28
+ - **`agledger_verify` takes `requireSuppliedKeys`, not `requireOutOfBandKeys`.** Behavior is unchanged, but the old name is refused as an unknown argument. In the result, `keyProvenance.outOfBand` is now `keyProvenance.supplied`, `optionalChecks` carries `key_anchoring`, and every result carries `keyTrust`.
29
+ - **`agledger_verify` reports a verdict, as `@agledger/verify` and `agledger verify` do.** `structuredContent` carries `verdict`: `trusted` when the chain is valid and `keyTrust.status` is `walked`, `failed` when it is not valid, and `unanchored` otherwise. The text block mirrors `structuredContent` as JSON and adds a `summary` (`Verdict: PASS`, `Verdict: VERIFIED, NOT ANCHORED` or `Verdict: FAIL`) with the next step. An unanchored result is not a trusted verdict and `isError` stays false for it. Pass `trustAnchors` to get a trusted verdict.
36
30
 
37
- - `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.
38
- - 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.
31
+ ### Added
39
32
 
40
- ## [2.10.1] - 2026-09-10
33
+ - **`trustAnchors` and `distrustedKeys` on `agledger_verify`.** `trustAnchors` takes SPKI digests (`sha256:<hex>`) of vault keys you obtained out of band, and the signed key statements in the export 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 with `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`. `distrustedKeys` takes your `VAULT_DISTRUSTED_KEYS` entries and requires `trustAnchors`; a pin may carry a date (`sha256:<hex>@<instant>`) to vouch for what the key signed before that instant. Invalid input is refused with `INVALID_ARGUMENT`. Requires `@agledger/verify-core` 2.0.0.
34
+ - **`agledger_verify` names the distrust entry an export says the Server applied.** When an API 2.0 export lists a distrusted key and your call did not pass the matching `distrustedKeys` entry, the `CHAIN_KEY_WINDOW_DRIFT` or `KEY_CLOSURE_INVALID` finding names the entry to confirm with the Server's operator.
35
+ - **`agledger_verify` reports an unsigned entry written while the vault was signing.** Such an entry fails with the new `CHAIN_ENTRY_UNSIGNED`, and an entry that names a key but carries an all-zero signature fails `CHAIN_SIGNATURE_INVALID`. Both match the Server's own chain verification.
41
36
 
42
37
  ### Changed
43
38
 
44
- - **LICENSE section 6 names the ciphers this package line ships**: Ed25519 (EdDSA), ECDSA P-256 with SHA-256, HMAC-SHA-256, AES-256-GCM, HKDF-SHA-256 and SHA-256. X25519 is gone from the list with the federation encryption key the engine no longer has. The LICENSE file is the only shipped byte that moved.
39
+ - **A timeout returns the key to retry with, and `--timeout` exists.** A POST that times out or loses its connection returns the `Idempotency-Key` it sent as `idempotencyKey`; retry with that exact key to avoid creating a second record. `--timeout <seconds>` (or `AGLEDGER_TIMEOUT`) sets the wait for each response, default 30; anything other than a positive number up to 2147483 exits 2.
40
+ - **A malformed API URL refuses startup.** An `--api-url` or `AGLEDGER_API_URL` that is not an absolute `http` or `https` URL exits 2 before the server accepts a connection, and names where the URL came from.
41
+ - `agledger_verify` walks an export's key statements in write order (`createdAt`, then `id`). A statement that counts for nothing only because its signer is distrusted and dated before the cutoff is reported as a `keyTrust.notes` entry (`Key note:` in the verdict text) rather than a finding.
42
+ - **A refused OIDC cert exchange reports the Server's `detail`.** API 2.0 error bodies carry `detail` rather than a top-level `message`, and the exchange error now reads it.
43
+ - **Documentation: body signatures under cert auth.** The README states that the Server verifies the body signature on every authenticated route under cert auth and seals it into each chain entry the request writes. The server sends `X-Agent-Signature` only with the OIDC cert credential and only on a request with a body.
44
+ - **Documentation: `AGLEDGER_OIDC_AGENT_ID` is an assertion, not a choice of agent.** The Server binds a cert to the agent the token names. If `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`. Bind the agent with `PATCH /v1/agents/{id}` (`oidcIss` and `oidcSub`) or `claimMapping.agent_id` on the trusted issuer.
45
45
 
46
- ## [2.10.0] - 2026-08-21
46
+ ## [2.11.0] - 2026-09-21
47
47
 
48
48
  ### Added
49
49
 
50
- - **An `idempotencyKey` argument on `agledger_api`, and a generated key on every POST.** The server could not send an `Idempotency-Key` at all, so an agent retrying a tool call after a timeout notarized the same work twice. Every POST now carries a generated key, which makes a single call replay-safe on its own. An agent retrying a call that may already have reached the Server passes the key it used the first time, and the Server returns the original result instead of creating a second record. The key binds to method, route and body, so a retry that changes the body is rejected rather than silently replaying the old response. Scoped to POST because that is what the engine arms: all 18 routes that opt into idempotency are POST, and the header is ignored elsewhere.
50
+ - **`agledger_verify` refuses a re-attributed export.** The `actorId`, `actorRole` and `actorOwnerId` an export displays are cross-checked against the signed actor claim, and a mismatch fails with the new `CHAIN_ACTOR_ATTRIBUTION_MISMATCH`. Requires `@agledger/verify-core` 1.5.0.
51
+ - **The server can authenticate with an OIDC token instead of an API key.** 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` to bind the cert to a specific agent. The server generates an Ed25519 key pair in memory, exchanges the token for a short-lived cert (`POST /v1/auth/oidc/cert`) and presents the cert as its bearer, so no long-lived secret sits in the MCP client configuration. An API key wins when set, then the command, then the file; the server prints a note naming any source it ignores.
52
+ - The token source is read on every exchange, and the cert is re-exchanged once half its lifetime has passed. A 401 on a cert forces one re-exchange and one retry with the same body and `Idempotency-Key`.
53
+ - 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 on the routes that accept one.
54
+ - A failed exchange returns `OIDC_EXCHANGE_FAILED` with the Server's status, error body and `recoveryHint`; a token source that cannot produce a token returns `OIDC_TOKEN_SOURCE_FAILED`. Tokens are scrubbed from both.
55
+ - A token command runs in its own process group and is killed on a 60-second timeout or more than 64 KiB of output.
56
+ - `agledger_discover` fetches `/health` without a credential. A token file that cannot be read exits 2 at startup.
57
+ - **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. The token comes from the process, never from a tool argument, and is scrubbed from every error and tool result. `agledger_discover` reports only whether a delegation is configured and its source. With the OIDC cert credential the Server records the delegation as `bound` to the agent's identity; with an API key, as `unbound`.
58
+ - **`agledger_verify` takes `agentKeys`**, the Ed25519 public keys (JWKs) of agent certs. An entry whose sealed agent signature names one of them has that signature re-verified offline, and a failure is the new `CHAIN_AGENT_SIGNATURE_INVALID`. Without it, `agentSignatures` counts the signatures without checking them. Requires `@agledger/verify-core` 1.5.0.
51
59
 
52
60
  ### Fixed
53
61
 
54
- - **A host tree holding zod 3 stripped every argument description out of the published tool contract.** `@modelcontextprotocol/sdk` declares zod as a non-optional peer across `^3.25 || ^4.0` and renders tool schemas with the copy it resolves. This package declared `zod: ^4.3.6`, so an application already holding zod 3 satisfied the SDK at the top level while npm nested a second copy of zod 4 for us. `.describe()` and `.meta()` write into zod's registry rather than onto the schema, and a registry belongs to one module instance, so the SDK looked our schemas up somewhere they had never been recorded: every argument description disappeared and `export`, `publicKeys` and `params` lost `type: string`. Nothing threw. The server started, connected and answered calls, and agents received the contract with its guidance removed. Present in published 2.9.0 and every release before it.
62
+ - **An argument a tool does not declare is refused.** Each tool answers an undeclared argument with `code: UNKNOWN_ARGUMENT`, naming the argument and the ones it accepts, before anything is sent. For example, `agledger_api` called with `body` instead of `params` now says so.
63
+ - The `agledger_api` description and the README name `recoveryHint` as the field to read on Server errors, and `suggestion` for errors the tool raises itself.
64
+ - The `agledger_verify` description now lists all 19 failure codes an audit export can produce, including `CHAIN_OIDC_ACTOR_MISMATCH`, `CHAIN_KEY_EXPIRED` and `CHAIN_KEY_NOT_YET_ACTIVE`.
55
65
 
56
- The fix is to stop forcing a second copy: this package now declares the same `^3.25.0 || ^4.0.0` range the SDK does, adds `zod` as a peer dependency, and imports the version-specific `zod/v4` subpath, which zod 3.25 also ships. One copy now serves both on either major. Verified end to end on three host trees (no zod, zod 4, zod 3): all resolve a single copy and publish the full contract, where the zod 3 tree previously degraded silently. Declaring the peer alone was **not** sufficient, and is worth knowing if this recurs: npm simply nested the copy to satisfy the peer. `src/zod-integrity.ts` warns on stderr at startup if a tree still resolves two different zod VERSIONS, because the failure is otherwise silent. It compares versions rather than copies deliberately: a host pinned below the `zod/v4` floor nests a private copy for each side, and with both on the same release the published contract is complete, so warning there would be a false alarm on a working install. Reported by agledger-testbed while reviewing the round-5 candidate.
66
+ ### Changed
57
67
 
58
- - **`agledger_verify` published its one mandatory argument as optional.** The tool advertised no `required` array at all, so every client read `export` as something it could omit. `jsonStringField` was built with `z.preprocess`, whose input is typed `unknown`; `unknown` subsumes `undefined`, so zod marked the field `optin: 'optional'` and the MCP SDK left it out of `required` when rendering the schema with `io: 'input'`. The field is now an explicit `unknown` piped through the transform, which reports required-ness correctly while still publishing as `type: string` and still accepting a native object from object-native runtimes. `agledger_api`, whose fields are plain `z.string()`, was never affected. Reported by agledger-testbed against the 2.10.0 candidate (F-982). A new `tests/tool-schema.test.ts` asserts the published `required` array of every tool, read back over a real client connection rather than from the zod, since that is where the two came apart.
68
+ - `LICENSE` follows SDK License Template 1.9.
69
+ - The README describes AGLedger as agent memory, approvals, audit trail and notifications on one API and one signed ledger, self-hosted.
59
70
 
60
- - **Object query parameters reached the wire as `[object Object]`.** The client ran every query value through `String(value)`, so `agledger_api` with `GET /v1/records/search` and a `criteria` or `metadata` filter returned 400 rather than filtering. Objects now expand into the API's bracket notation (`metadata[state]=blocked`), and a `Date` serializes as ISO-8601 rather than the JS locale form the date-time params reject. Found by driving the server against a live API.
71
+ ## [2.10.1] - 2026-09-10
61
72
 
62
73
  ### Changed
63
74
 
64
- - **The `params` description says the body is not type-coerced.** The Server stopped coercing the fields of a JSON body, and `params` is a JSON string the model writes, so the type discipline of the body is now the model's responsibility. Identifier fields (`externalTaskId`, `correlationId`, `platformRef`, `projectRef`, `publisher`) are declared `string` and frequently hold all-digit values, which is exactly the case a model is most likely to write as a bare number. The Server's 400 carries `received`, `expected`, `constraint` and `instancePath`, so the cost was a wasted turn rather than a dead end; the description now heads it off. Raised by agledger-api ahead of the engine tag (agents#123).
75
+ - `LICENSE` section 6 names the ciphers this package line ships: Ed25519 (EdDSA), ECDSA P-256 with SHA-256, HMAC-SHA-256, AES-256-GCM, HKDF-SHA-256 and SHA-256. No other files changed.
65
76
 
66
- - **The `agledger_api` description now covers supersession.** The ledger is append-only, so every past state keeps matching a filter forever, and an agent tracking ongoing work needs to know that `supersedesRecordId` plus `?superseded=false` is how "what is the state of my work right now" stays answerable. It also explains that `supersededByCount` above 1 is a fork with several current heads, and the difference between filtering on signed `criteria` and unsigned `metadata`.
77
+ ## [2.10.0] - 2026-08-21
67
78
 
68
- - `@agledger/verify-core` moves to `^1.4.0`. The declared range was `^1.3.0` while the lockfile pinned 1.3.0, so CI tested against a build without the ES256 verification floor while a fresh install resolved 1.4.0. Lockfile refreshed, which also clears a high-severity `nanoid` advisory in the dev tree (vitest -> vite -> postcss; never shipped in the tarball).
79
+ ### Added
69
80
 
70
- ## [2.9.0] - 2026-08-07
81
+ - **An `idempotencyKey` argument on `agledger_api`, and a generated key on every POST.** To retry a call that may already have reached the Server, pass the key used the first time and the Server returns the original result instead of creating a second record. The key binds to method, route and body, so a retry with a changed body is rejected.
71
82
 
72
83
  ### Fixed
73
84
 
74
- - **A server that refuses to start now exits non-zero.** The `uncaughtException` handler printed the error and returned, which suppresses Node's default non-zero exit. Since 2.8.0 made `--api-url` mandatory, the most likely first-run failure (`agledger-mcp --api-key ...` with no URL) printed `Uncaught exception: No API URL configured` and then **exited 0**. Any launcher, supervisor, or shell reading the exit code saw a clean shutdown of a server that never accepted a connection. Missing `--api-key` exited 1 while missing `--api-url` exited 0, so the two halves of the same mistake reported opposite outcomes.
75
-
76
- - **The documented Quick Start could not start the server.** The `claude_desktop_config.json` example in the README passed only `--api-key`, and the `--help` usage line read `agledger-mcp --api-key <key> [--api-url <url>]`, marking as optional the flag 2.8.0 had made required. Copy-pasting either into a working MCP client produced a server that died at startup. Both now show `--api-url` as required, and a test spawns the built binary and asserts the shipped `--help` never brackets it again.
85
+ - **Tool argument descriptions are published when the host already has zod 3.** The package now declares `zod` as a peer dependency with the same `^3.25.0 || ^4.0.0` range as `@modelcontextprotocol/sdk` and imports the `zod/v4` subpath, so a single copy of zod serves both. The server warns on stderr at startup if a dependency tree still resolves two different zod versions.
86
+ - **`agledger_verify` publishes `export` as a required argument.** The tool schema now lists it in `required`.
87
+ - **Object query parameters are sent correctly.** `agledger_api` with `GET /v1/records/search` and a `criteria` or `metadata` filter now expands objects into bracket notation (`metadata[state]=blocked`), and a `Date` serializes as ISO-8601.
77
88
 
78
- - **An unknown flag is reported as usage, not as a crash.** `parseArgs` runs in strict mode, so `--version` (which this server does not implement) threw and surfaced as `Uncaught exception: Unknown option '--version'` with exit 0. It now prints an error, points at `--help`, and exits 2.
89
+ ### Changed
79
90
 
80
- ### Changed (behavior)
91
+ - **The `params` description says the body is not type-coerced.** Identifier fields such as `externalTaskId`, `correlationId`, `platformRef`, `projectRef` and `publisher` are strings, so all-digit values must be written as strings.
92
+ - **The `agledger_api` description covers supersession:** `supersedesRecordId` with `?superseded=false` returns the current state of tracked work, `supersededByCount` above 1 means a fork with several current heads, and signed `criteria` differ from unsigned `metadata` as filters.
93
+ - `@agledger/verify-core` moves to `^1.4.0`.
81
94
 
82
- - **Exit codes are now a documented contract**: `0` clean, `1` runtime failure, `2` usage or configuration error. Configuration errors moved from 1 (missing key) and 0 (missing URL) to 2 uniformly. A launcher that keyed on the exact code `1` to mean "bad config" should read 2; anything treating non-zero as failure is unaffected, and the missing-URL case changes from a false success to a failure.
95
+ ## [2.9.0] - 2026-08-07
83
96
 
84
- ### Internal
97
+ ### Fixed
85
98
 
86
- - **The live integration suite no longer runs with placeholder credentials.** It probed `localhost:3001` and, if anything answered, ran with `agl_agt_test`, which every real Server rejects. The result was eight failures that read as a regression in whatever had just changed, when the only problem was an unset environment variable. Reachability is not permission, so it now skips on a missing key exactly as it skips on an unreachable API.
99
+ - **A server that refuses to start now exits non-zero.** A missing `--api-url` previously printed an error and exited 0.
100
+ - **The Quick Start and `--help` show `--api-url` as required.** The README `claude_desktop_config.json` example and the `--help` usage line now include it.
101
+ - **An unknown flag prints an error, points at `--help`, and exits 2.**
87
102
 
88
- ### Packaging
103
+ ### Changed (behavior)
89
104
 
90
- - **Source maps are no longer published.** They shipped with `sources` pointing at `../src/*.ts` and no `sourcesContent`, and `src/` is not in the tarball, so they resolved to nothing. The build no longer emits them at all, so no shipped `.js` or `.d.ts` carries a `sourceMappingURL` comment pointing at a map the tarball does not contain (agents#114).
91
- - **`bugs` added to package.json.**
105
+ - **Exit codes are a documented contract:** `0` clean, `1` runtime failure, `2` usage or configuration error. A missing `--api-key` or `--api-url` now exits 2. A launcher that checked for exactly `1` to detect bad configuration should check for 2.
92
106
 
93
107
  ## [2.8.0] - 2026-08-07
94
108
 
95
109
  ### Added
96
110
 
97
- - **`agledger://llms.txt` resource, and `agledger_discover` now names the narrative.** An MCP-connected agent had no way to learn `/llms.txt` existed: `discover` pointed only at OpenAPI, `resources/list` offered only the spec, and the string `llms` appeared nowhere in the package. The CLI advertised it, so the one integration surface built specifically for AI agents was the one hiding the API's agent-oriented documentation. The resource fetches live from `GET /llms.txt`, so it cannot go stale (agents#110).
111
+ - **`agledger://llms.txt` resource.** It fetches live from `GET /llms.txt`, and `agledger_discover` now points to it.
98
112
 
99
113
  ### Changed
100
114
 
101
- - **`--api-url` is now required.** The server defaulted to `https://agledger.example.com`, a placeholder that resolves nowhere, so a missing URL surfaced as a DNS failure against a host the operator never configured, on every tool call. It now refuses to start and says so. Every deployment is self-hosted, so there was no default worth having. Same defect the CLI and SDK carried (agents#105, agents#109); found while fixing agents#110, not separately filed.
115
+ - **`--api-url` is now required.** The placeholder default is removed, and the server refuses to start without a URL.
102
116
 
103
117
  ## [2.7.0] - 2026-08-05
104
118
 
105
- Signing-agility wave 2.
106
-
107
119
  ### Added
108
120
 
109
- - **`agledger_verify` handles ES256 chains** via `@agledger/verify-core` 1.2.0 (dispatch bound to the trusted key's SPKI; unsupported algorithms still fail closed as `CHAIN_UNSUPPORTED_ALGORITHM`).
121
+ - **`agledger_verify` handles ES256 chains** via `@agledger/verify-core` 1.2.0. Unsupported algorithms still fail closed as `CHAIN_UNSUPPORTED_ALGORITHM`.
110
122
 
111
123
  ## [2.6.0] - 2026-08-05
112
124
 
113
125
  ### Changed
114
126
 
115
- - **`agledger_verify` takes `@agledger/verify-core` `^1.1.0`, the verifier forward-compatibility floor.** Algorithm dispatch binds to the trusted verification key rather than the unverified protected header; tampered or missing header `alg` values fail as `CHAIN_ALG_MISMATCH`, a key algorithm beyond the build fails closed as `CHAIN_UNSUPPORTED_ALGORITHM`, the signature-covered kid is cross-checked against `signingKeyId` (`CHAIN_SIGNING_KEY_DRIFT`), and untagged COSE_Sign1 is rejected. Legitimate Ed25519 exports verify identically.
127
+ - **`agledger_verify` takes `@agledger/verify-core` `^1.1.0`.** Algorithm dispatch binds to the trusted verification key rather than the unverified protected header. Tampered or missing header `alg` values fail as `CHAIN_ALG_MISMATCH`, a key algorithm beyond the build fails as `CHAIN_UNSUPPORTED_ALGORITHM`, the signed kid is cross-checked against `signingKeyId` (`CHAIN_SIGNING_KEY_DRIFT`), and untagged COSE_Sign1 is rejected. Valid Ed25519 exports verify as before.
116
128
 
117
129
  ## [2.5.6] - 2026-08-01
118
130
 
119
- Security housekeeping. No tool-surface or behavior change.
120
-
121
- ### Changed
122
-
123
- - Upgraded `@modelcontextprotocol/sdk` to `^1.30.0`. A fresh `npm install @agledger/mcp-server` previously ended with npm reporting moderate vulnerabilities, and enterprise CI that gates on `npm audit --audit-level=moderate` failed the install outright. The chain was `@modelcontextprotocol/sdk` to `@hono/node-server ^1.19.9`, and the advisory (GHSA-frvp-7c67-39w9, path traversal in `serve-static` on Windows via an encoded backslash) is fixed only in `@hono/node-server` 2.x. SDK 1.30.0 widened that range to `^1.19.9 || ^2.0.5`, so there is finally a fix path. Almost certainly not exploitable here, since it is Windows-only on a `serve-static` code path this package does not use, but "no fix available" reads badly on a security product.
124
- - Refreshed the lockfile to in-range latest, clearing the remaining transitive advisories: `@hono/node-server` 2.0.12, `hono` 4.12.33 (GHSA-xgm2-5f3f-mvvc, GHSA-hvrm-45r6-mjfj, GHSA-w62v-xxxg-mg59), `fast-uri` 3.1.5 (GHSA-v2hh-gcrm-f6hx, GHSA-4c8g-83qw-93j6), `body-parser` 2.3.0. `npm audit` now reports 0 vulnerabilities.
125
-
126
- ### Notes
127
-
128
- - Verified against a live AGLedger API v1.3.4 over the in-memory MCP transport, not just mocks: all 75 tests pass, including the 8 live integration cases covering discover, auth identity, record list and create, the structured schema-help error, and the record lifecycle.
131
+ ### Security
129
132
 
130
- Closes cross-repo agledger-agents#101.
133
+ - Upgraded `@modelcontextprotocol/sdk` to `^1.30.0` and refreshed transitive dependencies (`@hono/node-server`, `hono`, `fast-uri`, `body-parser`), so a fresh install reports no `npm audit` vulnerabilities. No tool-surface or behavior change.
131
134
 
132
135
  ## [2.5.5] - 2026-07-16
133
136
 
134
- Docs and tooling. No tool-surface or behavior change.
135
-
136
137
  ### Changed
137
138
 
138
- - The `agledger_discover` tool description now leads with notarize (cross-repo #99); the agent-facing quickstart string previously opened with "track accountability."
139
- - Removed dead vocabulary, stale naming history, and the phantom "fulfill" endpoint framing from the README and pitch text (#99).
140
- - Refreshed the lockfile to in-range latest (`@agledger/verify-core` 1.0.2, plus dev tooling).
141
- - Upgraded the TypeScript devDependency to `^7.0.2`. Build, typecheck, and tests all pass under 7.0.2.
139
+ - The `agledger_discover` tool description and quickstart now lead with notarize.
140
+ - The README drops outdated terminology.
142
141
 
143
142
  ## [2.5.4] - 2026-06-29
144
143
 
145
- ### Changed
146
-
147
- - Docs only: removed em-dashes from the README prose and the package.json description (cross-repo #98 writing-style sweep). Rewrote each sentence rather than swapping the glyph. No tool-surface or behavior change.
144
+ - Maintenance release with no user-facing changes.
148
145
 
149
146
  ## [2.5.3] - 2026-06-20
150
147
 
151
148
  ### Changed
152
149
 
153
- - Bumped `@agledger/verify-core` to `^1.0.0` (now GA at 1.0.0 alongside the API and the published package line). No tool-surface or behavior changes — the `agledger_verify` offline-verification logic is unchanged.
150
+ - Bumped `@agledger/verify-core` to `^1.0.0`. No tool-surface or behavior changes.
154
151
 
155
152
  ## [2.5.2] - 2026-06-18
156
153
 
157
- ### Fixed
154
+ ### Security
158
155
 
159
- - **CodeQL `js/polynomial-redos`.** Replaced a regex-based trailing-slash strip with a linear scan, removing the polynomial-backtracking vector flagged by CodeQL. No tool-surface or behavior change.
156
+ - Replaced a regex-based trailing-slash strip with a linear scan to remove a polynomial-backtracking risk flagged by CodeQL (`js/polynomial-redos`). No tool-surface or behavior change.
160
157
 
161
158
  ## [2.5.1] - 2026-06-10
162
159
 
163
160
  ### Changed
164
161
 
165
- - **License re-sync.** `LICENSE` is now a verbatim copy of the canonical AGLedger SDK license template **v1.5**: §7 trademarks trimmed to **AGLedger + Settlement Signal (pending)** (removed the retired "Agentic Ledger" / AOAP claims), §6 export language modernized to ENC §740.17(b)(1) mass-market self-classification, and §1 carries the no-inspection / no-training / no-usage-data representation. README: dropped the retired AOAP protocol link and trimmed the trademark footer to match LICENSE §7.
166
- - No code changes; republished so the distributed tarball carries the corrected license text.
162
+ - `LICENSE` is updated to the canonical AGLedger SDK license template v1.5. The README drops a retired protocol link and trims the trademark footer to match `LICENSE` section 7.
167
163
 
168
164
  ## [2.5.0] - 2026-06-08
169
165
 
170
- Release marking the AGLedger API **v1.0.0 GA**. The MCP server is a thin pass-through over the API, so the tool surface is unchanged from 2.4.x; this is the GA-aligned cut alongside the SDK/CLI 1.0.0 release wave.
166
+ Aligned with AGLedger API v1.0.0 GA. The tool surface is unchanged from 2.4.x.
171
167
 
172
168
  ## [2.4.11] - 2026-06-04
173
169
 
174
170
  ### Security
175
171
 
176
- - Hardened `agledger_api` and `ApiClient` against off-origin paths (prevents API-key exfiltration). A protocol-relative path like `//evil.com/x` passed the `startsWith('/')` guard, and `new URL(path, apiUrl)` resolved it to a different origin (`https://evil.com/x`) — sending the `Authorization: Bearer <apiKey>` header off-host. Two layers now block this: `agledger_api` rejects a `path` starting with `//` (returns a `PATH_INVALID` error result), and `ApiClient.request` pins every request to the configured API origin, throwing if the resolved URL's origin differs. No caller can be steered off-origin.
172
+ - `agledger_api` rejects a `path` starting with `//` (returns a `PATH_INVALID` error result), and every request is pinned to the configured API origin. This prevents a crafted path from sending the API key to another host.
177
173
 
178
174
  ### Changed
179
175
 
180
- - SEP-1880 tool-level scopes (early adoption): `_meta.requiredScopes` added where it can be declared honestly. `agledger_verify` → `[]` (offline, no network, no key). `agledger_discover` → `[]` (calls `/health` + `/v1/scope-profiles`, both public, and `/v1/auth/me`, which is authenticated but scope-free by design — no NAMED scope gates it). `agledger_api` deliberately OMITS `_meta` (with an inline comment): it is the universal dispatcher to every route, each with its own server-enforced scope, so no single scope can be statically declared for it.
176
+ - Added `_meta.requiredScopes` to the tools where a scope can be stated: `agledger_verify` and `agledger_discover` declare `[]`. `agledger_api` declares none, since each route enforces its own scope.
181
177
 
182
178
  ## [2.4.10] - 2026-06-04
183
179
 
184
- No functional change. First release published from CI with **build provenance** via npm trusted publishing (OIDC) — npm attaches a Sigstore provenance attestation automatically; verify with `npm audit signatures`. A CycloneDX SBOM is attached to the release. This package now lives in its own source-of-truth repo `agledger-ai/mcp-server` and resolves `@agledger/verify-core@0.1.4`.
180
+ Published with npm build provenance (verify with `npm audit signatures`) and a CycloneDX SBOM. No functional change.
185
181
 
186
182
  ## [2.4.9] - 2026-06-02
187
183
 
188
184
  ### Security
189
185
 
190
- - `agledger_api` now rejects a `path` containing control characters (`\x00`–`\x1f`, `\x7f`) before building the request URL. Tool input is untrusted; control characters enable request-line / header injection and never appear in a legitimate API path. Returns a `PATH_INVALID` error result.
186
+ - `agledger_api` rejects a `path` containing control characters (`\x00` to `\x1f`, `\x7f`) with a `PATH_INVALID` error result.
191
187
 
192
188
  ### Changed
193
189
 
194
- - `agledger_api` `destructiveHint` annotation corrected `false` → `true`. The tool dispatches to any route, including `DELETE`/`PATCH`, so it can perform destructive, non-idempotent operations — the honest worst-case annotation per the 2026 MCP tool-annotation guidance. `agledger_discover` and `agledger_verify` annotations were already correct (`verify` is `openWorldHint:false` — offline, no network).
190
+ - The `agledger_api` `destructiveHint` annotation is now `true`, because the tool can dispatch `DELETE` and `PATCH` requests.
195
191
 
196
192
  ## [2.4.8] - 2026-05-29
197
193
 
198
194
  ### Fixed
199
195
 
200
- - `agledger_verify` now accepts the raw `GET /v1/verification-keys` response envelope (`{data:[...], ...}`) as `publicKeys`, unwrapping `.data` automatically — the MCP analogue of the CLI's F-732 fix (F-737). An MCP agent's natural flow gets the envelope straight from `agledger_api` and has no `.data[]`-extraction step, so the most obvious independent-audit call (`requireOutOfBandKeys: true` against the `agledger_api` keys response) previously failed. The compact `{keyId: SPKI-DER-base64}` map and the bare `[{keyId, publicKey, ...}]` list still pass through untouched. Updated tool description and example.
196
+ - `agledger_verify` accepts the raw `GET /v1/verification-keys` response envelope (`{data:[...], ...}`) as `publicKeys` and unwraps `.data`. The compact `{keyId: SPKI-DER-base64}` map and the bare `[{keyId, publicKey, ...}]` list are still accepted.
201
197
 
202
198
  ## [2.4.7] - 2026-05-29
203
199
 
204
200
  ### Changed
205
201
 
206
- - `agledger_verify` rebuilt on `@agledger/verify-core@^0.1.3`: export-path binding-integrity now fires on engine ≥ v0.26.x exports (a denormalised `payload` rewritten while `coseSign1` stays intact fails `CHAIN_PAYLOAD_BINDING_MISMATCH`, F-731), and a signature short-circuited by an upstream chain break reports `not-checked` rather than `skipped` (F-732).
202
+ - `agledger_verify` runs on `@agledger/verify-core@^0.1.3`. A denormalized `payload` rewritten while `coseSign1` stays intact fails `CHAIN_PAYLOAD_BINDING_MISMATCH`, and a signature skipped because of an upstream chain break reports `not-checked`.
207
203
 
208
204
  ## [2.4.6] - 2026-05-28
209
205
 
210
206
  ### Changed
211
207
 
212
- - Republished against `@agledger/verify-core` 0.1.2 — picks up F-698 OOB-key polymorphism and the temporal-axis fix. The `agledger_verify` tool's `publicKeys` argument now accepts either the compact `{keyId: SPKI-DER-base64}` map OR the natural array shape from `GET /v1/verification-keys` (`[{keyId, publicKey, ...}]`), as a JSON-encoded string or native object/array. Malformed shapes produce the tool's standard `{code: "INVALID_JSON", suggestion}` error envelope. Updated tool description and example.
208
+ - Updated to `@agledger/verify-core` 0.1.2. The `publicKeys` argument of `agledger_verify` accepts either the compact `{keyId: SPKI-DER-base64}` map or the array from `GET /v1/verification-keys` (`[{keyId, publicKey, ...}]`), as a JSON-encoded string or a native object or array. Malformed input returns the standard `{code: "INVALID_JSON", suggestion}` error.
213
209
 
214
210
  ## [2.4.5] - 2026-05-28
215
211
 
216
212
  ### Changed
217
213
 
218
- - Republished against `@agledger/verify-core` 0.1.1. The `agledger_verify` tool now exercises `oidc_actor` and `key_temporal` on exports from engine ≥ v0.26.x (the wire now carries `actorOidcIss/Sub/Synthesized` and `signingKeyWindows`); the tool result reports these as `applied` instead of `skipped_no_input` for those exports. Older exports without the new fields continue to report them as `skipped_no_input`.
214
+ - Updated to `@agledger/verify-core` 0.1.1. `agledger_verify` applies the `oidc_actor` and `key_temporal` checks to exports that carry the new fields; older exports still report them as `skipped_no_input`.
219
215
 
220
216
  ## [2.4.4] - 2026-05-27
221
217
 
222
- Verifier consolidation (Pass 1). `agledger_verify` now runs on the shared verification core `@agledger/verify-core` instead of a server-local copy of `verify-export.ts` — the same hash-chain + COSE_Sign1 + Ed25519 logic the SDK, CLI, and `@agledger/verify` share.
218
+ `agledger_verify` now runs on the shared verification core `@agledger/verify-core`, the same hash-chain, COSE_Sign1 and Ed25519 logic used by the SDK, CLI and `@agledger/verify`.
223
219
 
224
220
  ### Changed
225
221
 
226
- - Offline verifier failure reasons are now canonical SCREAMING_SNAKE `FailureCode` values from `@agledger/verify-core`.
227
- - New `requireOutOfBandKeys` input on the `agledger_verify` tool: fail closed unless every signature is verified against a caller-supplied (out-of-band) key, rejecting keys embedded in the export. For high-assurance audits.
228
- - The tool result now surfaces `keyProvenance` — whether each verified entry's key came from out-of-band (caller-supplied) keys or was embedded in the export — so agents can distinguish a self-attesting export from an independently keyed one.
222
+ - Offline verifier failure reasons are now `FailureCode` values from `@agledger/verify-core`, in SCREAMING_SNAKE case.
223
+ - New `requireOutOfBandKeys` input on `agledger_verify`: fail unless every signature is verified against a caller-supplied key, rejecting keys embedded in the export.
224
+ - The result includes `keyProvenance`, showing whether each verified entry's key was caller-supplied or embedded in the export.
229
225
 
230
226
  ## [2.4.3] - 2026-05-27
231
227
 
232
228
  ### Fixed
233
229
 
234
- - **`agledger_verify` rejected valid exports (F-682).** The offline verifier read the legacy `position` field on each export entry, but current exports (v0.25+) emit `chainPosition`. With `position` absent, every valid export failed with a false `position_gap` on the first entry. Now reads `chainPosition` with a `position` fallback for pre-v0.25 exports. Verified end-to-end against a live export.
230
+ - **`agledger_verify` rejected valid exports.** It now reads `chainPosition` (with a `position` fallback for older exports) instead of only the legacy `position` field.
235
231
 
236
232
  ## [2.4.2] - 2026-05-27
237
233
 
238
- Tracks AGLedger API v0.25.5 (Verify → Gate rename). The MCP server is a thin pass-through, so the renamed routes (`/outcome` → `/verdict`, `/verify` → `/evaluate`, `/verification-status` → `/gate-status`) reach the `agledger_api` tool automatically — no functional change. `agledger_verify` (offline COSE_Sign1 audit verification) is cryptographic and unchanged.
234
+ Tracks AGLedger API v0.25.5 (Verify to Gate rename). The renamed routes reach `agledger_api` automatically, and `agledger_verify` is unchanged.
239
235
 
240
236
  ### Changed
241
237
 
242
- - README: the Verdicts capability is now described as accept/reject (was PASS/FAIL).
238
+ - README: the Verdicts capability is described as accept/reject.
243
239
 
244
240
  ## [2.4.1] - 2026-05-21
245
241
 
246
- Tracks AGLedger API v0.24.0. MCP server is a thin pass-through, so the v0.24.0 rename sweep lands on `agledger_api` calls automatically. Internal updates:
242
+ Tracks AGLedger API v0.24.0.
247
243
 
248
244
  ### Changed
249
245
 
250
- - Offline verifier (`agledger_verify`): `RecordAuditExport.exportMetadata.enterpriseId` → `orgId` to match v0.24.0 export shape.
251
- - Integration test fixtures: `/v1/records/{id}/receipts` → `/v1/records/{id}/completions` (vocab cutover leftover from v0.23.0).
246
+ - `agledger_verify`: `RecordAuditExport.exportMetadata.enterpriseId` is now `orgId`, matching the v0.24.0 export shape.
252
247
 
253
248
  ## [2.4.0] - 2026-05-19
254
249
 
255
- Tracks AGLedger API v0.23.0. SCITT vocabulary alignment + canonical COSE_Sign1 chain envelope cutover. The MCP server is a thin pass-through, so most of the wave is API-side; the `agledger_verify` tool is rewritten to verify the new COSE_Sign1 envelope. Closes cross-repo issue agledger-agents#68.
256
-
257
- ### Changed (BREAKING — `agledger_verify` tool: format 1.0 → 2.0)
250
+ Tracks AGLedger API v0.23.0, which moves the chain to a canonical COSE_Sign1 envelope.
258
251
 
259
- - `agledger_verify` now decodes canonical COSE_Sign1 envelopes (RFC 9052, tag 18, EdDSA) over in-toto v1 Statement payloads, deterministic CBOR per RFC 8949 §4.2.1. Replaces the JCS + detached-Ed25519 verifier from 2.3.x.
260
- - Tool description updated to mention COSE_Sign1 + `Sig_structure` reconstruction + the new failure modes (`cose_decode_failed`, `cose_header_mismatch`).
261
- - The tool's `structuredContent` result now carries a `signatureCoverage` discriminator (`{ signed, unsigned, skipped, total }`). Agents should not conclude "Ed25519-verified" from `valid: true` alone — surface `signatureCoverage` or `integrityLevel` in their reports.
262
- - New `chainIntegrityReason: "payload_drift"` — emitted when the visible `payload` jsonb diverges from the predicate signed in `coseSign1` (privileged-DBA-bypass tamper detection).
263
- - Pre-1.0 export-format JSON (`exportFormatVersion: "1.0"`) is rejected with `unsupported_algorithm`. Re-export the chain from a v0.23.0+ engine. The MCP tool description tells the agent how to do this: `agledger_api method=GET path=/v1/records/{id}/audit-export`.
264
- - The verifier picks up a `cborg` runtime dependency (only used by the offline-verifier path; the `agledger_discover` + `agledger_api` tools still use direct `fetch`).
252
+ ### Changed (breaking)
265
253
 
266
- ### Changed (text only — Receipt → Completion alignment)
254
+ - `agledger_verify` decodes COSE_Sign1 envelopes (RFC 9052, tag 18, EdDSA) over in-toto v1 Statement payloads with deterministic CBOR (RFC 8949 section 4.2.1), replacing the earlier JCS and detached-Ed25519 verifier.
255
+ - The tool description now covers COSE_Sign1 and the new failure modes `cose_decode_failed` and `cose_header_mismatch`.
256
+ - `structuredContent` carries a `signatureCoverage` object (`{ signed, unsigned, skipped, total }`). Do not conclude "Ed25519-verified" from `valid: true` alone; report `signatureCoverage` or `integrityLevel`.
257
+ - New `chainIntegrityReason: "payload_drift"` when the visible `payload` differs from the predicate signed in `coseSign1`.
258
+ - Export format 1.0 (`exportFormatVersion: "1.0"`) is rejected with `unsupported_algorithm`. Re-export the chain with `agledger_api method=GET path=/v1/records/{id}/audit-export` from a v0.23.0 or later Server.
259
+ - Adds a `cborg` runtime dependency, used only by the offline verifier.
267
260
 
268
- - `agledger_discover` quickstart step 4: "Do your work, then submit a receipt" → "submit a completion"; path `/v1/records/{id}/receipts` → `/v1/records/{id}/completions`.
269
- - `agledger_api` tool description: route example `/v1/records/{id}/receipts` → `/v1/records/{id}/completions`. Workflow line "POST /v1/records/{id}/receipts — submit evidence when done" → "POST /v1/records/{id}/completions — submit evidence when done".
270
-
271
- The three-tool surface is unchanged: `agledger_discover`, `agledger_api`, `agledger_verify`. `agledger_api` is a pure HTTP pass-through, so the API-side renames (route paths, request/response field names, webhook event names, scopes) surface verbatim. Agents writing prompts that target `agledger_api method=POST path=/v1/records/{id}/receipts` need to update the path to `/v1/records/{id}/completions`.
261
+ ### Changed
272
262
 
273
- ### Tests
263
+ - `agledger_discover` quickstart step 4 and the `agledger_api` description now say "submit a completion" with the path `/v1/records/{id}/completions` (was `/v1/records/{id}/receipts`). Update any prompts that target the old path.
274
264
 
275
- - 127 tests pass. The `agledger_verify` test suite was rewritten with an in-test COSE_Sign1 envelope builder to cover the new failure modes (cose_decode_failed, cose_header_mismatch, payload_drift) without depending on engine-generated fixtures.
265
+ The three-tool surface is unchanged: `agledger_discover`, `agledger_api` and `agledger_verify`.
276
266
 
277
267
  ## [2.3.3] - 2026-05-06
278
268
 
279
269
  ### Fixed
280
270
 
281
- - **Gemini-MCP integrations no longer break on the first non-trivial call.** The three free-form object fields (`agledger_api.params`, `agledger_verify.export`, `agledger_verify.publicKeys`) were emitting `additionalProperties: {}` on a properties-less OBJECT — both keywords are outside Gemini's strict OpenAPI 3.0 function-call grammar, so any non-trivial body returned `MALFORMED_FUNCTION_CALL`. Each field is now declared as a JSON-encoded `string` on the wire (Gemini-friendly) and parsed server-side. Object-native runtimes (Claude Desktop, ChatGPT MCP) keep working — the server accepts either a stringified-JSON string or a native object via a Zod preprocess. Tool descriptions document the JSON-encoded shape with examples. (testbed F-532 / agledger-agents#67)
282
-
283
- ### Tests
284
-
285
- - Added Gemini-shape regressions covering all three affected fields: stringified-JSON path, native-object path (back-compat), and malformed-JSON error path. The new `INVALID_JSON` error code surfaces a structured suggestion telling the agent how to retry.
271
+ - **Gemini MCP integrations work on non-trivial calls.** `agledger_api.params`, `agledger_verify.export` and `agledger_verify.publicKeys` are now declared as JSON-encoded strings, which Gemini's function-call grammar accepts. Object-native runtimes (Claude Desktop, ChatGPT MCP) can still pass a native object. Malformed JSON returns the `INVALID_JSON` error with a suggestion for retrying.
286
272
 
287
273
  ## [2.3.2] - 2026-05-06
288
274
 
289
275
  ### Fixed
290
276
 
291
- - **Tool results are now visible to LLM-driven MCP runtimes.** Previously every tool returned `content: []` with all data in `structuredContent`. Per MCP spec 2025-06-18, structured content SHOULD also be returned as functionally-equivalent unstructured content; LLM clients (Claude Desktop, ChatGPT MCP, Cursor, OpenAI tool-mapped runtimes) only forward `content[]` to the model, so they saw empty results and stopped. All three tools (`agledger_discover`, `agledger_api`, `agledger_verify`) now mirror `structuredContent` into a single TextContent block on every success and error path. (testbed F-531 / agledger-agents#66)
292
- - **`serverInfo.version`, `User-Agent`, and `--help` banner no longer drift from `package.json`.** All three read the version from `package.json` at runtime via a shared `version.ts` module instead of duplicating the literal. v2.3.1 shipped `serverInfo.version: 2.3.0` and `User-Agent: agledger-mcp-server/2.2.0`; that class of drift is now structurally impossible.
293
- - **`--help` banner lists all three tools.** `agledger_verify` was missing from the Tools section.
294
- - **`mirrorContent` no longer pretty-prints.** The text mirror is consumed by an LLM, not a human — dropping the 2-space indent saves ~25% on agent context tokens for large paginated responses.
295
-
296
- ### Build
297
-
298
- - Added a `files` allowlist to `package.json` so the npm tarball only ships `dist/`, `LICENSE`, `README.md`, `CHANGELOG.md`, and `package.json` (24 files vs. 29 in 2.3.1). No more shipping `tests/` or `tsconfig.json`.
299
-
300
- ### Tests
301
-
302
- - Added `assertContentMirrorsStructured` helper and a dedicated F-531 regression suite covering success and error paths on all three tools, plus a parity test asserting `SERVER_VERSION` matches `package.json`.
277
+ - **Tool results are visible to LLM-driven MCP runtimes.** All three tools now mirror `structuredContent` into a single text content block on every success and error path.
278
+ - `serverInfo.version`, `User-Agent` and the `--help` banner now read the version from `package.json`.
279
+ - The `--help` banner lists all three tools, including `agledger_verify`.
280
+ - The text mirror is no longer pretty-printed, which cuts token use on large responses.
303
281
 
304
282
  ## [2.3.1] - 2026-04-30
305
283
 
306
- Tracks AGLedger API v0.22.13. The MCP server is a thin pass-through, so all 10 new v0.22.x routes (`/v1/admin/strings/*`, federation gateway status, peer directory, vault checkpoints, dispute withdraw, etc.) are reachable via `agledger_api` with no surface changes.
307
-
308
- ### Changed
309
-
310
- - Re-published as part of the v0.7.1 SDK/CLI sweep tracking API v0.22.13. No tool-surface changes.
284
+ Tracks AGLedger API v0.22.13. No tool-surface changes.
311
285
 
312
286
  ## [2.3.0] - 2026-04-27
313
287
 
314
- Tracks AGLedger API v0.21.5. Every `/v1/mandates/*` route is now `/v1/records/*`; `Contract Type` is `Type`. The MCP server is a thin pass-through, so this release sweeps tool descriptions, the quickstart returned by `agledger_discover`, and the offline verifier's field names.
315
-
316
- ### Changed (BREAKING)
288
+ Tracks AGLedger API v0.21.5. Every `/v1/mandates/*` route is now `/v1/records/*`, and `Contract Type` is `Type`.
317
289
 
318
- - **Offline verifier output field rename.** `verify-export.ts` exports `RecordAuditExport` (was `MandateAuditExport`). Metadata fields: `mandateId` → `recordId`, `contractType` → `type`. `VerifyExportResult.mandateId` → `recordId`. Crypto primitives (RFC 8785 JCS, SHA-256, Ed25519) and the signature input `{position}:{payloadHash}:{previousHash}` are unchanged.
319
- - **`agledger_verify` tool description** points at `/v1/records/{id}/audit-export`. The `INVALID_EXPORT` error suggestion was updated similarly.
290
+ ### Changed (breaking)
320
291
 
321
- ### Changed (tool description / quickstart sweep)
292
+ - Offline verifier output fields are renamed: `mandateId` to `recordId` and `contractType` to `type`; `MandateAuditExport` is now `RecordAuditExport`. The signature input `{position}:{payloadHash}:{previousHash}` is unchanged.
293
+ - The `agledger_verify` description points at `/v1/records/{id}/audit-export`, and the `INVALID_EXPORT` error suggestion is updated to match.
322
294
 
323
- - **`agledger_discover` quickstart** now reads:
324
- 1. `GET /v1/schemas` — list Record types.
325
- 2. `GET /v1/schemas/{type}` — get required fields and examples.
326
- 3. `POST /v1/records` — create a record.
327
- 4. `POST /v1/records/{id}/receipts` — submit evidence when done.
328
- - **`agledger_api` tool description** uses the new vocabulary throughout (workflow steps, path examples, `PATH_INVALID` error message and suggestion).
329
- - **README** Tools table, Agent workflow section, and "What is AGLedger?" bullet list use Record / Type vocabulary.
330
-
331
- ### Build
295
+ ### Changed
332
296
 
333
- - `prebuild` now wipes `dist/` so stale outputs from prior builds cannot leak into the next one.
297
+ - `agledger_discover` quickstart now reads: `GET /v1/schemas` to list Record types, `GET /v1/schemas/{type}` for required fields and examples, `POST /v1/records` to create a record, `POST /v1/records/{id}/receipts` to submit evidence when done.
298
+ - The `agledger_api` description and the README use the Record and Type vocabulary.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
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
+ Requires an AGLedger Server 2.0 or later. For a 1.x Server, use `@agledger/mcp-server@2.11.0`, the last release that supports it.
6
+
5
7
  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
8
 
7
9
  **Learn more**
@@ -37,8 +39,9 @@ Add to your MCP client configuration (e.g. `claude_desktop_config.json`):
37
39
 
38
40
  Both flags are required, unless an OIDC token source stands in for the key (see
39
41
  [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` the
41
- server exits before it accepts a connection.
42
+ self-hosted, so there is no default server to call: without `--api-url`, or
43
+ with one that is not an absolute `http` or `https` URL, the server exits before
44
+ it accepts a connection.
42
45
 
43
46
  Or run directly:
44
47
 
@@ -47,7 +50,7 @@ agledger-mcp --api-key <key> --api-url <url>
47
50
  ```
48
51
 
49
52
  Exit codes: `0` clean, `1` runtime failure, `2` usage or configuration error
50
- (missing flag, unknown flag), so a launcher can tell a misconfiguration from a
53
+ (missing flag, unknown flag, an API URL that is not an `http(s)` URL), so a launcher can tell a misconfiguration from a
51
54
  crash.
52
55
 
53
56
  ## Authenticating with OIDC instead of an API key
@@ -57,18 +60,29 @@ provider as a trusted issuer for agents, the MCP server can run with no API key
57
60
  at all. Give it a source of OIDC tokens instead. It exchanges a token for a
58
61
  short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`), presents the
59
62
  cert as its bearer, and signs each request body with an Ed25519 key that exists
60
- only in its own memory. The Server records that signature in the signed chain
61
- entry of every record the agent writes (`predicate.on_behalf_of.agent_signature`).
63
+ only in its own memory. The Server verifies that signature and seals it into
64
+ every chain entry the agent writes (`predicate.on_behalf_of.agent_signature`).
62
65
  Nothing is written to disk.
63
66
 
64
67
  | Env var | Description |
65
68
  |---------|-------------|
66
69
  | `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. |
67
70
  | `AGLEDGER_OIDC_TOKEN_CMD` | A shell command whose stdout is an OIDC JWT. Run on every exchange. |
68
- | `AGLEDGER_OIDC_AGENT_ID` | Optional. The agent id to bind the cert to, when the issuer does not map one from the token. |
71
+ | `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. |
69
72
 
70
73
  An API key wins when one is set, then the command, then the file.
71
74
 
75
+ **The token decides which agent the cert binds to**, never the MCP server's
76
+ configuration. An administrator binds an agent to the token's identity in one
77
+ of two ways: `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's
78
+ issuer and subject), or a `claimMapping` of `agent_id` on the trusted issuer,
79
+ which reads the agent id from a claim in the token. An issuer that
80
+ auto-provisions agents creates one for an unbound subject instead. A token that
81
+ binds no agent is refused, and the Server's `recoveryHint` says which binding is
82
+ missing. A token bound to a federation shadow agent (one listed at
83
+ `GET /v1/peer-agents`) is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that
84
+ agent authenticates on its own Server.
85
+
72
86
  ```bash
73
87
  AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
74
88
  agledger-mcp --api-url https://your-agledger-instance
@@ -93,7 +107,7 @@ the Server answers 401 (a revoked cert), after which the request is retried a
93
107
  single time. A refresh that fails while the current cert is still valid keeps
94
108
  the current cert and prints one warning on stderr. When the exchange itself is
95
109
  refused, the tool result carries `code: OIDC_EXCHANGE_FAILED`, the Server's
96
- status and error body, and its `recoveryHint`.
110
+ status and error body, and its `recoveryHint` as the result's `suggestion`.
97
111
 
98
112
  The Server exchanges a token id (`jti`) only once, so every exchange needs a
99
113
  new token. A command runs on every exchange; a file is read on every exchange,
@@ -151,7 +165,7 @@ to compare, and it is recorded `unbound`.
151
165
  |------|-------------|
152
166
  | `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
153
167
  | `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. |
154
- | `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. Pass `agentKeys` (the agents' cert public keys as JWKs) to re-verify the agent signatures sealed in the chain; without them those signatures are counted but not checked. Built on the shared `@agledger/verify-core`. |
168
+ | `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, `agentKeys` (the agents' cert public keys as JWKs) re-verifies the agent signatures sealed in the chain, and `federationKeys` (`{"<hubId>": "<key>"}`, each peer Server's federation key as its operator gives it) re-verifies the peer messages a receiving Server sealed on its `FEDERATION_*` entries, which fail `CHAIN_FEDERATION_WIRE_INVALID` when they do not hold. After a peer changes its federation key, give an array entry `history`, the JSON the peer serves at `GET /.well-known/agledger-federation-keys.json`, so the entries sealed under its earlier keys verify too. 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`. |
155
169
 
156
170
  ## Resources
157
171
 
@@ -166,10 +180,10 @@ Both are fetched live from the running instance, so neither can go stale.
166
180
 
167
181
  The `agledger_discover` tool returns a quickstart workflow that guides agents through the accountability flow:
168
182
 
169
- 1. `GET /v1/schemas` -- list available Record types
170
- 2. `GET /v1/schemas/{type}` -- get required fields and examples
171
- 3. `POST /v1/records` -- create a record
172
- 4. `POST /v1/records/{id}/completions` -- submit a completion (evidence) when done
183
+ 1. `GET /v1/schemas`: list available Record types
184
+ 2. `GET /v1/schemas/{type}`: get required fields and examples
185
+ 3. `POST /v1/records`: create a record
186
+ 4. `POST /v1/records/{id}/completions`: submit a completion (evidence) when done
173
187
 
174
188
  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.
175
189
 
@@ -179,15 +193,18 @@ Every API error response includes a `recoveryHint` naming the fix, so an agent c
179
193
  |------|---------|-------------|
180
194
  | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key. Required unless an OIDC token source is set (see above). |
181
195
  | `--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. |
196
+ | `--timeout` | `AGLEDGER_TIMEOUT` | Seconds to wait for each API response (default 30). A positive number up to 2147483; anything else exits 2. |
197
+
198
+ 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.
182
199
 
183
200
  ## What is AGLedger?
184
201
 
185
202
  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.
186
203
 
187
- - **Records** -- structured commitments with acceptance criteria and tolerance bands
188
- - **Completions** -- performer evidence recording what was reported to be done
189
- - **Verdicts** -- principal accept/reject decisions on a Completion (the Gate), with settlement signals
190
- - **Audit chain** -- notarized records as COSE_Sign1 envelopes, hash-chained, Ed25519-signed, tamper-evident, verifiable offline
204
+ - **Records**: structured commitments with acceptance criteria and tolerance bands
205
+ - **Completions**: performer evidence recording what was reported to be done
206
+ - **Verdicts**: principal accept/reject decisions on a Completion (the Gate), with settlement signals
207
+ - **Audit chain**: notarized records as COSE_Sign1 envelopes, hash-chained, Ed25519-signed, tamper-evident, verifiable offline
191
208
 
192
209
  Learn more at [agledger.ai](https://www.agledger.ai) | [API docs](https://www.agledger.ai/docs/)
193
210
 
@@ -103,9 +103,11 @@ export class ApiClient {
103
103
  if (options?.anonymous) {
104
104
  return this.send(url, method, headers, body);
105
105
  }
106
- // A cert credential signs the body with the key bound to its cert. The
107
- // Server records the signature in the chain entry on the routes that
108
- // accept one and ignores the headers elsewhere.
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.
109
111
  if (body !== undefined && this.credential.signBody) {
110
112
  Object.assign(headers, this.credential.signBody(body));
111
113
  }
@@ -105,7 +105,11 @@ export declare class ApiKeyCredential implements Credential {
105
105
  export interface OidcCertCredentialOptions {
106
106
  /** Returns a fresh OIDC JWT. Called once per exchange, never cached. */
107
107
  getOidcToken: OidcTokenGetter;
108
- /** Optional agent binding sent on the exchange (a UUID in the issuer's org). */
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
+ */
109
113
  agentId?: string;
110
114
  /** Re-exchange once this fraction of the cert's lifetime has passed. Default 0.5. */
111
115
  refreshFraction?: number;
@@ -360,8 +360,8 @@ export class OidcCertCredential {
360
360
  }
361
361
  if (res.status !== 201) {
362
362
  const scrubbed = scrub(res.body, token);
363
- const serverMessage = scrubbed?.message;
364
- throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned ${res.status}${typeof serverMessage === 'string' ? `: ${serverMessage}` : ''}`, res.status, scrubbed);
363
+ const serverDetail = scrubbed?.detail;
364
+ throw new OidcExchangeError(`OIDC cert exchange failed: POST ${EXCHANGE_PATH} returned ${res.status}${typeof serverDetail === 'string' ? `: ${serverDetail}` : ''}`, res.status, scrubbed);
365
365
  }
366
366
  const out = res.body;
367
367
  const issuedAt = Date.parse(String(out?.cert?.issuedAt));
package/dist/index.js CHANGED
@@ -25,6 +25,31 @@ process.on('unhandledRejection', (reason) => {
25
25
  process.stderr.write(`Fatal: unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}\n`);
26
26
  process.exit(EXIT_RUNTIME_FAILURE);
27
27
  });
28
+ /** Why an API URL cannot be used, or undefined when it can. */
29
+ function apiUrlProblem(url) {
30
+ let parsed;
31
+ try {
32
+ parsed = new URL(url);
33
+ }
34
+ catch {
35
+ return 'is not a URL';
36
+ }
37
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
38
+ return `has scheme '${parsed.protocol}', and only http: and https: are supported`;
39
+ }
40
+ return undefined;
41
+ }
42
+ /** The longest delay setTimeout takes; a larger one fires at once, which would time every call out. */
43
+ const MAX_TIMEOUT_SECONDS = 2_147_483;
44
+ /** Why a timeout in seconds cannot be used, or undefined when it can. */
45
+ function timeoutProblem(raw) {
46
+ const seconds = raw.trim() === '' ? NaN : Number(raw);
47
+ if (!Number.isFinite(seconds) || seconds <= 0)
48
+ return 'is not a positive number of seconds';
49
+ if (seconds > MAX_TIMEOUT_SECONDS)
50
+ return `is more than ${MAX_TIMEOUT_SECONDS} seconds`;
51
+ return undefined;
52
+ }
28
53
  function main() {
29
54
  let values;
30
55
  try {
@@ -32,6 +57,7 @@ function main() {
32
57
  options: {
33
58
  'api-key': { type: 'string', short: 'k' },
34
59
  'api-url': { type: 'string', short: 'u' },
60
+ timeout: { type: 'string' },
35
61
  help: { type: 'boolean', short: 'h' },
36
62
  },
37
63
  strict: true,
@@ -55,6 +81,10 @@ Options:
55
81
  --api-url, -u Base URL of your AGLedger instance (or AGLEDGER_API_URL env
56
82
  var). Required: AGLedger is self-hosted, so there is no
57
83
  default server to call.
84
+ --timeout Seconds to wait for each API response (or AGLEDGER_TIMEOUT
85
+ env var). Default 30, at most 2147483. A call that times
86
+ out may still have been applied: retry a POST with the
87
+ idempotencyKey the timeout error names, never a new one.
58
88
  --help, -h Show this help message
59
89
 
60
90
  Credentials: one is required. An API key wins when set; otherwise an OIDC
@@ -67,7 +97,13 @@ request bodies. Nothing is written to disk.
67
97
  AGLEDGER_OIDC_TOKEN_FILE File holding an OIDC JWT; read on every exchange,
68
98
  so a rotated Kubernetes projected token is picked
69
99
  up.
70
- AGLEDGER_OIDC_AGENT_ID Optional agent id to bind the cert to.
100
+ AGLEDGER_OIDC_AGENT_ID Optional assertion of the agent id the token
101
+ binds to. The token decides the agent; a
102
+ different id, or any id on a token bound to
103
+ no agent, is 403 CERT_AGENT_BINDING_MISMATCH.
104
+ Bind an agent with PATCH /v1/agents/{id}
105
+ (oidcIss, oidcSub) or claimMapping.agent_id
106
+ on the trusted issuer.
71
107
 
72
108
  Delegation (optional): when the agent acts for a person or another party, an
73
109
  RFC 8693 token-exchange result token is sent as AGLedger-On-Behalf-Of on every
@@ -140,6 +176,26 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
140
176
  'AGLedger is self-hosted, so the MCP server cannot guess your Server.\n');
141
177
  process.exit(EXIT_USAGE_ERROR);
142
178
  }
179
+ // A URL that does not parse used to start the server, which then failed
180
+ // every tool call; `localhost:3000` parses, with `localhost:` as its scheme.
181
+ // Only an absolute http(s) URL can reach a Server.
182
+ const urlProblem = apiUrlProblem(apiUrl);
183
+ if (urlProblem) {
184
+ const origin = values['api-url'] !== undefined ? '--api-url' : 'AGLEDGER_API_URL';
185
+ process.stderr.write(`Error: the API URL from ${origin} (${JSON.stringify(apiUrl)}) ${urlProblem}. ` +
186
+ 'Give the full base URL of your AGLedger Server, scheme included, for example https://agledger.internal.\n');
187
+ process.exit(EXIT_USAGE_ERROR);
188
+ }
189
+ const timeoutRaw = values.timeout ?? process.env.AGLEDGER_TIMEOUT;
190
+ if (timeoutRaw !== undefined) {
191
+ const problem = timeoutProblem(timeoutRaw);
192
+ if (problem) {
193
+ const origin = values.timeout !== undefined ? '--timeout' : 'AGLEDGER_TIMEOUT';
194
+ process.stderr.write(`Error: the timeout from ${origin} (${JSON.stringify(timeoutRaw)}) ${problem}. ` +
195
+ 'Give the seconds to wait for each API response, for example 60.\n');
196
+ process.exit(EXIT_USAGE_ERROR);
197
+ }
198
+ }
143
199
  const oboCmd = process.env[ON_BEHALF_OF_ENV.CMD] || undefined;
144
200
  const oboFile = process.env[ON_BEHALF_OF_ENV.FILE] || undefined;
145
201
  let onBehalfOf;
@@ -162,6 +218,7 @@ Exit codes: 0 clean, 1 runtime failure, 2 usage or configuration error.
162
218
  const server = new AgledgerMcpServer({
163
219
  ...(apiKey ? { apiKey } : { oidc }),
164
220
  apiUrl,
221
+ ...(timeoutRaw !== undefined ? { timeoutMs: Math.round(Number(timeoutRaw) * 1000) } : {}),
165
222
  ...(onBehalfOf ? { onBehalfOf } : {}),
166
223
  });
167
224
  // A version-skewed zod resolution strips every argument description and the
package/dist/server.d.ts CHANGED
@@ -24,6 +24,28 @@ export interface AgledgerMcpServerOptions {
24
24
  /** Request timeout in milliseconds. Default 30000. */
25
25
  timeoutMs?: number;
26
26
  }
27
+ /**
28
+ * The summary lines on the evidence bodies an `?evidence=true` export
29
+ * inlines, each re-bound to the hash its entry signs. Silent when every one
30
+ * re-bound, or when the export carries none.
31
+ */
32
+ export declare function evidenceLines(counts: {
33
+ present: number;
34
+ verified: number;
35
+ clientHashed: number;
36
+ failed: number;
37
+ }): string[];
38
+ /**
39
+ * The summary lines on the sealed federation messages. `failed` ones failed a
40
+ * check (a key given for the hub that did not match among them); the rest of
41
+ * the unverified ones came from a hub no key was given for.
42
+ */
43
+ export declare function peerMessageLines(wire: {
44
+ present: number;
45
+ verified: number;
46
+ failed: number;
47
+ afterRetirement: number;
48
+ }): string[];
27
49
  export declare class AgledgerMcpServer {
28
50
  readonly mcp: McpServer;
29
51
  readonly client: ApiClient;
package/dist/server.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // for the check that catches a tree which splits them anyway.
14
14
  import { z } from 'zod/v4';
15
15
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
16
- import { verifyAuditExport, } from '@agledger/verify-core';
16
+ import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, suggestion, verifyAuditExport, } from '@agledger/verify-core';
17
17
  import { ApiClient } from './api-client.js';
18
18
  import { OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
19
19
  import { DelegationSource, DelegationSourceError } from './delegation.js';
@@ -29,7 +29,8 @@ const QUICKSTART = {
29
29
  ],
30
30
  };
31
31
  const DOCS = {
32
- description: 'Every API response includes nextSteps for self-guided workflow discovery. ' +
32
+ description: 'Most API responses carry nextSteps for self-guided workflow discovery; follow them when present ' +
33
+ '(listings, the schema catalogue and the org listing carry none). ' +
33
34
  'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog, ' +
34
35
  'and GET /llms.txt (also exposed as the agledger://llms.txt resource) for the prose narrative ' +
35
36
  'written for agents: what the product is for, the vocabulary, and how the pieces fit together. ' +
@@ -155,7 +156,7 @@ function parseJsonObject(value, fieldName) {
155
156
  /**
156
157
  * Parse a JSON-encoded object OR array. Used for fields that legitimately
157
158
  * accept either shape (e.g. `agledger_verify.publicKeys`, which accepts verify-core
158
- * `OutOfBandKeyEntry[]` polymorphism). Strings,
159
+ * `SuppliedKeyEntry[]` polymorphism). Strings,
159
160
  * numbers, booleans, and null still fail loudly.
160
161
  */
161
162
  function parseJsonObjectOrArray(value, fieldName) {
@@ -192,6 +193,100 @@ function unwrapVerificationKeys(raw) {
192
193
  }
193
194
  return raw;
194
195
  }
196
+ /**
197
+ * The verdict as text plus the next step, carried as the result's `summary`,
198
+ * worded as the other verifiers word their headlines. Worded
199
+ * from `valid` and `keyTrust.status` only: an applicability flag says a check
200
+ * ran, never that it passed, so no sentence here claims agreement on anything
201
+ * but the verdict. An unanchored result never reads as a pass.
202
+ */
203
+ function verifyVerdictText(result) {
204
+ const trust = result.keyTrust;
205
+ const verdict = result.verdict;
206
+ const lines = [];
207
+ if (verdict === 'failed') {
208
+ const at = result.brokenAt;
209
+ lines.push(at
210
+ ? `Verdict: FAIL at position ${at.position}: ${at.code}.${at.detail ? ` ${at.detail}` : ''}`
211
+ : 'Verdict: FAIL.');
212
+ lines.push('Verification FAILED: the chain or the key statements do not hold up.');
213
+ for (const f of trust.findings) {
214
+ lines.push(`Key finding: ${f.code}${f.keyId ? ` (${f.keyId})` : ''}: ${f.detail}`);
215
+ }
216
+ if (at)
217
+ lines.push(`Next: ${suggestion(at.code)}`);
218
+ }
219
+ else if (verdict === 'trusted') {
220
+ lines.push(`Verdict: PASS. Nothing failed, and every signature was checked under a key the signed key statements ` +
221
+ `link to a trust anchor you gave (${trust.anchors.join(', ')}). ` +
222
+ `${result.verifiedEntries}/${result.totalEntries} entries verified.`);
223
+ }
224
+ else if (trust.status === 'no_anchored_signature') {
225
+ lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: the trustAnchors ' +
226
+ `(${trust.anchors.join(', ')}) were walked, but no signature here verified under a key they anchor. ` +
227
+ 'An entry that carries no signature proves nothing about who wrote it.');
228
+ lines.push('Next: if the entries are signed, check that each trustAnchors digest is a vault key of the install that wrote ' +
229
+ 'this export (ask the operator). An export with no signed entry cannot be anchored.');
230
+ }
231
+ else {
232
+ lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: no trustAnchors were ' +
233
+ 'given, so every signing key was taken on the word of the export itself, and a key written into the ' +
234
+ "Server's database alone would verify.");
235
+ lines.push('Next: call agledger_verify again with trustAnchors set to the sha256:<hex> digest of a vault key taken out of ' +
236
+ 'band (the installer prints the first vault key\'s; ask the operator). ' +
237
+ (trust.anchoredFrom
238
+ ? `The export names its Server's key as ${trust.anchoredFrom}; that is the export's own claim and is not an anchor.`
239
+ : 'The export names no Server key.'));
240
+ }
241
+ for (const n of trust.notes) {
242
+ lines.push(`Key note: ${n.keyId ? `(${n.keyId}) ` : ''}${n.detail}`);
243
+ }
244
+ const { skipped } = result.signatureCoverage;
245
+ if (result.valid && skipped > 0) {
246
+ lines.push(`${skipped} of ${result.totalEntries} entries carry no signature, so they are covered by the hash chain only.`);
247
+ }
248
+ const { present, verified } = result.agentSignatures;
249
+ if (present > verified) {
250
+ lines.push(`${present - verified} of ${present} agent signatures were not checked: pass agentKeys with the agents' cert public keys to re-verify them.`);
251
+ }
252
+ lines.push(...peerMessageLines(result.federationWire));
253
+ lines.push(...evidenceLines(result.evidenceBinding));
254
+ return lines.join('\n');
255
+ }
256
+ /**
257
+ * The summary lines on the evidence bodies an `?evidence=true` export
258
+ * inlines, each re-bound to the hash its entry signs. Silent when every one
259
+ * re-bound, or when the export carries none.
260
+ */
261
+ export function evidenceLines(counts) {
262
+ const lines = [];
263
+ if (counts.failed > 0) {
264
+ lines.push(`${counts.failed} of ${counts.present} inlined evidence bodies failed CHAIN_EVIDENCE_BINDING_MISMATCH: they do not hash to the evidenceHash or payloadHash their entry signs.`);
265
+ }
266
+ if (counts.clientHashed > 0) {
267
+ lines.push(`${counts.clientHashed} of ${counts.present} inlined evidence bodies are on an encrypted-mode completion, whose signed hash covers a cleartext the export does not carry, so they were not re-bound: decrypt and hash them yourself.`);
268
+ }
269
+ return lines;
270
+ }
271
+ /**
272
+ * The summary lines on the sealed federation messages. `failed` ones failed a
273
+ * check (a key given for the hub that did not match among them); the rest of
274
+ * the unverified ones came from a hub no key was given for.
275
+ */
276
+ export function peerMessageLines(wire) {
277
+ const lines = [];
278
+ if (wire.afterRetirement > 0) {
279
+ lines.push(`${wire.afterRetirement} of ${wire.present} sealed peer messages the peer signed under a key it had already retired: in order when the receiver's federation.peer_revoked audit row for the peer comes after them.`);
280
+ }
281
+ if (wire.failed > 0) {
282
+ lines.push(`${wire.failed} of ${wire.present} sealed peer messages failed CHAIN_FEDERATION_WIRE_INVALID.`);
283
+ }
284
+ const noKey = wire.present - wire.verified - wire.failed;
285
+ if (noKey > 0) {
286
+ lines.push(`${noKey} of ${wire.present} sealed peer messages were hashed and matched to their entry but their peer signature was not checked: pass federationKeys with each sending hub's federation key to re-verify them.`);
287
+ }
288
+ return lines;
289
+ }
195
290
  /**
196
291
  * Every code `agledger_verify` can report, named in its description so a model
197
292
  * can branch on them. The list used to be typed out by hand and fell three
@@ -199,7 +294,8 @@ function unwrapVerificationKeys(raw) {
199
294
  * CHAIN_KEY_NOT_YET_ACTIVE). `ExportCodesMissing` below makes the compiler
200
295
  * fail when verify-core adds an export-level code this list does not carry.
201
296
  * CHECKPOINT_* and TENANT_* are dump-verifier codes and never come back from
202
- * an audit export.
297
+ * an audit export. KEY_* are findings on the export's signed key statements,
298
+ * reported at position 0 when trustAnchors are given.
203
299
  */
204
300
  const EXPORT_FAILURE_CODES = [
205
301
  'CHAIN_HASH_MISMATCH',
@@ -213,6 +309,7 @@ const EXPORT_FAILURE_CODES = [
213
309
  'CHAIN_OIDC_ACTOR_MISMATCH',
214
310
  'CHAIN_SIGNATURE_INVALID',
215
311
  'CHAIN_SIGNATURE_MISSING_KEY',
312
+ 'CHAIN_ENTRY_UNSIGNED',
216
313
  'CHAIN_KEY_POLICY_VIOLATION',
217
314
  'CHAIN_KEY_EXPIRED',
218
315
  'CHAIN_KEY_NOT_YET_ACTIVE',
@@ -220,7 +317,13 @@ const EXPORT_FAILURE_CODES = [
220
317
  'CHAIN_SIGNING_KEY_DRIFT',
221
318
  'CHAIN_ACTOR_ATTRIBUTION_MISMATCH',
222
319
  'CHAIN_AGENT_SIGNATURE_INVALID',
320
+ 'CHAIN_FEDERATION_WIRE_INVALID',
321
+ 'CHAIN_EVIDENCE_BINDING_MISMATCH',
223
322
  'CHAIN_UNSUPPORTED_ALGORITHM',
323
+ 'CHAIN_SIGNING_KEY_UNANCHORED',
324
+ 'KEY_STATEMENT_INVALID',
325
+ 'KEY_CLOSURE_INVALID',
326
+ 'CHAIN_KEY_WINDOW_DRIFT',
224
327
  'UNSUPPORTED_FORMAT',
225
328
  'CHAIN_EMPTY',
226
329
  ];
@@ -260,14 +363,38 @@ const VERIFY_ARGS = {
260
363
  'objects are also accepted for compatibility.'),
261
364
  publicKeys: jsonStringField
262
365
  .optional()
263
- .describe('Optional out-of-band signing keys. Accepts any of these as a JSON-encoded ' +
366
+ .describe('Optional signing keys you supply. Accepts any of these as a JSON-encoded ' +
264
367
  'string (or a native object/array): a compact map ' +
265
368
  '\'{"key-1":"MCowBQYDK2VwAyEA..."}\' (values are base64 SPKI DER; Ed25519 keys ' +
266
369
  'start "MCowBQYDK2Vw", P-256 keys "MFkwEwYHKoZIzj0"), the list shape ' +
267
370
  '\'[{"keyId":"key-1","publicKey":"MCowBQYDK2VwAyEA..."}]\', or the raw ' +
268
371
  'GET /v1/verification-keys response envelope (\'{"data":[...], ...}\'); the ' +
269
372
  '.data array is unwrapped automatically, so the agledger_api response can be ' +
270
- 'passed straight through). Merged over any keys embedded in the export.'),
373
+ 'passed straight through, and each key\'s signed statements are walked with trustAnchors). ' +
374
+ 'Merged over any keys embedded in the export. Where a key came from is not whether it is ' +
375
+ 'trusted: the Server serves these from the same database as the export. That is trustAnchors.'),
376
+ trustAnchors: z
377
+ .array(z.string())
378
+ .optional()
379
+ .describe('Recommended. SPKI digests ("sha256:<64 hex>") of vault keys you took out of band: the installer ' +
380
+ 'prints the first vault key\'s, and the Server\'s signing-key-digest.js derives one from a key ' +
381
+ 'the operator holds. Ask the operator for it; do not take it from the export ' +
382
+ '(exportMetadata.anchoredFrom) or from GET /v1/verification-keys, which are the Server\'s own word. ' +
383
+ 'The signed key statements the export carries are walked from these: an entry signed by a key ' +
384
+ 'the walk does not reach fails CHAIN_SIGNING_KEY_UNANCHORED, and a statement that does not hold ' +
385
+ 'fails at position 0 with KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID or CHAIN_KEY_WINDOW_DRIFT. ' +
386
+ 'Without it, result.keyTrust.status is "no_anchor": valid:true then means only that the chain ' +
387
+ 'is intact against keys nobody pinned, not that it is trusted.'),
388
+ distrustedKeys: z
389
+ .array(z.string())
390
+ .optional()
391
+ .describe('Optional. The operator\'s VAULT_DISTRUSTED_KEYS entries: "sha256:<64 hex>", optionally ' +
392
+ '"@<RFC 3339 instant>". What such a key signed from that instant (with none, from its retirement) ' +
393
+ 'counts for nothing in the walk. Requires trustAnchors. A dated entry may name a key also in ' +
394
+ 'trustAnchors, which then vouches for what that key signed before the instant; an undated one may not. ' +
395
+ 'Where an export lists a key retired at the instant the Server distrusts it from (distrustedFrom), earlier ' +
396
+ 'than its signed retirement, a run without the same entry fails on that window, and the finding names the ' +
397
+ 'distrustedKeys entry to confirm with the operator.'),
271
398
  agentKeys: jsonStringField
272
399
  .optional()
273
400
  .describe('Optional Ed25519 public keys of agent certs, as a JSON-encoded array of JWKs ' +
@@ -275,17 +402,32 @@ const VERIFY_ARGS = {
275
402
  'An entry whose sealed agent signature names one of these keys by thumbprint has that ' +
276
403
  'signature re-verified offline, and fails CHAIN_AGENT_SIGNATURE_INVALID if it does not verify. ' +
277
404
  'Without it, agent signatures are counted in result.agentSignatures but not checked.'),
405
+ federationKeys: jsonStringField
406
+ .optional()
407
+ .describe('Optional peer federation keys, as a JSON-encoded object \'{"<hubId>":"<key>"}\' or array ' +
408
+ '\'[{"hubId":"...","publicKey":"..."}]\', each key the peer Server\'s Ed25519 federation key as its ' +
409
+ 'operator gives it (base64 SPKI DER, or base64 of the raw 32 bytes the handshake registered). ' +
410
+ 'A receiving Server seals each peer message it accepts on the chain entry it writes (payload.wire), ' +
411
+ 'as the peer signed it. Every sealed message is held to its body hash and to its entry; one from a ' +
412
+ 'hub given here also has its signature re-verified under that key, which proves what the peer ' +
413
+ 'asserted from this export alone, and fails CHAIN_FEDERATION_WIRE_INVALID if it does not verify. ' +
414
+ 'After a peer changes its federation key, add "history" to an array entry: the JSON the peer serves at ' +
415
+ 'GET /.well-known/agledger-federation-keys.json (no auth). Every key it links to that entry\'s publicKey ' +
416
+ 'through successions both keys signed is then trusted inside its window, so entries sealed before the ' +
417
+ 'change verify; each message is placed in its key\'s window by its signed wire.timestamp. A hub may appear ' +
418
+ 'twice, to pin a key no succession links or one the history does not list. ' +
419
+ 'result.federationWire counts present, verified, failed and afterRetirement (verified, but signed by the ' +
420
+ 'peer under a key it had already retired).'),
278
421
  requireKeyId: z
279
422
  .string()
280
423
  .optional()
281
424
  .describe('If set, every entry must reference this keyId. Rejects exports signed by a ' +
282
425
  'retired or unexpected key even if cryptographically valid.'),
283
- requireOutOfBandKeys: z
426
+ requireSuppliedKeys: z
284
427
  .boolean()
285
428
  .optional()
286
- .describe('High-assurance: refuse keys embedded in the export. An entry whose only key is ' +
287
- 'export-embedded fails CHAIN_KEY_POLICY_VIOLATION, forcing verification against ' +
288
- 'keys supplied out of band via publicKeys.'),
429
+ .describe('Refuse keys embedded in the export: an entry whose only key is export-embedded fails ' +
430
+ 'CHAIN_KEY_POLICY_VIOLATION, so every signature is checked against a key from publicKeys.'),
289
431
  };
290
432
  export class AgledgerMcpServer {
291
433
  mcp;
@@ -387,8 +529,10 @@ export class AgledgerMcpServer {
387
529
  });
388
530
  this.mcp.registerTool('agledger_api', {
389
531
  title: 'AGLedger API',
390
- description: 'Make any AGLedger API call. All paths start with /v1/. ' +
391
- 'The API returns nextSteps on every response: follow them. Workflow: ' +
532
+ description: 'Make any AGLedger API call. API routes live under /v1/; the discovery documents ' +
533
+ '(/openapi.json, /llms.txt, /llms-full.txt, /lifecycle) and /a2a sit at the root. ' +
534
+ 'Most responses carry nextSteps: follow them when present (listing pages, GET /v1/schemas ' +
535
+ 'and GET /v1/admin/orgs carry none). Workflow: ' +
392
536
  '1. GET /v1/schemas, list Record types. ' +
393
537
  '2. GET /v1/schemas/{type}, get required fields and examples. ' +
394
538
  '3. POST /v1/records, create a record. ' +
@@ -429,6 +573,7 @@ export class AgledgerMcpServer {
429
573
  const refused = unknownArgumentResult('agledger_api', API_ARGS, args, 'The request body (POST/PUT/PATCH) and the query string (GET/DELETE) both go in `params`.');
430
574
  if (refused)
431
575
  return refused;
576
+ let sentKey;
432
577
  try {
433
578
  const { method, path, params, idempotencyKey } = args;
434
579
  if (!path.startsWith('/')) {
@@ -450,8 +595,11 @@ export class AgledgerMcpServer {
450
595
  return errorResult('Path contains control characters.', 'PATH_INVALID', 'Remove control characters (newlines, tabs, null bytes) from the path.');
451
596
  }
452
597
  const options = {};
453
- if (idempotencyKey !== undefined)
454
- options.idempotencyKey = idempotencyKey;
598
+ // The key is fixed here, not left for the client to generate, so a
599
+ // timeout error can name the key that went out. Only POST carries one.
600
+ sentKey = method === 'POST' ? (idempotencyKey ?? crypto.randomUUID()) : undefined;
601
+ if (sentKey !== undefined)
602
+ options.idempotencyKey = sentKey;
455
603
  if (params !== undefined && params !== '') {
456
604
  const decoded = parseJsonObject(params, 'params');
457
605
  if (!decoded.ok)
@@ -485,10 +633,14 @@ export class AgledgerMcpServer {
485
633
  if (credentialError)
486
634
  return credentialError;
487
635
  if (err instanceof DOMException && err.name === 'AbortError') {
488
- return errorResult('The API did not respond in time. Retry the same request.', 'TIMEOUT', 'Retry the same request. Increase --timeout if your instance is slow to respond.');
636
+ return errorResult('The API did not respond in time. The request may still have been applied.', 'TIMEOUT', sentKey
637
+ ? `Retry the same request with idempotencyKey "${sentKey}": the Server returns the original result if the first attempt was applied, and applies it once if not. A new key can create a duplicate. If your instance is slow to respond, start agledger-mcp with --timeout <seconds> (or AGLEDGER_TIMEOUT).`
638
+ : 'Retry the same request. This method carries no idempotency key. If your instance is slow to respond, start agledger-mcp with --timeout <seconds> (or AGLEDGER_TIMEOUT).', sentKey ? { idempotencyKey: sentKey } : undefined);
489
639
  }
490
640
  if (err instanceof TypeError && err.message.includes('fetch')) {
491
- return errorResult(err.message, 'NETWORK_ERROR', 'Check that the API URL is correct. Try GET /health to verify connectivity.');
641
+ return errorResult(err.message, 'NETWORK_ERROR', sentKey
642
+ ? `Check that the API URL is correct. Try GET /health to verify connectivity. If the connection dropped after the request went out it may have been applied: retry with idempotencyKey "${sentKey}", never a new key.`
643
+ : 'Check that the API URL is correct. Try GET /health to verify connectivity.', sentKey ? { idempotencyKey: sentKey } : undefined);
492
644
  }
493
645
  return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
494
646
  }
@@ -499,12 +651,18 @@ export class AgledgerMcpServer {
499
651
  'Decodes each entry\'s tagged COSE_Sign1 envelope (RFC 9052), recomputes ' +
500
652
  'sha256 over the envelope bytes, walks the hash chain, cross-checks the protected-' +
501
653
  'header chain claim against the row columns, and verifies every envelope signature (Ed25519 or ES256, dispatched from the trusted key material; anything else fails closed). ' +
502
- 'No network calls. For an independent audit, pass publicKeys obtained out of band ' +
503
- '(GET /v1/verification-keys or /.well-known/scitt-keys) rather than trusting the ' +
504
- 'export\'s embedded keys; result.keyProvenance reports out-of-band vs embedded key use. ' +
654
+ 'No network calls. Pass trustAnchors (the sha256:<hex> digest of a vault key the operator ' +
655
+ 'took out of band) so the export\'s signed key statements are walked from a key you trust: ' +
656
+ 'without it the keys are taken on the export\'s word and keyTrust.status is "no_anchor". ' +
657
+ 'result.verdict is "trusted" (PASS: valid, and keyTrust.status "walked"), "failed", or "unanchored" ' +
658
+ '(VERIFIED, NOT ANCHORED: valid, but keyTrust.status "no_anchor", or "no_anchored_signature" when the ' +
659
+ 'anchors were walked and no signature verified under a key they anchor); an unanchored result is not a trusted verdict. ' +
660
+ 'result.summary states the verdict in words and the next step. ' +
505
661
  'On failure, brokenAt pinpoints the first entry that failed and its canonical code ' +
506
662
  `(${EXPORT_FAILURE_CODES.join(', ')}); CHAIN_UNSUPPORTED_ALGORITHM means this build ` +
507
663
  'could not compute the key\'s algorithm: upgrade, and never read it as a pass. Obtain the export via agledger_api with method=GET, path=/v1/records/{id}/audit-export. ' +
664
+ 'Add params \'{"evidence":true}\' to inline each completion\'s evidence and each dispute\'s filed payload: every inlined body is ' +
665
+ 're-bound to the hash its entry signs (result.evidenceBinding; an edited one fails CHAIN_EVIDENCE_BINDING_MISMATCH). ' +
508
666
  'For the raw COSE_Sign1 stream, use path=/v1/records/{id}/attestation.',
509
667
  inputSchema: toolInput(VERIFY_ARGS),
510
668
  annotations: {
@@ -522,7 +680,7 @@ export class AgledgerMcpServer {
522
680
  if (refused)
523
681
  return refused;
524
682
  try {
525
- const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, requireKeyId, requireOutOfBandKeys, } = args;
683
+ const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, federationKeys: federationKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, } = args;
526
684
  const decodedExport = parseJsonObject(exportRaw, 'export');
527
685
  if (!decodedExport.ok)
528
686
  return decodedExport.error;
@@ -530,6 +688,27 @@ export class AgledgerMcpServer {
530
688
  if (!('entries' in exportData)) {
531
689
  return errorResult('Input is not a valid audit export. Expected an object with exportMetadata and entries.', 'INVALID_EXPORT', 'Call agledger_api with method=GET and path=/v1/records/{id}/audit-export, then pass the response body as the `export` argument.');
532
690
  }
691
+ // Parsed here as well as in verify-core so a malformed digest is
692
+ // reported against the argument that carried it.
693
+ try {
694
+ parseTrustAnchors(trustAnchors ?? []);
695
+ parseDistrustedKeys(distrustedKeys ?? []);
696
+ }
697
+ catch (err) {
698
+ return errorResult(err instanceof Error ? err.message : String(err), 'INVALID_ARGUMENT', 'Pass trustAnchors as ["sha256:<64 hex>"] and distrustedKeys as ["sha256:<64 hex>" or "sha256:<64 hex>@<RFC 3339 instant>"].');
699
+ }
700
+ try {
701
+ assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys);
702
+ }
703
+ catch (err) {
704
+ return errorResult(err instanceof Error ? err.message : String(err), 'INVALID_ARGUMENT', 'Keep the pin and give the leaked key the instant it leaked, "sha256:<64 hex>@<RFC 3339 instant>"; or, if nothing it signed is vouched for, drop it from trustAnchors.');
705
+ }
706
+ const anchored = trustAnchors !== undefined && trustAnchors.length > 0;
707
+ // verify-core reads distrusted keys only during the walk, so without
708
+ // an anchor they would be dropped without a word.
709
+ if (!anchored && distrustedKeys !== undefined && distrustedKeys.length > 0) {
710
+ return errorResult('distrustedKeys is read only during the key-statement walk, which needs trustAnchors.', 'INVALID_ARGUMENT', 'Pass trustAnchors with the sha256:<hex> digest of a vault key the operator took out of band.');
711
+ }
533
712
  let publicKeys;
534
713
  if (publicKeysRaw !== undefined && publicKeysRaw !== '') {
535
714
  const decodedKeys = parseJsonObjectOrArray(publicKeysRaw, 'publicKeys');
@@ -547,13 +726,26 @@ export class AgledgerMcpServer {
547
726
  }
548
727
  agentKeys = decodedAgentKeys.value;
549
728
  }
729
+ let federationKeys;
730
+ if (federationKeysRaw !== undefined && federationKeysRaw !== '') {
731
+ const decodedFederationKeys = parseJsonObjectOrArray(federationKeysRaw, 'federationKeys');
732
+ if (!decodedFederationKeys.ok)
733
+ return decodedFederationKeys.error;
734
+ federationKeys = decodedFederationKeys.value;
735
+ }
550
736
  const result = verifyAuditExport(exportData, {
551
737
  publicKeys,
552
738
  agentKeys,
739
+ federationKeys,
553
740
  requireKeyId,
554
- requireOutOfBandKeys,
741
+ requireSuppliedKeys,
742
+ ...(anchored ? { trustAnchors, distrustedKeys } : {}),
555
743
  });
556
- const structured = result;
744
+ // verify-core's result verbatim, verdict first (`valid` alone is true
745
+ // on a run that anchored nothing), with the verdict in words and the
746
+ // next step as `summary`, in the one JSON text block.
747
+ const { verdict, ...rest } = result;
748
+ const structured = { verdict, summary: verifyVerdictText(result), ...rest };
557
749
  return {
558
750
  content: mirrorContent(structured),
559
751
  structuredContent: structured,
@@ -561,7 +753,10 @@ export class AgledgerMcpServer {
561
753
  };
562
754
  }
563
755
  catch (err) {
564
- return errorResult(err instanceof Error ? err.message : String(err), 'VERIFY_FAILED');
756
+ // verify-core throws TypeError only on input it refuses (a supplied
757
+ // key's window that is not RFC 3339, a malformed key list): that is
758
+ // the caller's argument, not a failed verification.
759
+ return errorResult(err instanceof Error ? err.message : String(err), err instanceof TypeError ? 'INVALID_ARGUMENT' : 'VERIFY_FAILED');
565
760
  }
566
761
  });
567
762
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agledger/mcp-server",
3
- "version": "2.11.0",
4
- "description": "AGLedger MCP Server: thin API pass-through for AI agents via MCP protocol",
3
+ "version": "3.1.0",
4
+ "description": "AGLedger MCP server: the AGLedger API as MCP tools, so any MCP-capable agent can write to the signed ledger.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "AGLedger LLC",
7
7
  "repository": {
@@ -55,7 +55,7 @@
55
55
  "prepublishOnly": "npm run build && npm run lint:pkg"
56
56
  },
57
57
  "dependencies": {
58
- "@agledger/verify-core": "^1.5.0",
58
+ "@agledger/verify-core": "^2.1.0",
59
59
  "@modelcontextprotocol/sdk": "^1.30.0",
60
60
  "zod": "^3.25.0 || ^4.0.0"
61
61
  },