@agledger/mcp-server 3.0.0 → 3.2.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/dist/server.js CHANGED
@@ -1,22 +1,18 @@
1
- // `zod/v4`, not `zod`. The MCP SDK declares zod as a non-optional peer across
2
- // `^3.25 || ^4.0` and imports the version-specific subpaths, so it runs on
3
- // whichever major the host tree holds. Importing bare `zod` pinned us to v4 and
4
- // forced npm to nest a second copy whenever a host held zod 3 -- and two copies
5
- // of zod means two registries. `.describe()` and `.meta()` write into the
6
- // registry rather than onto the schema, so the SDK rendered our tools against a
7
- // registry that had never seen them: every argument description gone, and the
8
- // type of every JSON-string argument with it. Nothing threw.
9
- //
10
- // zod 3.25 ships the v4 implementation under this subpath, so one import works
11
- // on both majors and lets npm resolve a single shared copy. Matching the SDK's
12
- // dependency range is what makes the dedupe possible; see `zod-integrity.ts`
13
- // for the check that catches a tree which splits them anyway.
1
+ // `zod/v4`, the version-specific subpath, rather than bare `zod`. This package
2
+ // declares the same zod range `@modelcontextprotocol/server` does (^4.2.0), which
3
+ // is what lets npm install one shared copy. Two copies of zod mean two
4
+ // registries: `.describe()` and `.meta()` write into the registry rather than
5
+ // onto the schema, so the MCP library would render our tools against a registry
6
+ // that had never seen them, dropping every argument description and the type of
7
+ // every JSON-string argument. Nothing throws. `zod-integrity.ts` warns when a
8
+ // tree splits them anyway.
14
9
  import { z } from 'zod/v4';
15
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
10
+ import { McpServer } from '@modelcontextprotocol/server';
16
11
  import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, suggestion, verifyAuditExport, } from '@agledger/verify-core';
