@agledger/mcp-server 2.11.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,31 @@ All notable changes to the AGLedger MCP Server will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [3.0.0] - 2026-10-05
8
+
9
+ Targets API 2.0 only. The major version follows the API's, and is 3 because this server is at 2.x. 2.12.0 was never published; its changes are part of this release.
10
+
11
+ ### Breaking
12
+
13
+ - **`agledger_verify` takes `requireSuppliedKeys`, not `requireOutOfBandKeys`.** A key the Server serves at `/v1/verification-keys` comes from the same database as the export, so "out of band" promised an independence the argument never gave. Behaviour is unchanged, and the old name is refused as an unknown argument. In the result, `keyProvenance.outOfBand` is `keyProvenance.supplied`, `optionalChecks` carries `key_anchoring`, and every result carries `keyTrust`.
14
+ - **`agledger_verify` reports a verdict, as `@agledger/verify` and `agledger verify` do.** `structuredContent` carries `verdict` beside verify-core's result: `trusted` when the chain is valid and `keyTrust.status` is `walked`, `failed` when it is not valid, and `unanchored` otherwise. The one text block mirrors `structuredContent` as JSON, which also carries `summary`: the verdict in the other verifiers' words (`Verdict: PASS`, `Verdict: VERIFIED, NOT ANCHORED`, `Verdict: FAIL`) with the next step, worded from `valid` and `keyTrust.status` only. `verdict` is the one `@agledger/verify-core` now puts on its result. An unanchored result says it is not a trusted verdict, and `isError` stays false for it. It is unanchored in two cases: without `trustAnchors` (`keyTrust.status` `no_anchor`), where the text names the key the export claims as its Server's (`exportMetadata.anchoredFrom`, which is not an anchor) and says to call the tool again with a pin; and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`), as for an export of unsigned entries pinned on any key. Entries that carry no signature are named as covered by the hash chain only, and agent signatures left unchecked are counted.
15
+
16
+ ### Added
17
+
18
+ - **`agledger_verify` takes `trustAnchors` and `distrustedKeys`**, through `@agledger/verify-core` 2.0.0. `trustAnchors` is the SPKI digests (`sha256:<hex>`) of vault keys the operator took out of band; the signed key statements the export carries, plus the `statements` on keys passed as `publicKeys`, are walked from them. An entry signed by a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails at position 0 with `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`; the tool description names all four, and the compile-time check that it names every export code now covers `KEY_*`. `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries; without `trustAnchors` it is refused (`INVALID_ARGUMENT`) rather than ignored, as is a malformed digest and a pinned key distrusted with no instant, which the Server refuses to start with. A pin beside a dated entry for the same key (`sha256:<hex>@<instant>`) is taken and vouches for what the key signed before the instant; an export accounts for nothing a distrusted key signed (`keyTrust.accounted` is empty), so such entries fail. Any other input verify-core refuses (a supplied key window that is not RFC 3339, an agent key that is not an Ed25519 JWK) is `INVALID_ARGUMENT` rather than `VERIFY_FAILED`. Both publish as flat string arrays. Every export vector in the API 2.0 conformance corpus was driven through the packed server over stdio, unpinned and pinned on the key the export names. Unpinned, each returned its manifest's expected result, a pass as `unanchored` and a failure as `failed` with the manifest's code. Pinned, every failing vector fails with the same code and every passing vector is `trusted`, with two exceptions that are correct: `key-substitution.json` fails `CHAIN_SIGNING_KEY_UNANCHORED` on the substituted key, and `unsigned.json`, which names no Server key and carries no signature to anchor, is `unanchored` (`no_anchored_signature`) pinned on any key.
19
+
20
+ - **`agledger_verify` names the distrust entry an export says the Server applied.** An API 2.0 export lists a key the Server's `VAULT_DISTRUSTED_KEYS` names with `distrustedFrom` in `exportMetadata.signingKeyWindows`, which verify-core reads: where that entry cut the listed retirement and the call did not pass the same `distrustedKeys` entry, the `CHAIN_KEY_WINDOW_DRIFT` (or `KEY_CLOSURE_INVALID`) finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`) to confirm with the Server's operator rather than reading as a rewritten column, says when the given entry carries another instant, and an earlier given instant is a `Key note:` in `summary`. The verdict is as before. The wording names `distrustedKeys` and `trustAnchors`, which are this tool's own argument names.
21
+ - **`agledger_verify` reports an unsigned entry written while the vault was signing.** An entry with no signing key fails with the new `CHAIN_ENTRY_UNSIGNED` when an earlier entry in its chain names a key, or when it was written at or after the earliest activation time among the keys the verifier holds. An unsigned history written before the first key stays reduced coverage, as before. An entry that names a key but carries an all-zero signature now fails `CHAIN_SIGNATURE_INVALID`. Both match the Server's own chain verification.
22
+
23
+ ### Changed
24
+
25
+ - **A timeout names the key to retry with, and `--timeout` exists.** The `TIMEOUT` error told an agent to retry the same request and to raise `--timeout`, which the binary rejected as an unknown option; the retry then created a second record, because the generated `Idempotency-Key` was never shown. A POST that times out, or whose connection fails, now returns the key it sent as `idempotencyKey` and says to retry with that exact key. A request with no key (any other method) says so rather than naming one. `--timeout <seconds>` (or `AGLEDGER_TIMEOUT`) sets the wait for each response, default 30, and anything but a positive number up to 2147483 exits 2.
26
+ - **A malformed API URL refuses startup.** An `--api-url` or `AGLEDGER_API_URL` that is not an absolute `http` or `https` URL (`not-a-url`, or `localhost:3000` with no scheme) exits 2 before the server accepts a connection, naming where the URL came from, like the other configuration refusals. It used to start, exit 0 on EOF, and leave every tool call to fail.
27
+ - `agledger_verify` walks an export's key statements in write order (`createdAt`, then `id`), which every API 2.0 export carries, so the key-anchoring findings name the statement row, and a trusted key's later admissions date its window as the Server's do. The write times decide only the order: they are not signed, so a key statement signed by a key in `distrustedKeys` counts for nothing whatever time it carries. A statement that counts for nothing only because its signer is distrusted, dated before the cutoff by the export's own unsigned write time, is a `keyTrust.notes` entry rather than a finding, so an honest rotation away from a key distrusted after it still passes pinned on its successor. The verdict text lists each note as `Key note:`.
28
+ - **A refused OIDC cert exchange reports the Server's `detail`.** API 2.0 removed the top-level `message` from every RFC 9457 error body, leaving `detail` as the one human-readable field. The exchange error read `message`, so against a 2.0 Server an expired or unbound token surfaced as "returned 401" with the Server's reason gone (mcp-server#33). It now reads `detail`. The error body is still forwarded to the tool result as the Server sent it, scrubbed of the token. The server's own errors (`{error, message, code, suggestion}`) keep their `message`; they are not API bodies.
29
+ - **The README says the Server verifies the body signature on every authenticated route** under cert auth and seals it into every chain entry the request writes, rather than recording it on some routes and ignoring it elsewhere (mcp-server#34). The server sends `X-Agent-Signature` only with the OIDC cert credential and only on a request with a body, since the Server refuses the headers with 400 under any other credential (an API key, or an admin or platform OIDC bearer).
30
+ - **`AGLEDGER_OIDC_AGENT_ID` is documented as an assertion, not a choice of agent.** The Server binds a cert to the agent the token names (a mapped `agent_id` claim, else the agent carrying the token's `oidcIss`/`oidcSub`, else an auto-provisioned one), and never to one the request body chooses. When `AGLEDGER_OIDC_AGENT_ID` names a different agent, or the token binds none, the exchange is refused with 403 `CERT_AGENT_BINDING_MISMATCH`; a token bound to a federation shadow agent is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`. `--help` and the README now say so, and point at binding the agent instead: `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub`, or `claimMapping.agent_id` on the trusted issuer. The server still sends the id when it is set, and the refusal reaches the tool result as `OIDC_EXCHANGE_FAILED` with the Server's status, error body, and `recoveryHint` as the `suggestion`, as it did before.
31
+
7
32
  ## [2.11.0] - 2026-09-21
8
33
 
9
34
  ### Added
package/README.md CHANGED
@@ -37,8 +37,9 @@ Add to your MCP client configuration (e.g. `claude_desktop_config.json`):
37
37
 
38
38
  Both flags are required, unless an OIDC token source stands in for the key (see
39
39
  [below](#authenticating-with-oidc-instead-of-an-api-key)). AGLedger is
40
- self-hosted, so there is no default server to call: without `--api-url` the
41
- server exits before it accepts a connection.
40
+ self-hosted, so there is no default server to call: without `--api-url`, or
41
+ with one that is not an absolute `http` or `https` URL, the server exits before
42
+ it accepts a connection.
42
43
 
43
44
  Or run directly:
44
45
 
@@ -47,7 +48,7 @@ agledger-mcp --api-key <key> --api-url <url>
47
48
  ```
48
49
 
49
50
  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
51
+ (missing flag, unknown flag, an API URL that is not an `http(s)` URL), so a launcher can tell a misconfiguration from a
51
52
  crash.
52
53
 
53
54
  ## Authenticating with OIDC instead of an API key
@@ -57,18 +58,29 @@ provider as a trusted issuer for agents, the MCP server can run with no API key
57
58
  at all. Give it a source of OIDC tokens instead. It exchanges a token for a
58
59
  short-lived cert signed by the Server (`POST /v1/auth/oidc/cert`), presents the
59
60
  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`).
61
+ only in its own memory. The Server verifies that signature and seals it into
62
+ every chain entry the agent writes (`predicate.on_behalf_of.agent_signature`).
62
63
  Nothing is written to disk.
63
64
 
64
65
  | Env var | Description |
65
66
  |---------|-------------|
66
67
  | `AGLEDGER_OIDC_TOKEN_FILE` | A file holding an OIDC JWT, such as a Kubernetes projected service-account token. Read on every exchange, so a token rotated on disk is picked up. |
67
68
  | `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. |
69
+ | `AGLEDGER_OIDC_AGENT_ID` | Optional. An assertion of the agent id the token binds to, sent on the exchange. It never chooses the agent: when it names a different one, or the token binds none, the Server refuses the exchange with 403 `CERT_AGENT_BINDING_MISMATCH` rather than issue a cert for an agent you did not expect. Leave it unset unless you want that check. |
69
70
 
70
71
  An API key wins when one is set, then the command, then the file.
71
72
 
73
+ **The token decides which agent the cert binds to**, never the MCP server's
74
+ configuration. An administrator binds an agent to the token's identity in one
75
+ of two ways: `PATCH /v1/agents/{id}` with `oidcIss` and `oidcSub` (the token's
76
+ issuer and subject), or a `claimMapping` of `agent_id` on the trusted issuer,
77
+ which reads the agent id from a claim in the token. An issuer that
78
+ auto-provisions agents creates one for an unbound subject instead. A token that
79
+ binds no agent is refused, and the Server's `recoveryHint` says which binding is
80
+ missing. A token bound to a federation shadow agent (one listed at
81
+ `GET /v1/peer-agents`) is refused with 403 `SHADOW_AGENT_CERT_FORBIDDEN`: that
82
+ agent authenticates on its own Server.
83
+
72
84
  ```bash
73
85
  AGLEDGER_OIDC_TOKEN_FILE=/var/run/secrets/agledger/token \
74
86
  agledger-mcp --api-url https://your-agledger-instance
@@ -93,7 +105,7 @@ the Server answers 401 (a revoked cert), after which the request is retried a
93
105
  single time. A refresh that fails while the current cert is still valid keeps
94
106
  the current cert and prints one warning on stderr. When the exchange itself is
95
107
  refused, the tool result carries `code: OIDC_EXCHANGE_FAILED`, the Server's
96
- status and error body, and its `recoveryHint`.
108
+ status and error body, and its `recoveryHint` as the result's `suggestion`.
97
109
 
98
110
  The Server exchanges a token id (`jti`) only once, so every exchange needs a
99
111
  new token. A command runs on every exchange; a file is read on every exchange,
@@ -151,7 +163,7 @@ to compare, and it is recorded `unbound`.
151
163
  |------|-------------|
152
164
  | `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
153
165
  | `agledger_api` | Make any AGLedger API call (method, path, params). Every POST carries a generated `Idempotency-Key`; pass `idempotencyKey` to reuse the first attempt's key when retrying a call that may already have landed. The API returns `nextSteps` on every response for self-guided workflow discovery. |
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`. |
166
+ | `agledger_verify` | Verify a record audit export offline (COSE_Sign1 envelopes per RFC 9052, hash chain + envelope signatures, Ed25519 or ES256). No network calls. Returns the verifier's result as one JSON text block (the same object as `structuredContent`), with `summary` stating the verdict and the next step. Pass `trustAnchors` (`["sha256:<digest>"]`, the SPKI digest of a vault key the operator took out of band; the installer prints the first one) so the export's signed key statements are walked from a key you trust: an entry under a key the walk does not reach fails `CHAIN_SIGNING_KEY_UNANCHORED`, and a statement that does not hold fails `KEY_STATEMENT_INVALID`, `KEY_CLOSURE_INVALID` or `CHAIN_KEY_WINDOW_DRIFT`. The result carries `verdict`: `trusted` (text `Verdict: PASS`) only when the chain is valid and the walk reached a signature, `failed` (`Verdict: FAIL`), or `unanchored` (`Verdict: VERIFIED, NOT ANCHORED`), which is not a trusted verdict. A run is unanchored without `trustAnchors` (`keyTrust.status` `no_anchor`, the keys taken on the export's word) and when the pin was walked but no signature verified under a key it anchors (`no_anchored_signature`, as for an export of unsigned entries). `distrustedKeys` takes the operator's `VAULT_DISTRUSTED_KEYS` entries and needs `trustAnchors`, and a key both pinned and distrusted is refused (`INVALID_ARGUMENT`), as the Server refuses to start with it; a key statement a distrusted key signed counts for nothing at any instant, because the write times an export carries are not signed. Where an export lists a key retired at the instant the Server distrusts it from (`distrustedFrom`), earlier than its signed retirement, a pinned call without the same `distrustedKeys` entry fails on that key's window (`CHAIN_KEY_WINDOW_DRIFT`, or `KEY_CLOSURE_INVALID` where no closure retires it), and the finding names the entry (`distrustedKeys sha256:<hex>@<distrustedFrom>`), the listing's unsigned word, to confirm with the operator before passing it. `publicKeys` supplies keys (the `GET /v1/verification-keys` response works as is), `requireSuppliedKeys` refuses the export's embedded keys, and `agentKeys` (the agents' cert public keys as JWKs) re-verifies the agent signatures sealed in the chain. Input verify-core refuses, such as a supplied key window that is not RFC 3339, is `INVALID_ARGUMENT`. Built on the shared `@agledger/verify-core`. |
155
167
 
156
168
  ## Resources
157
169
 
@@ -179,6 +191,9 @@ Every API error response includes a `recoveryHint` naming the fix, so an agent c
179
191
  |------|---------|-------------|
180
192
  | `--api-key` | `AGLEDGER_API_KEY` | AGLedger API key. Required unless an OIDC token source is set (see above). |
181
193
  | `--api-url` | `AGLEDGER_API_URL` | API base URL of your instance (required). AGLedger is self-hosted, so there is no default; the server refuses to start without it. |
194
+ | `--timeout` | `AGLEDGER_TIMEOUT` | Seconds to wait for each API response (default 30). A positive number up to 2147483; anything else exits 2. |
195
+
196
+ A call that times out may still have been applied. On a POST, the `TIMEOUT` error carries the `idempotencyKey` that was sent: retry with exactly that key and the Server returns the original result instead of creating a second record. Reads and other methods carry no key.
182
197
 
183
198
  ## What is AGLedger?
184
199
 
@@ -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.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';
@@ -155,7 +155,7 @@ function parseJsonObject(value, fieldName) {
155
155
  /**
156
156
  * Parse a JSON-encoded object OR array. Used for fields that legitimately
157
157
  * accept either shape (e.g. `agledger_verify.publicKeys`, which accepts verify-core
158
- * `OutOfBandKeyEntry[]` polymorphism). Strings,
158
+ * `SuppliedKeyEntry[]` polymorphism). Strings,
159
159
  * numbers, booleans, and null still fail loudly.
160
160
  */
161
161
  function parseJsonObjectOrArray(value, fieldName) {
@@ -192,6 +192,64 @@ function unwrapVerificationKeys(raw) {
192
192
  }
193
193
  return raw;
194
194
  }
195
+ /**
196
+ * The verdict as text plus the next step, carried as the result's `summary`,
197
+ * worded as the other verifiers word their headlines. Worded
198
+ * from `valid` and `keyTrust.status` only: an applicability flag says a check
199
+ * ran, never that it passed, so no sentence here claims agreement on anything
200
+ * but the verdict. An unanchored result never reads as a pass.
201
+ */
202
+ function verifyVerdictText(result) {
203
+ const trust = result.keyTrust;
204
+ const verdict = result.verdict;
205
+ const lines = [];
206
+ if (verdict === 'failed') {
207
+ const at = result.brokenAt;
208
+ lines.push(at
209
+ ? `Verdict: FAIL at position ${at.position}: ${at.code}.${at.detail ? ` ${at.detail}` : ''}`
210
+ : 'Verdict: FAIL.');
211
+ lines.push('Verification FAILED: the chain or the key statements do not hold up.');
212
+ for (const f of trust.findings) {
213
+ lines.push(`Key finding: ${f.code}${f.keyId ? ` (${f.keyId})` : ''}: ${f.detail}`);
214
+ }
215
+ if (at)
216
+ lines.push(`Next: ${suggestion(at.code)}`);
217
+ }
218
+ else if (verdict === 'trusted') {
219
+ lines.push(`Verdict: PASS. Nothing failed, and every signature was checked under a key the signed key statements ` +
220
+ `link to a trust anchor you gave (${trust.anchors.join(', ')}). ` +
221
+ `${result.verifiedEntries}/${result.totalEntries} entries verified.`);
222
+ }
223
+ else if (trust.status === 'no_anchored_signature') {
224
+ lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: the trustAnchors ' +
225
+ `(${trust.anchors.join(', ')}) were walked, but no signature here verified under a key they anchor. ` +
226
+ 'An entry that carries no signature proves nothing about who wrote it.');
227
+ lines.push('Next: if the entries are signed, check that each trustAnchors digest is a vault key of the install that wrote ' +
228
+ 'this export (ask the operator). An export with no signed entry cannot be anchored.');
229
+ }
230
+ else {
231
+ lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: no trustAnchors were ' +
232
+ 'given, so every signing key was taken on the word of the export itself, and a key written into the ' +
233
+ "Server's database alone would verify.");
234
+ lines.push('Next: call agledger_verify again with trustAnchors set to the sha256:<hex> digest of a vault key taken out of ' +
235
+ 'band (the installer prints the first vault key\'s; ask the operator). ' +
236
+ (trust.anchoredFrom
237
+ ? `The export names its Server's key as ${trust.anchoredFrom}; that is the export's own claim and is not an anchor.`
238
+ : 'The export names no Server key.'));
239
+ }
240
+ for (const n of trust.notes) {
241
+ lines.push(`Key note: ${n.keyId ? `(${n.keyId}) ` : ''}${n.detail}`);
242
+ }
243
+ const { skipped } = result.signatureCoverage;
244
+ if (result.valid && skipped > 0) {
245
+ lines.push(`${skipped} of ${result.totalEntries} entries carry no signature, so they are covered by the hash chain only.`);
246
+ }
247
+ const { present, verified } = result.agentSignatures;
248
+ if (present > verified) {
249
+ lines.push(`${present - verified} of ${present} agent signatures were not checked: pass agentKeys with the agents' cert public keys to re-verify them.`);
250
+ }
251
+ return lines.join('\n');
252
+ }
195
253
  /**
196
254
  * Every code `agledger_verify` can report, named in its description so a model
197
255
  * can branch on them. The list used to be typed out by hand and fell three
@@ -199,7 +257,8 @@ function unwrapVerificationKeys(raw) {
199
257
  * CHAIN_KEY_NOT_YET_ACTIVE). `ExportCodesMissing` below makes the compiler
200
258
  * fail when verify-core adds an export-level code this list does not carry.
201
259
  * CHECKPOINT_* and TENANT_* are dump-verifier codes and never come back from
202
- * an audit export.
260
+ * an audit export. KEY_* are findings on the export's signed key statements,
261
+ * reported at position 0 when trustAnchors are given.
203
262
  */
204
263
  const EXPORT_FAILURE_CODES = [
205
264
  'CHAIN_HASH_MISMATCH',
@@ -213,6 +272,7 @@ const EXPORT_FAILURE_CODES = [
213
272
  'CHAIN_OIDC_ACTOR_MISMATCH',
214
273
  'CHAIN_SIGNATURE_INVALID',
215
274
  'CHAIN_SIGNATURE_MISSING_KEY',
275
+ 'CHAIN_ENTRY_UNSIGNED',
216
276
  'CHAIN_KEY_POLICY_VIOLATION',
217
277
  'CHAIN_KEY_EXPIRED',
218
278
  'CHAIN_KEY_NOT_YET_ACTIVE',
@@ -221,6 +281,10 @@ const EXPORT_FAILURE_CODES = [
221
281
  'CHAIN_ACTOR_ATTRIBUTION_MISMATCH',
222
282
  'CHAIN_AGENT_SIGNATURE_INVALID',
223
283
  'CHAIN_UNSUPPORTED_ALGORITHM',
284
+ 'CHAIN_SIGNING_KEY_UNANCHORED',
285
+ 'KEY_STATEMENT_INVALID',
286
+ 'KEY_CLOSURE_INVALID',
287
+ 'CHAIN_KEY_WINDOW_DRIFT',
224
288
  'UNSUPPORTED_FORMAT',
225
289
  'CHAIN_EMPTY',
226
290
  ];
@@ -260,14 +324,38 @@ const VERIFY_ARGS = {
260
324
  'objects are also accepted for compatibility.'),
261
325
  publicKeys: jsonStringField
262
326
  .optional()
263
- .describe('Optional out-of-band signing keys. Accepts any of these as a JSON-encoded ' +
327
+ .describe('Optional signing keys you supply. Accepts any of these as a JSON-encoded ' +
264
328
  'string (or a native object/array): a compact map ' +
265
329
  '\'{"key-1":"MCowBQYDK2VwAyEA..."}\' (values are base64 SPKI DER; Ed25519 keys ' +
266
330
  'start "MCowBQYDK2Vw", P-256 keys "MFkwEwYHKoZIzj0"), the list shape ' +
267
331
  '\'[{"keyId":"key-1","publicKey":"MCowBQYDK2VwAyEA..."}]\', or the raw ' +
268
332
  'GET /v1/verification-keys response envelope (\'{"data":[...], ...}\'); the ' +
269
333
  '.data array is unwrapped automatically, so the agledger_api response can be ' +
270
- 'passed straight through). Merged over any keys embedded in the export.'),
334
+ 'passed straight through, and each key\'s signed statements are walked with trustAnchors). ' +
335
+ 'Merged over any keys embedded in the export. Where a key came from is not whether it is ' +
336
+ 'trusted: the Server serves these from the same database as the export. That is trustAnchors.'),
337
+ trustAnchors: z
338
+ .array(z.string())
339
+ .optional()
340
+ .describe('Recommended. SPKI digests ("sha256:<64 hex>") of vault keys you took out of band: the installer ' +
341
+ 'prints the first vault key\'s, and the Server\'s signing-key-digest.js derives one from a key ' +
342
+ 'the operator holds. Ask the operator for it; do not take it from the export ' +
343
+ '(exportMetadata.anchoredFrom) or from GET /v1/verification-keys, which are the Server\'s own word. ' +
344
+ 'The signed key statements the export carries are walked from these: an entry signed by a key ' +
345
+ 'the walk does not reach fails CHAIN_SIGNING_KEY_UNANCHORED, and a statement that does not hold ' +
346
+ 'fails at position 0 with KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID or CHAIN_KEY_WINDOW_DRIFT. ' +
347
+ 'Without it, result.keyTrust.status is "no_anchor": valid:true then means only that the chain ' +
348
+ 'is intact against keys nobody pinned, not that it is trusted.'),
349
+ distrustedKeys: z
350
+ .array(z.string())
351
+ .optional()
352
+ .describe('Optional. The operator\'s VAULT_DISTRUSTED_KEYS entries: "sha256:<64 hex>", optionally ' +
353
+ '"@<RFC 3339 instant>". What such a key signed from that instant (with none, from its retirement) ' +
354
+ 'counts for nothing in the walk. Requires trustAnchors. A dated entry may name a key also in ' +
355
+ 'trustAnchors, which then vouches for what that key signed before the instant; an undated one may not. ' +
356
+ 'Where an export lists a key retired at the instant the Server distrusts it from (distrustedFrom), earlier ' +
357
+ 'than its signed retirement, a run without the same entry fails on that window, and the finding names the ' +
358
+ 'distrustedKeys entry to confirm with the operator.'),
271
359
  agentKeys: jsonStringField
272
360
  .optional()
273
361
  .describe('Optional Ed25519 public keys of agent certs, as a JSON-encoded array of JWKs ' +
@@ -280,12 +368,11 @@ const VERIFY_ARGS = {
280
368
  .optional()
281
369
  .describe('If set, every entry must reference this keyId. Rejects exports signed by a ' +
282
370
  'retired or unexpected key even if cryptographically valid.'),
283
- requireOutOfBandKeys: z
371
+ requireSuppliedKeys: z
284
372
  .boolean()
285
373
  .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.'),
374
+ .describe('Refuse keys embedded in the export: an entry whose only key is export-embedded fails ' +
375
+ 'CHAIN_KEY_POLICY_VIOLATION, so every signature is checked against a key from publicKeys.'),
289
376
  };
290
377
  export class AgledgerMcpServer {
291
378
  mcp;
@@ -429,6 +516,7 @@ export class AgledgerMcpServer {
429
516
  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
517
  if (refused)
431
518
  return refused;
519
+ let sentKey;
432
520
  try {
433
521
  const { method, path, params, idempotencyKey } = args;
434
522
  if (!path.startsWith('/')) {
@@ -450,8 +538,11 @@ export class AgledgerMcpServer {
450
538
  return errorResult('Path contains control characters.', 'PATH_INVALID', 'Remove control characters (newlines, tabs, null bytes) from the path.');
451
539
  }
452
540
  const options = {};
453
- if (idempotencyKey !== undefined)
454
- options.idempotencyKey = idempotencyKey;
541
+ // The key is fixed here, not left for the client to generate, so a
542
+ // timeout error can name the key that went out. Only POST carries one.
543
+ sentKey = method === 'POST' ? (idempotencyKey ?? crypto.randomUUID()) : undefined;
544
+ if (sentKey !== undefined)
545
+ options.idempotencyKey = sentKey;
455
546
  if (params !== undefined && params !== '') {
456
547
  const decoded = parseJsonObject(params, 'params');
457
548
  if (!decoded.ok)
@@ -485,10 +576,14 @@ export class AgledgerMcpServer {
485
576
  if (credentialError)
486
577
  return credentialError;
487
578
  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.');
579
+ return errorResult('The API did not respond in time. The request may still have been applied.', 'TIMEOUT', sentKey
580
+ ? `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).`
581
+ : '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
582
  }
490
583
  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.');
584
+ return errorResult(err.message, 'NETWORK_ERROR', sentKey
585
+ ? `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.`
586
+ : 'Check that the API URL is correct. Try GET /health to verify connectivity.', sentKey ? { idempotencyKey: sentKey } : undefined);
492
587
  }
493
588
  return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
494
589
  }
@@ -499,9 +594,13 @@ export class AgledgerMcpServer {
499
594
  'Decodes each entry\'s tagged COSE_Sign1 envelope (RFC 9052), recomputes ' +
500
595
  'sha256 over the envelope bytes, walks the hash chain, cross-checks the protected-' +
501
596
  '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. ' +
597
+ 'No network calls. Pass trustAnchors (the sha256:<hex> digest of a vault key the operator ' +
598
+ 'took out of band) so the export\'s signed key statements are walked from a key you trust: ' +
599
+ 'without it the keys are taken on the export\'s word and keyTrust.status is "no_anchor". ' +
600
+ 'result.verdict is "trusted" (PASS: valid, and keyTrust.status "walked"), "failed", or "unanchored" ' +
601
+ '(VERIFIED, NOT ANCHORED: valid, but keyTrust.status "no_anchor", or "no_anchored_signature" when the ' +
602
+ 'anchors were walked and no signature verified under a key they anchor); an unanchored result is not a trusted verdict. ' +
603
+ 'result.summary states the verdict in words and the next step. ' +
505
604
  'On failure, brokenAt pinpoints the first entry that failed and its canonical code ' +
506
605
  `(${EXPORT_FAILURE_CODES.join(', ')}); CHAIN_UNSUPPORTED_ALGORITHM means this build ` +
507
606
  '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. ' +
@@ -522,7 +621,7 @@ export class AgledgerMcpServer {
522
621
  if (refused)
523
622
  return refused;
524
623
  try {
525
- const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, requireKeyId, requireOutOfBandKeys, } = args;
624
+ const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, } = args;
526
625
  const decodedExport = parseJsonObject(exportRaw, 'export');
527
626
  if (!decodedExport.ok)
528
627
  return decodedExport.error;
@@ -530,6 +629,27 @@ export class AgledgerMcpServer {
530
629
  if (!('entries' in exportData)) {
531
630
  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
631
  }
632
+ // Parsed here as well as in verify-core so a malformed digest is
633
+ // reported against the argument that carried it.
634
+ try {
635
+ parseTrustAnchors(trustAnchors ?? []);
636
+ parseDistrustedKeys(distrustedKeys ?? []);
637
+ }
638
+ catch (err) {
639
+ 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>"].');
640
+ }
641
+ try {
642
+ assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys);
643
+ }
644
+ catch (err) {
645
+ 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.');
646
+ }
647
+ const anchored = trustAnchors !== undefined && trustAnchors.length > 0;
648
+ // verify-core reads distrusted keys only during the walk, so without
649
+ // an anchor they would be dropped without a word.
650
+ if (!anchored && distrustedKeys !== undefined && distrustedKeys.length > 0) {
651
+ 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.');
652
+ }
533
653
  let publicKeys;
534
654
  if (publicKeysRaw !== undefined && publicKeysRaw !== '') {
535
655
  const decodedKeys = parseJsonObjectOrArray(publicKeysRaw, 'publicKeys');
@@ -551,9 +671,14 @@ export class AgledgerMcpServer {
551
671
  publicKeys,
552
672
  agentKeys,
553
673
  requireKeyId,
554
- requireOutOfBandKeys,
674
+ requireSuppliedKeys,
675
+ ...(anchored ? { trustAnchors, distrustedKeys } : {}),
555
676
  });
556
- const structured = result;
677
+ // verify-core's result verbatim, verdict first (`valid` alone is true
678
+ // on a run that anchored nothing), with the verdict in words and the
679
+ // next step as `summary`, in the one JSON text block.
680
+ const { verdict, ...rest } = result;
681
+ const structured = { verdict, summary: verifyVerdictText(result), ...rest };
557
682
  return {
558
683
  content: mirrorContent(structured),
559
684
  structuredContent: structured,
@@ -561,7 +686,10 @@ export class AgledgerMcpServer {
561
686
  };
562
687
  }
563
688
  catch (err) {
564
- return errorResult(err instanceof Error ? err.message : String(err), 'VERIFY_FAILED');
689
+ // verify-core throws TypeError only on input it refuses (a supplied
690
+ // key's window that is not RFC 3339, a malformed key list): that is
691
+ // the caller's argument, not a failed verification.
692
+ return errorResult(err instanceof Error ? err.message : String(err), err instanceof TypeError ? 'INVALID_ARGUMENT' : 'VERIFY_FAILED');
565
693
  }
566
694
  });
567
695
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agledger/mcp-server",
3
- "version": "2.11.0",
3
+ "version": "3.0.0",
4
4
  "description": "AGLedger MCP Server: thin API pass-through for AI agents via MCP protocol",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "AGLedger LLC",
@@ -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.0.0",
59
59
  "@modelcontextprotocol/sdk": "^1.30.0",
60
60
  "zod": "^3.25.0 || ^4.0.0"
61
61
  },