17
- import { ApiClient } from './api-client.js';
18
- import { OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
12
+ import { ApiClient, QueryShapeError } from './api-client.js';
13
+ import { AgentKeysFileError, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
19
14
  import { DelegationSource, DelegationSourceError } from './delegation.js';
15
+ import { describeError, fetchCause } from './errors.js';
20
16
  import { SERVER_VERSION } from './version.js';
21
17
  export { SERVER_VERSION };
22
18
  const QUICKSTART = {
@@ -29,17 +25,16 @@ const QUICKSTART = {
29
25
  ],
30
26
  };
31
27
  const DOCS = {
32
- description: 'Every API response includes nextSteps for self-guided workflow discovery. ' +
28
+ description: 'Most API responses carry nextSteps for self-guided workflow discovery; follow them when present ' +
29
+ '(listings, the schema catalogue and the org listing carry none). ' +
33
30
  'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog, ' +
34
31
  'and GET /llms.txt (also exposed as the agledger://llms.txt resource) for the prose narrative ' +
35
32
  'written for agents: what the product is for, the vocabulary, and how the pieces fit together. ' +
36
33
  'Read llms.txt first if you are new to this API; read OpenAPI when you need exact routes.',
37
34
  openapi: '/openapi.json',
38
35
  openapiResource: 'agledger://openapi',
39
- // The API's agent-oriented narrative. An MCP-connected agent never learned
40
- // this existed: discover named only OpenAPI and resources/list offered only
41
- // the spec, so the one integration surface built for agents hid the API's
42
- // agent-facing documentation.
36
+ // The API's agent-oriented narrative, advertised by discover and offered
37
+ // through resources/list beside the OpenAPI spec.
43
38
  narrative: '/llms.txt',
44
39
  narrativeResource: 'agledger://llms.txt',
45
40
  };
@@ -49,9 +44,9 @@ function mirrorContent(structured) {
49
44
  return [{ type: 'text', text: JSON.stringify(structured) }];
50
45
  }
51
46
  /**
52
- * Structured error for CLI-origin failures (network, timeout, malformed input).
53
- * API-origin errors are forwarded verbatim without enrichment; if the API
54
- * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
47
+ * Structured error for failures raised by this server (network, timeout, malformed input).
48
+ * API-origin errors are forwarded verbatim without enrichment: a suggestion
49
+ * the API returns reaches the agent as sent, and none is added when it returns none.
55
50
  */
56
51
  function errorResult(message, code, suggestion, extra) {
57
52
  const structuredContent = { error: true, message };
@@ -67,12 +62,67 @@ function errorResult(message, code, suggestion, extra) {
67
62
  isError: true,
68
63
  };
69
64
  }
65
+ /** Cause codes that mean the Server's certificate was not accepted. */
66
+ const TLS_CAUSE = /^(CERT_|UNABLE_TO_|DEPTH_ZERO_|SELF_SIGNED_|ERR_TLS_|ERR_SSL_|ERR_CERT)|HOSTNAME_MISMATCH/;
67
+ /** A request that never reached the API: the connection failed, so nothing was applied. */
68
+ function networkErrorResult(err, sentKey) {
69
+ const cause = fetchCause(err);
70
+ const message = describeError(err);
71
+ if (cause === 'ENOTFOUND') {
72
+ return errorResult(message, 'NETWORK_ERROR', 'The API host does not resolve. Check the API URL for a typo, and that DNS can see it from this machine. Nothing was sent.');
73
+ }
74
+ if (cause === 'ECONNREFUSED') {
75
+ return errorResult(message, 'NETWORK_ERROR', 'The host resolved but refused the connection. Check that the Server is running and the port in the API URL is right. Nothing was sent.');
76
+ }
77
+ if (cause !== undefined && TLS_CAUSE.test(cause)) {
78
+ return errorResult(message, 'NETWORK_ERROR', 'The Server\'s TLS certificate was not accepted. Check the certificate chain, its expiry and that the host name matches the API URL. For a private certificate authority, start agledger-mcp with NODE_EXTRA_CA_CERTS=<path to the CA certificate>. Nothing was sent.');
79
+ }
80
+ return errorResult(message, 'NETWORK_ERROR', sentKey
81
+ ? `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.`
82
+ : 'Check that the API URL is correct. Try GET /health to verify connectivity.', sentKey ? { idempotencyKey: sentKey } : undefined);
83
+ }
84
+ /** GET a discovery document for a resource read; a failure throws with the status and the API's own detail, or the connection's cause. */
85
+ async function fetchDocument(client, path) {
86
+ let response;
87
+ try {
88
+ response = await client.request('GET', path);
89
+ }
90
+ catch (err) {
91
+ throw new Error(`Failed to fetch ${path}: ${describeError(err)}`, { cause: err });
92
+ }
93
+ if (!response.ok)
94
+ throw new Error(apiFailureText(path, response));
95
+ return response.body;
96
+ }
97
+ /** What a failed fetch of a discovery document says: the status, then the API's own detail and recovery hint. */
98
+ function apiFailureText(path, response) {
99
+ const body = response.body !== null && typeof response.body === 'object' ? response.body : {};
100
+ const parts = [body.detail, body.message, body.recoveryHint].filter((v) => typeof v === 'string' && v !== '');
101
+ return `Failed to fetch ${path}: HTTP ${response.status}${parts.length > 0 ? `. ${parts.join(' ')}` : ''}`;
102
+ }
70
103
  /**
71
104
  * The credential could not produce a bearer. This is a client-side failure (the
72
105
  * request never went out), so it is reported in the server's own error shape.
73
106
  * The exchange's refusal is carried as the Server sent it, scrubbed of any
74
107
  * token, and its recoveryHint is passed through rather than rewritten.
75
108
  */
109
+ /**
110
+ * The agent keys argument in every shape the agledger-verify and agledger
111
+ * verify `--agent-keys` file takes: one JWK, a list of them, or a
112
+ * `{keys:[...]}` JWK Set (the file AGLEDGER_AGENT_KEYS_FILE collects), where an
113
+ * entry may wrap its key as `{publicKeyJwk:{...}}`. verify-core validates each
114
+ * key and refuses a bad one with a TypeError.
115
+ */
116
+ function agentKeyList(value) {
117
+ const list = Array.isArray(value)
118
+ ? value
119
+ : value !== null && typeof value === 'object' && Array.isArray(value.keys)
120
+ ? value.keys
121
+ : [value];
122
+ return list.map((entry) => entry !== null && typeof entry === 'object' && 'publicKeyJwk' in entry
123
+ ? entry.publicKeyJwk
124
+ : entry);
125
+ }
76
126
  function credentialErrorResult(err) {
77
127
  if (err instanceof OidcExchangeError) {
78
128
  return errorResult(err.message, err.code, err.recoveryHint ??
@@ -81,6 +131,9 @@ function credentialErrorResult(err) {
81
131
  if (err instanceof DelegationSourceError) {
82
132
  return errorResult(err.message, err.code, 'Fix the delegation source the server was started with (AGLEDGER_ON_BEHALF_OF_CMD or AGLEDGER_ON_BEHALF_OF_FILE); it must yield a current RFC 8693 token-exchange result token.');
83
133
  }
134
+ if (err instanceof AgentKeysFileError) {
135
+ return errorResult(err.message, err.code, `Fix or move ${err.path} (named by AGLEDGER_AGENT_KEYS_FILE), or unset it and restart the server. Nothing was signed under the new cert.`);
136
+ }
84
137
  if (err instanceof OidcTokenSourceError) {
85
138
  return errorResult(err.message, err.code, 'Fix the token source the server was started with (AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE); it must yield a current OIDC JWT on every call.');
86
139
  }
@@ -119,8 +172,8 @@ function unknownArgumentResult(tool, shape, args, hint) {
119
172
  // then the handler JSON.parses uniformly.
120
173
  //
121
174
  // Deliberately NOT `z.preprocess`, which published these fields as optional
122
- // even when they were required. The MCP SDK renders tool schemas with
123
- // `toJSONSchema(..., { io: 'input' })`, and that builds `required` from each
175
+ // even when they were required. Tool schemas are rendered with
176
+ // `toJSONSchema(..., { io: 'input' })`, which builds `required` from each
124
177
  // field's `_zod.optin`. `z.preprocess` types its input as `unknown`, which
125
178
  // subsumes `undefined`, so it sets `optin: 'optional'` and the field drops out
126
179
  // of `required`. `agledger_verify` published no `required` array at all, which
@@ -133,32 +186,8 @@ const jsonStringField = z
133
186
  .transform((v) => (v !== null && typeof v === 'object' ? JSON.stringify(v) : v))
134
187
  .pipe(z.string())
135
188
  .meta({ type: 'string' });
136
- function parseJsonObject(value, fieldName) {
137
- let parsed;
138
- try {
139
- parsed = JSON.parse(value);
140
- }
141
- catch (err) {
142
- return {
143
- ok: false,
144
- error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}') or as a native object.`),
145
- };
146
- }
147
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
148
- return {
149
- ok: false,
150
- error: errorResult(`Argument \`${fieldName}\` must decode to a JSON object.`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON object, e.g. '{"key":"value"}'.`),
151
- };
152
- }
153
- return { ok: true, value: parsed };
154
- }
155
- /**
156
- * Parse a JSON-encoded object OR array. Used for fields that legitimately
157
- * accept either shape (e.g. `agledger_verify.publicKeys`, which accepts verify-core
158
- * `SuppliedKeyEntry[]` polymorphism). Strings,
159
- * numbers, booleans, and null still fail loudly.
160
- */
161
- function parseJsonObjectOrArray(value, fieldName) {
189
+ function parseJsonObject(value, fieldName, options) {
190
+ const allowArray = options?.allowArray === true;
162
191
  let parsed;
163
192
  try {
164
193
  parsed = JSON.parse(value);
@@ -166,13 +195,19 @@ function parseJsonObjectOrArray(value, fieldName) {
166
195
  catch (err) {
167
196
  return {
168
197
  ok: false,
169
- error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}' or '[{"keyId":"k1","publicKey":"…"}]') or as a native object/array.`),
198
+ error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${describeError(err)}`, 'INVALID_JSON', allowArray
199
+ ? `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}' or '[{"keyId":"k1","publicKey":"..."}]') or as a native object/array.`
200
+ : `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}') or as a native object.`),
170
201
  };
171
202
  }
172
- if (parsed === null || typeof parsed !== 'object') {
203
+ if (parsed === null || typeof parsed !== 'object' || (!allowArray && Array.isArray(parsed))) {
173
204
  return {
174
205
  ok: false,
175
- error: errorResult(`Argument \`${fieldName}\` must decode to a JSON object or array.`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON object (\`{keyId: spkiBase64, ...}\`) or array (\`[{keyId, publicKey}, ...]\`).`),
206
+ error: errorResult(allowArray
207
+ ? `Argument \`${fieldName}\` must decode to a JSON object or array.`
208
+ : `Argument \`${fieldName}\` must decode to a JSON object.`, 'INVALID_JSON', allowArray
209
+ ? `Pass \`${fieldName}\` as a JSON object (\`{keyId: spkiBase64, ...}\`) or array (\`[{keyId, publicKey}, ...]\`).`
210
+ : `Pass \`${fieldName}\` as a JSON object, e.g. '{"key":"value"}'.`),
176
211
  };
177
212
  }
178
213
  return { ok: true, value: parsed };
@@ -182,7 +217,7 @@ function parseJsonObjectOrArray(value, fieldName) {
182
217
  * returns an envelope `{ data: [{ keyId, publicKey, ... }], canonicalization, ... }`,
183
218
  * not the bare array verify-core expects. An MCP agent's natural flow gets the
184
219
  * envelope straight from `agledger_api` and has no `.data[]`-extraction step,
185
- * so unwrap `.data` here, the MCP analogue of the CLI's fix. A
220
+ * so unwrap `.data` here. A
186
221
  * bare `[{keyId, publicKey}]` list or a `{keyId: base64}` map passes through
187
222
  * untouched; verify-core then validates the shape and throws on anything else.
188
223
  */
@@ -220,17 +255,25 @@ function verifyVerdictText(result) {
220
255
  `link to a trust anchor you gave (${trust.anchors.join(', ')}). ` +
221
256
  `${result.verifiedEntries}/${result.totalEntries} entries verified.`);
222
257
  }
258
+ else if (!result.valid) {
259
+ lines.push(`Verdict: NOT ANCHORED. The trustAnchors (${trust.anchors.join(', ')}) reach none of the signing keys in this ` +
260
+ 'export, so every signed entry reads CHAIN_SIGNING_KEY_UNANCHORED, but the export verifies without them: ' +
261
+ 'nothing in it fails on its own. This is the result for an export from another Server than the one pinned, ' +
262
+ 'and equally for one re-signed wholesale under keys of its own. NOT a trusted verdict.');
263
+ lines.push('Next: check with the operator that each trustAnchors digest is a vault key of the install that wrote this ' +
264
+ 'export, and call agledger_verify again with the right one.');
265
+ }
223
266
  else if (trust.status === 'no_anchored_signature') {
224
267
  lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: the trustAnchors ' +
225
268
  `(${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.');
269
+ 'An entry that carries no signature says nothing about who wrote it.');
227
270
  lines.push('Next: if the entries are signed, check that each trustAnchors digest is a vault key of the install that wrote ' +
228
271
  'this export (ask the operator). An export with no signed entry cannot be anchored.');
229
272
  }
230
273
  else {
231
274
  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.");
275
+ 'given, so every signing key was taken on the word of the export itself, and a key planted on the ' +
276
+ 'Server alone would verify.');
234
277
  lines.push('Next: call agledger_verify again with trustAnchors set to the sha256:<hex> digest of a vault key taken out of ' +
235
278
  'band (the installer prints the first vault key\'s; ask the operator). ' +
236
279
  (trust.anchoredFrom
@@ -248,16 +291,65 @@ function verifyVerdictText(result) {
248
291
  if (present > verified) {
249
292
  lines.push(`${present - verified} of ${present} agent signatures were not checked: pass agentKeys with the agents' cert public keys to re-verify them.`);
250
293
  }
294
+ lines.push(entryCountLine(result.entryCount));
295
+ lines.push(...peerMessageLines(result.federationWire));
296
+ lines.push(...evidenceLines(result.evidenceBinding));
251
297
  return lines.join('\n');
252
298
  }
299
+ /**
300
+ * What the export's entry count was held to. A chain cut from the end still
301
+ * verifies entry by entry, so the report names the stated count, if any, that
302
+ * stood behind the number of entries it verified.
303
+ */
304
+ export function entryCountLine(count) {
305
+ if (count.expectedEntries !== null)
306
+ return `Entry count: held to the checkpoint at position ${count.expectedEntries}.`;
307
+ if (count.statedEntries !== null) {
308
+ return `Entry count: held to the ${count.statedEntries} the export states; it names no checkpoint for this record yet.`;
309
+ }
310
+ return "Entry count: the file's own; the export states no count and names no checkpoint.";
311
+ }
312
+ /**
313
+ * The summary lines on the evidence bodies an `?evidence=true` export
314
+ * inlines, each re-bound to the hash its entry signs. Silent when every one
315
+ * re-bound, or when the export carries none.
316
+ */
317
+ export function evidenceLines(counts) {
318
+ const lines = [];
319
+ if (counts.failed > 0) {
320
+ 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.`);
321
+ }
322
+ if (counts.clientHashed > 0) {
323
+ 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.`);
324
+ }
325
+ return lines;
326
+ }
327
+ /**
328
+ * The summary lines on the sealed federation messages. `failed` ones failed a
329
+ * check (a key given for the hub that did not match among them); the rest of
330
+ * the unverified ones came from a hub no key was given for.
331
+ */
332
+ export function peerMessageLines(wire) {
333
+ const lines = [];
334
+ if (wire.afterRetirement > 0) {
335
+ 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 entry for the peer comes after them.`);
336
+ }
337
+ if (wire.failed > 0) {
338
+ lines.push(`${wire.failed} of ${wire.present} sealed peer messages failed CHAIN_FEDERATION_WIRE_INVALID.`);
339
+ }
340
+ const noKey = wire.present - wire.verified - wire.failed;
341
+ if (noKey > 0) {
342
+ 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.`);
343
+ }
344
+ return lines;
345
+ }
253
346
  /**
254
347
  * Every code `agledger_verify` can report, named in its description so a model
255
- * can branch on them. The list used to be typed out by hand and fell three
256
- * codes behind verify-core (CHAIN_OIDC_ACTOR_MISMATCH, CHAIN_KEY_EXPIRED,
257
- * CHAIN_KEY_NOT_YET_ACTIVE). `ExportCodesMissing` below makes the compiler
258
- * fail when verify-core adds an export-level code this list does not carry.
259
- * CHECKPOINT_* and TENANT_* are dump-verifier codes and never come back from
260
- * an audit export. KEY_* are findings on the export's signed key statements,
348
+ * can branch on them. `ExportCodesMissing` below makes the compiler fail when
349
+ * verify-core adds an export-level code this list does not carry.
350
+ * CHECKPOINT_ROW_MISSING is the one CHECKPOINT_* code an export reports (it
351
+ * carries fewer entries than its checkpoint position); the other CHECKPOINT_*
352
+ * and the TENANT_* codes are dump-verifier codes. KEY_* are findings on the export's signed key statements,
261
353
  * reported at position 0 when trustAnchors are given.
262
354
  */
263
355
  const EXPORT_FAILURE_CODES = [
@@ -280,6 +372,8 @@ const EXPORT_FAILURE_CODES = [
280
372
  'CHAIN_SIGNING_KEY_DRIFT',
281
373
  'CHAIN_ACTOR_ATTRIBUTION_MISMATCH',
282
374
  'CHAIN_AGENT_SIGNATURE_INVALID',
375
+ 'CHAIN_FEDERATION_WIRE_INVALID',
376
+ 'CHAIN_EVIDENCE_BINDING_MISMATCH',
283
377
  'CHAIN_UNSUPPORTED_ALGORITHM',
284
378
  'CHAIN_SIGNING_KEY_UNANCHORED',
285
379
  'KEY_STATEMENT_INVALID',
@@ -287,6 +381,7 @@ const EXPORT_FAILURE_CODES = [
287
381
  'CHAIN_KEY_WINDOW_DRIFT',
288
382
  'UNSUPPORTED_FORMAT',
289
383
  'CHAIN_EMPTY',
384
+ 'CHECKPOINT_ROW_MISSING',
290
385
  ];
291
386
  // Resolves to `true` only when nothing is missing; otherwise the assignment
292
387
  // fails and the error names the missing code.
@@ -333,7 +428,7 @@ const VERIFY_ARGS = {
333
428
  '.data array is unwrapped automatically, so the agledger_api response can be ' +
334
429
  'passed straight through, and each key\'s signed statements are walked with trustAnchors). ' +
335
430
  '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.'),
431
+ 'trusted: the Server serves these along with the export. That is trustAnchors.'),
337
432
  trustAnchors: z
338
433
  .array(z.string())
339
434
  .optional()
@@ -358,11 +453,45 @@ const VERIFY_ARGS = {
358
453
  'distrustedKeys entry to confirm with the operator.'),
359
454
  agentKeys: jsonStringField
360
455
  .optional()
361
- .describe('Optional Ed25519 public keys of agent certs, as a JSON-encoded array of JWKs ' +
362
- '\'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\' (the publicKeyJwk each agent sent at cert exchange, also the cnf.jwk claim in its certJws). ' +
456
+ .describe('Optional Ed25519 public keys of agent certs, JSON-encoded: an array of JWKs ' +
457
+ '\'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\', one JWK, or a {"keys":[...]} JWK Set (the file AGLEDGER_AGENT_KEYS_FILE collects), ' +
458
+ 'where an entry may wrap its key as {"publicKeyJwk":{...}}. Each is the publicKeyJwk an agent sent at cert exchange (also the cnf.jwk ' +
459
+ 'claim in its certJws; agledger_discover shows this server\'s own as agentKey). ' +
363
460
  'An entry whose sealed agent signature names one of these keys by thumbprint has that ' +
364
461
  'signature re-verified offline, and fails CHAIN_AGENT_SIGNATURE_INVALID if it does not verify. ' +
365
462
  'Without it, agent signatures are counted in result.agentSignatures but not checked.'),
463
+ federationKeys: jsonStringField
464
+ .optional()
465
+ .describe('Optional peer federation keys, as a JSON-encoded object \'{"<hubId>":"<key>"}\' or array ' +
466
+ '\'[{"hubId":"...","publicKey":"..."}]\', each key the peer Server\'s Ed25519 federation key as its ' +
467
+ 'operator gives it (base64 SPKI DER, or base64 of the raw 32 bytes the handshake registered). ' +
468
+ 'A receiving Server seals each peer message it accepts on the chain entry it writes (payload.wire), ' +
469
+ 'as the peer signed it. Every sealed message is held to its body hash and to its entry; one from a ' +
470
+ 'hub given here also has its signature re-verified under that key, which checks what the peer ' +
471
+ 'asserted from this export alone, and fails CHAIN_FEDERATION_WIRE_INVALID if it does not verify. ' +
472
+ 'After a peer changes its federation key, add "history" to an array entry: the JSON the peer serves at ' +
473
+ 'GET /.well-known/agledger-federation-keys.json (no auth). Every key it links to that entry\'s publicKey ' +
474
+ 'through successions both keys signed is then trusted inside its window, so entries sealed before the ' +
475
+ 'change verify; each message is placed in its key\'s window by its signed wire.timestamp. A hub may appear ' +
476
+ 'twice, to pin a key no succession links or one the history does not list. ' +
477
+ 'Federation key histories need a Server 2.2 or later on the peer. ' +
478
+ 'A message signed more than 300 seconds after its key\'s retirement fails CHAIN_FEDERATION_WIRE_INVALID unless ' +
479
+ 'allowAfterRetirement is true. result.federationWire counts present, verified, failed and afterRetirement ' +
480
+ '(accepted under allowAfterRetirement, signed by the peer under a key it had already retired).'),
481
+ allowAfterRetirement: z
482
+ .boolean()
483
+ .optional()
484
+ .describe('Accept a sealed peer message signed under a key after that key\'s retirement, and count it in ' +
485
+ 'result.federationWire.afterRetirement, for a peer that kept signing briefly after rotating because its process ' +
486
+ 'had not restarted. Without it such a message fails CHAIN_FEDERATION_WIRE_INVALID.'),
487
+ expectedEntryCount: z
488
+ .number()
489
+ .int()
490
+ .min(0)
491
+ .optional()
492
+ .describe('The number of entries the export must hold, taken out of band (the record\'s entry count from the Server or an ' +
493
+ 'earlier export). The counts an export states about itself are unsigned, so an export cut from the end with them ' +
494
+ 'deleted verifies; with this set it fails CHAIN_POSITION_GAP, and result.optionalChecks.entry_count is "applied".'),
366
495
  requireKeyId: z
367
496
  .string()
368
497
  .optional()
@@ -377,22 +506,26 @@ const VERIFY_ARGS = {
377
506
  export class AgledgerMcpServer {
378
507
  mcp;
379
508
  client;
509
+ /** The cert credential, when the server authenticates with an OIDC token source. */
510
+ oidcCredential;
511
+ agentKeysFile;
380
512
  constructor(options) {
381
513
  // No placeholder default. agledger.example.com resolves nowhere, so a
382
514
  // missing --api-url surfaced as a DNS failure against a host the operator
383
- // never configured, on every tool call. Same defect the CLI and SDK
384
- // carried; every deployment is self-hosted, so there is no default worth
385
- // having. Fail at startup, where it can be read.
515
+ // never configured, on every tool call. Every deployment is self-hosted, so
516
+ // there is no default worth having. Fail at startup, where it can be read.
386
517
  const apiUrl = options.apiUrl;
387
518
  if (!apiUrl) {
388
519
  throw new Error('No API URL configured. AGLedger is self-hosted, so the MCP server cannot guess your Server: ' +
389
520
  'pass --api-url <url> or set AGLEDGER_API_URL.');
390
521
  }
391
- if (Boolean(options.apiKey) === Boolean(options.oidc)) {
522
+ this.oidcCredential = !options.apiKey && options.oidc ? new OidcCertCredential(options.oidc) : undefined;
523
+ this.agentKeysFile = options.oidc?.agentKeysFile;
524
+ const credential = options.apiKey ? options.apiKey : this.oidcCredential;
525
+ if (Boolean(options.apiKey) === Boolean(options.oidc) || !credential) {
392
526
  throw new Error('Configure exactly one credential: an API key (--api-key or AGLEDGER_API_KEY) or an OIDC token source ' +
393
527
  '(AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE).');
394
528
  }
395
- const credential = options.apiKey ? options.apiKey : new OidcCertCredential(options.oidc);
396
529
  this.client = new ApiClient(apiUrl, credential, options.timeoutMs, options.onBehalfOf ? new DelegationSource(options.onBehalfOf) : undefined);
397
530
  this.mcp = new McpServer({ name: 'agledger-mcp-server', version: SERVER_VERSION }, { capabilities: { tools: {}, resources: {} } });
398
531
  this.registerTools();
@@ -430,29 +563,35 @@ export class AgledgerMcpServer {
430
563
  client.request('GET', '/v1/scope-profiles'),
431
564
  ]);
432
565
  const result = {};
433
- if (health.status === 'fulfilled') {
434
- result.health = health.value.body;
566
+ // One section per call. A call the API refused is marked with the
567
+ // HTTP status and the API's own body, so a failed section never reads
568
+ // as an answer, and one that never completed carries the error.
569
+ const section = (call) => {
570
+ if (call.status === 'rejected')
571
+ return { error: describeError(call.reason) };
572
+ if (call.value.ok)
573
+ return call.value.body;
574
+ const body = call.value.body !== null && typeof call.value.body === 'object' ? call.value.body : {};
575
+ return { httpStatus: call.value.status, ...body, error: true };
576
+ };
577
+ result.health = section(health);
578
+ if (identity.status === 'rejected') {
579
+ const credentialError = credentialErrorResult(identity.reason);
580
+ result.identity = credentialError ? credentialError.structuredContent : section(identity);
435
581
  }
436
582
  else {
437
- result.health = {
438
- error: health.reason instanceof Error ? health.reason.message : String(health.reason),
439
- };
440
- }
441
- if (identity.status === 'fulfilled') {
442
- result.identity = identity.value.body;
583
+ result.identity = section(identity);
443
584
  }
444
- else {
445
- const credentialError = credentialErrorResult(identity.reason);
446
- result.identity = credentialError
447
- ? credentialError.structuredContent
448
- : {
449
- error: identity.reason instanceof Error
450
- ? identity.reason.message
451
- : String(identity.reason),
452
- };
453
- }
454
- if (scopeProfiles.status === 'fulfilled') {
455
- result.scopeProfiles = scopeProfiles.value.body;
585
+ result.scopeProfiles = section(scopeProfiles);
586
+ // The cert key this server signs request bodies with. The cert
587
+ // carries only its thumbprint, so this is the key agledger_verify's
588
+ // agentKeys needs to re-verify what this server signed.
589
+ if (this.oidcCredential) {
590
+ result.agentKey = {
591
+ publicKeyJwk: this.oidcCredential.publicKeyJwk,
592
+ ...(this.agentKeysFile ? { recordedIn: this.agentKeysFile } : {}),
593
+ note: 'Pass this key in agledger_verify agentKeys to re-verify the agent signatures this server sealed. One key per server process.',
594
+ };
456
595
  }
457
596
  // Whether POSTs carry an AGLedger-On-Behalf-Of delegation, and from
458
597
  // where. The token itself is never shown.
@@ -469,13 +608,15 @@ export class AgledgerMcpServer {
469
608
  return { content: mirrorContent(result), structuredContent: result };
470
609
  }
471
610
  catch (err) {
472
- return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
611
+ return errorResult(describeError(err), 'DISCOVER_FAILED');
473
612
  }
474
613
  });
475
614
  this.mcp.registerTool('agledger_api', {
476
615
  title: 'AGLedger API',
477
- description: 'Make any AGLedger API call. All paths start with /v1/. ' +
478
- 'The API returns nextSteps on every response: follow them. Workflow: ' +
616
+ description: 'Make any AGLedger API call. API routes live under /v1/; the discovery documents ' +
617
+ '(/openapi.json, /llms.txt, /llms-full.txt, /lifecycle) and /a2a sit at the root. ' +
618
+ 'Most responses carry nextSteps: follow them when present (listing pages, GET /v1/schemas ' +
619
+ 'and GET /v1/admin/orgs carry none). Workflow: ' +
479
620
  '1. GET /v1/schemas, list Record types. ' +
480
621
  '2. GET /v1/schemas/{type}, get required fields and examples. ' +
481
622
  '3. POST /v1/records, create a record. ' +
@@ -490,6 +631,20 @@ export class AgledgerMcpServer {
490
631
  'auditor verifies offline; metadata[key]=value filters an unsigned annotation instead. ' +
491
632
  'If a call fails, the error says how to recover: recoveryHint on an error from the Server, ' +
492
633
  'suggestion on an error this tool raises itself (a bad argument, a timeout, a credential failure). ' +
634
+ 'Say what produced the work: POST /v1/records and POST /v1/records/{id}/completions take an optional ' +
635
+ 'producedBy object (modelProvider, modelId, modelVersion, agentSoftware, agentSoftwareVersion, promptDigest, ' +
636
+ 'configDigest; digests are sha256:, sha384: or sha512: hex). Search takes traceId, originRecordId, ' +
637
+ 'producedBy[key]=value and numeric bounds written as criteriaGte[amount]=500 (also criteriaGt/Lt/Lte and the ' +
638
+ 'metadata twins); pass them in params as nested objects, e.g. {"criteriaGte":{"amount":500}}. ' +
639
+ 'GET /v1/records/counts takes the same filters plus groupBy, up to two comma-joined dimensions ' +
640
+ '(type, status, performerAgentId, principalAgentId, category, gateMode, operatingMode, createdDay, createdMonth). ' +
641
+ 'A verdict (POST /v1/records/{id}/verdict) may add signatureMeaning (authorship, review, approval or responsibility): ' +
642
+ 'it is taken only on an ephemeral OIDC cert, and the Server refuses it with 422 on an API key. ' +
643
+ 'GET /v1/records/{id}/audit-export takes format=html and returns the page as text exactly as the Server sent it; ' +
644
+ 'use the default JSON export for agledger_verify. ' +
645
+ 'On a keyed write, 409 IDEMPOTENCY_KEY_IN_FLIGHT means the first attempt is still running: retry with the same key ' +
646
+ 'after Retry-After (an error result carries it as retryAfter, in seconds, beside httpStatus). 409 IDEMPOTENT_WRITE_COMMITTED means it already landed: follow its refreshUrl, do not retry. ' +
647
+ '503 SERVER_SHUTTING_DOWN is retryable. ' +
493
648
  'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource); ' +
494
649
  'for prose orientation, GET /llms.txt (or read the agledger://llms.txt resource). ' +
495
650
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body. ' +
@@ -499,7 +654,8 @@ export class AgledgerMcpServer {
499
654
  annotations: {
500
655
  readOnlyHint: false,
501
656
  // This tool dispatches to any route, including DELETE/PATCH, so it can
502
- // perform destructive, non-idempotent operations. Annotate honestly.
657
+ // perform destructive, non-idempotent operations, so it is marked
658
+ // destructive and not idempotent.
503
659
  destructiveHint: true,
504
660
  idempotentHint: false,
505
661
  openWorldHint: true,
@@ -509,9 +665,9 @@ export class AgledgerMcpServer {
509
665
  // method+path to every route, each with its own scope requirement
510
666
  // (records:read, records:write, etc.). The required scope is route-
511
667
  // dependent and enforced server-side per request; it cannot be
512
- // statically declared for the dispatcher as a whole. Fabricating a
513
- // single scope here would be dishonest. Callers see the real missing
514
- // scopes in the API's 403 response (missingScopes), forwarded verbatim.
668
+ // statically declared for the dispatcher as a whole, so no scope is
669
+ // listed here. A caller sees the missing scopes in the API's 403
670
+ // response (missingScopes), forwarded verbatim.
515
671
  }, async (args) => {
516
672
  const refused = unknownArgumentResult('agledger_api', API_ARGS, args, 'The request body (POST/PUT/PATCH) and the query string (GET/DELETE) both go in `params`.');
517
673
  if (refused)
@@ -534,7 +690,7 @@ export class AgledgerMcpServer {
534
690
  // Reject control characters before building the request URL. Tool input
535
691
  // is untrusted; control chars enable request-line / header injection and
536
692
  // never appear in a legitimate API path.
537
- if (/[\x00-\x1f\x7f]/.test(path)) {
693
+ if (Array.from(path).some((ch) => ch.charCodeAt(0) <= 0x1f || ch.charCodeAt(0) === 0x7f)) {
538
694
  return errorResult('Path contains control characters.', 'PATH_INVALID', 'Remove control characters (newlines, tabs, null bytes) from the path.');
539
695
  }
540
696
  const options = {};
@@ -557,14 +713,25 @@ export class AgledgerMcpServer {
557
713
  const response = await client.request(method, path, options);
558
714
  if (response.ok) {
559
715
  const body = response.body;
716
+ // A text response (format=html|csv|ndjson on an audit export) is
717
+ // handed back as the Server sent it, not as an escaped JSON string.
718
+ // structuredContent keeps the {_raw, _contentType} wrapper.
719
+ const text = typeof body?._raw === 'string' ? [{ type: 'text', text: body._raw }] : mirrorContent(body);
560
720
  return {
561
- content: mirrorContent(body),
721
+ content: text,
562
722
  structuredContent: body,
563
723
  };
564
724
  }
565
725
  // Forward the API error body verbatim. The API owns error guidance;
566
- // the MCP does not enrich, translate, or inject suggestions.
567
- const errorBody = (response.body ?? {});
726
+ // the MCP does not enrich, translate, or inject suggestions. What it
727
+ // adds is what the body cannot say: the HTTP status, and the seconds
728
+ // of a Retry-After header, which the tool description tells the model
729
+ // to honour. The body's own fields win over both.
730
+ const errorBody = {
731
+ httpStatus: response.status,
732
+ ...(response.retryAfterSeconds !== undefined ? { retryAfter: response.retryAfterSeconds } : {}),
733
+ ...(response.body ?? {}),
734
+ };
568
735
  return {
569
736
  content: mirrorContent(errorBody),
570
737
  structuredContent: errorBody,
@@ -581,11 +748,12 @@ export class AgledgerMcpServer {
581
748
  : '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);
582
749
  }
583
750
  if (err instanceof TypeError && err.message.includes('fetch')) {
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);
751
+ return networkErrorResult(err, sentKey);
752
+ }
753
+ if (err instanceof QueryShapeError) {
754
+ return errorResult(err.message, 'INVALID_ARGUMENT', 'Give each params entry a string, number or boolean, or an object of them one level deep (params: { criteriaGte: { amount: 500 } }). Nothing was sent.');
587
755
  }
588
- return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
756
+ return errorResult(describeError(err), 'UNKNOWN_ERROR');
589
757
  }
590
758
  });
591
759
  this.mcp.registerTool('agledger_verify', {
@@ -593,17 +761,23 @@ export class AgledgerMcpServer {
593
761
  description: 'Verify an AGLedger record audit export offline (format 2.0, COSE_Sign1). ' +
594
762
  'Decodes each entry\'s tagged COSE_Sign1 envelope (RFC 9052), recomputes ' +
595
763
  'sha256 over the envelope bytes, walks the hash chain, cross-checks the protected-' +
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). ' +
764
+ 'header chain claim against the entry fields the export lists beside the signed bytes, and verifies every envelope signature (Ed25519 or ES256, dispatched from the trusted key material; anything else fails closed). ' +
597
765
  'No network calls. Pass trustAnchors (the sha256:<hex> digest of a vault key the operator ' +
598
766
  'took out of band) so the export\'s signed key statements are walked from a key you trust: ' +
599
767
  'without it the keys are taken on the export\'s word and keyTrust.status is "no_anchor". ' +
600
768
  'result.verdict is "trusted" (PASS: valid, and keyTrust.status "walked"), "failed", or "unanchored" ' +
601
769
  '(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. ' +
770
+ 'anchors were walked and no signature verified under a key they anchor; also NOT ANCHORED with valid false when the ' +
771
+ 'trustAnchors reach none of the export\'s keys and it verifies without them, as for another Server\'s pin); ' +
772
+ 'an unanchored result is not a trusted verdict, and isError is set only for "failed". ' +
603
773
  'result.summary states the verdict in words and the next step. ' +
604
774
  'On failure, brokenAt pinpoints the first entry that failed and its canonical code ' +
605
775
  `(${EXPORT_FAILURE_CODES.join(', ')}); CHAIN_UNSUPPORTED_ALGORITHM means this build ` +
606
776
  '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. ' +
777
+ 'Add params \'{"evidence":true}\' to inline each completion\'s evidence and each dispute\'s filed payload: every inlined body is ' +
778
+ 're-bound to the hash its entry signs (result.evidenceBinding; an edited one fails CHAIN_EVIDENCE_BINDING_MISMATCH). ' +
779
+ 'Pass the export exactly as fetched: its length is held to the counts it states (result.entryCount), so an export with ' +
780
+ 'entries removed from the end fails CHECKPOINT_ROW_MISSING or CHAIN_POSITION_GAP. ' +
607
781
  'For the raw COSE_Sign1 stream, use path=/v1/records/{id}/attestation.',
608
782
  inputSchema: toolInput(VERIFY_ARGS),
609
783
  annotations: {
@@ -621,7 +795,7 @@ export class AgledgerMcpServer {
621
795
  if (refused)
622
796
  return refused;
623
797
  try {
624
- const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, } = args;
798
+ const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, federationKeys: federationKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, allowAfterRetirement, expectedEntryCount, } = args;
625
799
  const decodedExport = parseJsonObject(exportRaw, 'export');
626
800
  if (!decodedExport.ok)
627
801
  return decodedExport.error;
@@ -636,13 +810,13 @@ export class AgledgerMcpServer {
636
810
  parseDistrustedKeys(distrustedKeys ?? []);
637
811
  }
638
812
  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>"].');
813
+ return errorResult(describeError(err), 'INVALID_ARGUMENT', 'Pass trustAnchors as ["sha256:<64 hex>"] and distrustedKeys as ["sha256:<64 hex>" or "sha256:<64 hex>@<RFC 3339 instant>"].');
640
814
  }
641
815
  try {
642
816
  assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys);
643
817
  }
644
818
  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.');
819
+ return errorResult(describeError(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
820
  }
647
821
  const anchored = trustAnchors !== undefined && trustAnchors.length > 0;
648
822
  // verify-core reads distrusted keys only during the walk, so without
@@ -652,26 +826,33 @@ export class AgledgerMcpServer {
652
826
  }
653
827
  let publicKeys;
654
828
  if (publicKeysRaw !== undefined && publicKeysRaw !== '') {
655
- const decodedKeys = parseJsonObjectOrArray(publicKeysRaw, 'publicKeys');
829
+ const decodedKeys = parseJsonObject(publicKeysRaw, 'publicKeys', { allowArray: true });
656
830
  if (!decodedKeys.ok)
657
831
  return decodedKeys.error;
658
832
  publicKeys = unwrapVerificationKeys(decodedKeys.value);
659
833
  }
660
834
  let agentKeys;
661
835
  if (agentKeysRaw !== undefined && agentKeysRaw !== '') {
662
- const decodedAgentKeys = parseJsonObjectOrArray(agentKeysRaw, 'agentKeys');
836
+ const decodedAgentKeys = parseJsonObject(agentKeysRaw, 'agentKeys', { allowArray: true });
663
837
  if (!decodedAgentKeys.ok)
664
838
  return decodedAgentKeys.error;
665
- if (!Array.isArray(decodedAgentKeys.value)) {
666
- return errorResult('Argument `agentKeys` must decode to a JSON array of Ed25519 JWKs.', 'INVALID_JSON', 'Pass `agentKeys` as \'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\'.');
667
- }
668
- agentKeys = decodedAgentKeys.value;
839
+ agentKeys = agentKeyList(decodedAgentKeys.value);
840
+ }
841
+ let federationKeys;
842
+ if (federationKeysRaw !== undefined && federationKeysRaw !== '') {
843
+ const decodedFederationKeys = parseJsonObject(federationKeysRaw, 'federationKeys', { allowArray: true });
844
+ if (!decodedFederationKeys.ok)
845
+ return decodedFederationKeys.error;
846
+ federationKeys = decodedFederationKeys.value;
669
847
  }
670
848
  const result = verifyAuditExport(exportData, {
671
849
  publicKeys,
672
850
  agentKeys,
851
+ federationKeys,
673
852
  requireKeyId,
674
853
  requireSuppliedKeys,
854
+ ...(allowAfterRetirement !== undefined ? { allowAfterRetirement } : {}),
855
+ ...(expectedEntryCount !== undefined ? { expectedEntryCount } : {}),
675
856
  ...(anchored ? { trustAnchors, distrustedKeys } : {}),
676
857
  });
677
858
  // verify-core's result verbatim, verdict first (`valid` alone is true
@@ -682,22 +863,24 @@ export class AgledgerMcpServer {
682
863
  return {
683
864
  content: mirrorContent(structured),
684
865
  structuredContent: structured,
685
- isError: !result.valid,
866
+ // A pin that was not met is not a failure of the export (verdict
867
+ // "unanchored"); only a failed verdict is.
868
+ isError: verdict === 'failed',
686
869
  };
687
870
  }
688
871
  catch (err) {
689
872
  // verify-core throws TypeError only on input it refuses (a supplied
690
873
  // key's window that is not RFC 3339, a malformed key list): that is
691
874
  // 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');
875
+ return errorResult(describeError(err), err instanceof TypeError ? 'INVALID_ARGUMENT' : 'VERIFY_FAILED');
693
876
  }
694
877
  });
695
878
  }
696
879
  registerResources() {
697
880
  const client = this.client;
698
881
  /**
699
- * Proxies GET /openapi.json at read time. Keeps the spec fresh, with no local
700
- * cache that could go stale. Clients (Claude Desktop, etc.) surface this
882
+ * Proxies GET /openapi.json at read time. Fetches the spec on every read, with no
883
+ * local cache. Clients (Claude Desktop, etc.) surface this
701
884
  * in their resource picker, so users/agents can pull the spec into context
702
885
  * without constructing an `agledger_api` call.
703
886
  */
@@ -705,25 +888,20 @@ export class AgledgerMcpServer {
705
888
  description: 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json, always current with the running API instance.',
706
889
  mimeType: 'application/json',
707
890
  }, async () => {
708
- const response = await client.request('GET', '/openapi.json');
709
- if (!response.ok) {
710
- throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
711
- }
891
+ const body = await fetchDocument(client, '/openapi.json');
712
892
  return {
713
893
  contents: [
714
894
  {
715
895
  uri: 'agledger://openapi',
716
896
  mimeType: 'application/json',
717
- text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
897
+ text: typeof body === 'string' ? body : JSON.stringify(body),
718
898
  },
719
899
  ],
720
900
  };
721
901
  });
722
902
  /**
723
903
  * Proxies GET /llms.txt at read time. The API writes this narrative for
724
- * agents, and an MCP-connected agent had no way to learn it existed: the
725
- * CLI advertised it, this server did not. Same live-fetch approach as the
726
- * spec resource, so it cannot go stale.
904
+ * agents. Same live-fetch approach as the spec resource.
727
905
  */
728
906
  this.mcp.registerResource('agledger-llms-txt', 'agledger://llms.txt', {
729
907
  description: "The AGLedger API's agent-oriented documentation narrative (the llms.txt convention). " +
@@ -732,13 +910,9 @@ export class AgledgerMcpServer {
732
910
  'OpenAPI spec if you are new to the API.',
733
911
  mimeType: 'text/plain',
734
912
  }, async () => {
735
- const response = await client.request('GET', '/llms.txt');
736
- if (!response.ok) {
737
- throw new Error(`Failed to fetch /llms.txt: HTTP ${response.status}`);
738
- }
739
913
  // /llms.txt is text/plain, so the client surfaces the raw body rather
740
914
  // than a parsed object.
741
- const body = response.body;
915
+ const body = await fetchDocument(client, '/llms.txt');
742
916
  const text = typeof body === 'string'
743
917
  ? body
744
918
  : body && typeof body === 'object' && '_raw' in body