@agledger/mcp-server 2.10.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -13,8 +13,10 @@
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
+ import { OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
19
+ import { DelegationSource, DelegationSourceError } from './delegation.js';
18
20
  import { SERVER_VERSION } from './version.js';
19
21
  export { SERVER_VERSION };
20
22
  const QUICKSTART = {
@@ -51,18 +53,64 @@ function mirrorContent(structured) {
51
53
  * API-origin errors are forwarded verbatim without enrichment; if the API
52
54
  * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
53
55
  */
54
- function errorResult(message, code, suggestion) {
56
+ function errorResult(message, code, suggestion, extra) {
55
57
  const structuredContent = { error: true, message };
56
58
  if (code)
57
59
  structuredContent.code = code;
58
60
  if (suggestion)
59
61
  structuredContent.suggestion = suggestion;
62
+ if (extra)
63
+ Object.assign(structuredContent, extra);
60
64
  return {
61
65
  content: mirrorContent(structuredContent),
62
66
  structuredContent,
63
67
  isError: true,
64
68
  };
65
69
  }
70
+ /**
71
+ * The credential could not produce a bearer. This is a client-side failure (the
72
+ * request never went out), so it is reported in the server's own error shape.
73
+ * The exchange's refusal is carried as the Server sent it, scrubbed of any
74
+ * token, and its recoveryHint is passed through rather than rewritten.
75
+ */
76
+ function credentialErrorResult(err) {
77
+ if (err instanceof OidcExchangeError) {
78
+ return errorResult(err.message, err.code, err.recoveryHint ??
79
+ 'The OIDC cert exchange was refused. Check that the token source yields a current token from an issuer registered for agents on this Server.', err.status ? { status: err.status, response: err.body } : undefined);
80
+ }
81
+ if (err instanceof DelegationSourceError) {
82
+ 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
+ }
84
+ if (err instanceof OidcTokenSourceError) {
85
+ 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
+ }
87
+ return undefined;
88
+ }
89
+ /**
90
+ * A tool's input schema, refusing arguments it does not declare.
91
+ *
92
+ * zod's default object strips unknown keys, so `agledger_api` called with
93
+ * `body` instead of `params` sent no payload at all and the agent read the
94
+ * Server's "body must be object" as a payload problem. The object is loose so
95
+ * the handler sees the stray key and can name it; `additionalProperties` is
96
+ * then dropped from the published schema, which is what it said before. JSON
97
+ * Schema reads an absent `additionalProperties` as "allowed", same as the `{}`
98
+ * a loose object would publish, and Gemini's function-call grammar rejects
99
+ * the keyword outright. `tests/tool-schema.test.ts` asserts the published
100
+ * document.
101
+ */
102
+ function toolInput(shape) {
103
+ return z.looseObject(shape).meta({ additionalProperties: undefined });
104
+ }
105
+ function unknownArgumentResult(tool, shape, args, hint) {
106
+ const declared = Object.keys(shape);
107
+ const unknown = Object.keys(args).filter((k) => !declared.includes(k));
108
+ if (unknown.length === 0)
109
+ return undefined;
110
+ const names = unknown.map((k) => `\`${k}\``).join(', ');
111
+ const accepted = declared.length ? declared.map((k) => `\`${k}\``).join(', ') : 'no arguments';
112
+ return errorResult(`${tool} does not take ${unknown.length === 1 ? 'the argument' : 'the arguments'} ${names}. It accepts ${accepted}.`, 'UNKNOWN_ARGUMENT', `${hint ? `${hint} ` : ''}Call ${tool} again with only the arguments it declares.`, { unknownArguments: unknown, acceptedArguments: declared });
113
+ }
66
114
  // Free-form object fields are declared as `string` on the wire so Gemini's
67
115
  // function-call grammar (a strict OpenAPI 3.0 subset that rejects
68
116
  // `additionalProperties` and properties-less OBJECT) can emit them. The
@@ -107,7 +155,7 @@ function parseJsonObject(value, fieldName) {
107
155
  /**
108
156
  * Parse a JSON-encoded object OR array. Used for fields that legitimately
109
157
  * accept either shape (e.g. `agledger_verify.publicKeys`, which accepts verify-core
110
- * `OutOfBandKeyEntry[]` polymorphism). Strings,
158
+ * `SuppliedKeyEntry[]` polymorphism). Strings,
111
159
  * numbers, booleans, and null still fail loudly.
112
160
  */
113
161
  function parseJsonObjectOrArray(value, fieldName) {
@@ -144,6 +192,188 @@ function unwrapVerificationKeys(raw) {
144
192
  }
145
193
  return raw;
146
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
+ }
253
+ /**
254
+ * 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,
261
+ * reported at position 0 when trustAnchors are given.
262
+ */
263
+ const EXPORT_FAILURE_CODES = [
264
+ 'CHAIN_HASH_MISMATCH',
265
+ 'CHAIN_LINK_BROKEN',
266
+ 'CHAIN_GENESIS_INVALID',
267
+ 'CHAIN_POSITION_GAP',
268
+ 'CHAIN_MALFORMED_ENTRY',
269
+ 'CHAIN_COSE_DECODE_FAILED',
270
+ 'CHAIN_COSE_HEADER_MISMATCH',
271
+ 'CHAIN_PAYLOAD_BINDING_MISMATCH',
272
+ 'CHAIN_OIDC_ACTOR_MISMATCH',
273
+ 'CHAIN_SIGNATURE_INVALID',
274
+ 'CHAIN_SIGNATURE_MISSING_KEY',
275
+ 'CHAIN_ENTRY_UNSIGNED',
276
+ 'CHAIN_KEY_POLICY_VIOLATION',
277
+ 'CHAIN_KEY_EXPIRED',
278
+ 'CHAIN_KEY_NOT_YET_ACTIVE',
279
+ 'CHAIN_ALG_MISMATCH',
280
+ 'CHAIN_SIGNING_KEY_DRIFT',
281
+ 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH',
282
+ 'CHAIN_AGENT_SIGNATURE_INVALID',
283
+ 'CHAIN_UNSUPPORTED_ALGORITHM',
284
+ 'CHAIN_SIGNING_KEY_UNANCHORED',
285
+ 'KEY_STATEMENT_INVALID',
286
+ 'KEY_CLOSURE_INVALID',
287
+ 'CHAIN_KEY_WINDOW_DRIFT',
288
+ 'UNSUPPORTED_FORMAT',
289
+ 'CHAIN_EMPTY',
290
+ ];
291
+ // Resolves to `true` only when nothing is missing; otherwise the assignment
292
+ // fails and the error names the missing code.
293
+ const exportCodesComplete = true;
294
+ void exportCodesComplete;
295
+ const DISCOVER_ARGS = {};
296
+ const API_ARGS = {
297
+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
298
+ path: z
299
+ .string()
300
+ .describe('API path starting with / (e.g. /v1/records, /v1/schemas, /v1/records/{id}/completions)'),
301
+ params: jsonStringField
302
+ .optional()
303
+ .describe('Request parameters as a JSON-encoded string, e.g. \'{"type":"notarize-generic-v1","criteria":{"task_description":"..."}}\'. ' +
304
+ 'For GET/DELETE: becomes query parameters. For POST/PUT/PATCH: becomes the JSON body. ' +
305
+ 'The body is not type-coerced, so write each value as the type the schema declares. ' +
306
+ 'Identifier fields (externalTaskId, correlationId, platformRef, projectRef, publisher) are ' +
307
+ 'strings even when the identifier is all digits: send "4821", not 4821. ' +
308
+ 'Native JSON objects are also accepted for compatibility.'),
309
+ idempotencyKey: z
310
+ .string()
311
+ .max(256)
312
+ .optional()
313
+ .describe('Optional dedup key for POST calls, max 256 characters. Ignored on other methods. ' +
314
+ 'One is generated per call when you omit it, so a single call is already replay-safe. ' +
315
+ 'Pass your own only when you are retrying a call that may have already reached the ' +
316
+ 'Server (a timeout, a dropped connection): reuse the exact key from the first attempt ' +
317
+ 'and the Server returns the original result instead of notarizing the work twice. ' +
318
+ 'A key is bound to method, route, and body, so a retry that changes the body is ' +
319
+ 'rejected with 400 rather than silently replaying the old response.'),
320
+ };
321
+ const VERIFY_ARGS = {
322
+ export: jsonStringField.describe('The audit export as a JSON-encoded string (the response body from ' +
323
+ 'GET /v1/records/{id}/audit-export, JSON.stringify\'d). Native JSON ' +
324
+ 'objects are also accepted for compatibility.'),
325
+ publicKeys: jsonStringField
326
+ .optional()
327
+ .describe('Optional signing keys you supply. Accepts any of these as a JSON-encoded ' +
328
+ 'string (or a native object/array): a compact map ' +
329
+ '\'{"key-1":"MCowBQYDK2VwAyEA..."}\' (values are base64 SPKI DER; Ed25519 keys ' +
330
+ 'start "MCowBQYDK2Vw", P-256 keys "MFkwEwYHKoZIzj0"), the list shape ' +
331
+ '\'[{"keyId":"key-1","publicKey":"MCowBQYDK2VwAyEA..."}]\', or the raw ' +
332
+ 'GET /v1/verification-keys response envelope (\'{"data":[...], ...}\'); the ' +
333
+ '.data array is unwrapped automatically, so the agledger_api response can be ' +
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.'),
359
+ agentKeys: jsonStringField
360
+ .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). ' +
363
+ 'An entry whose sealed agent signature names one of these keys by thumbprint has that ' +
364
+ 'signature re-verified offline, and fails CHAIN_AGENT_SIGNATURE_INVALID if it does not verify. ' +
365
+ 'Without it, agent signatures are counted in result.agentSignatures but not checked.'),
366
+ requireKeyId: z
367
+ .string()
368
+ .optional()
369
+ .describe('If set, every entry must reference this keyId. Rejects exports signed by a ' +
370
+ 'retired or unexpected key even if cryptographically valid.'),
371
+ requireSuppliedKeys: z
372
+ .boolean()
373
+ .optional()
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.'),
376
+ };
147
377
  export class AgledgerMcpServer {
148
378
  mcp;
149
379
  client;
@@ -158,7 +388,12 @@ export class AgledgerMcpServer {
158
388
  throw new Error('No API URL configured. AGLedger is self-hosted, so the MCP server cannot guess your Server: ' +
159
389
  'pass --api-url <url> or set AGLEDGER_API_URL.');
160
390
  }
161
- this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
391
+ if (Boolean(options.apiKey) === Boolean(options.oidc)) {
392
+ throw new Error('Configure exactly one credential: an API key (--api-key or AGLEDGER_API_KEY) or an OIDC token source ' +
393
+ '(AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE).');
394
+ }
395
+ const credential = options.apiKey ? options.apiKey : new OidcCertCredential(options.oidc);
396
+ this.client = new ApiClient(apiUrl, credential, options.timeoutMs, options.onBehalfOf ? new DelegationSource(options.onBehalfOf) : undefined);
162
397
  this.mcp = new McpServer({ name: 'agledger-mcp-server', version: SERVER_VERSION }, { capabilities: { tools: {}, resources: {} } });
163
398
  this.registerTools();
164
399
  this.registerResources();
@@ -169,7 +404,7 @@ export class AgledgerMcpServer {
169
404
  title: 'Discover AGLedger API',
170
405
  description: 'Returns API health, your identity, available scopes, and a quickstart workflow. ' +
171
406
  'Call this first. The response tells you who you are and what to do next.',
172
- inputSchema: {},
407
+ inputSchema: toolInput(DISCOVER_ARGS),
173
408
  annotations: {
174
409
  readOnlyHint: true,
175
410
  destructiveHint: false,
@@ -182,10 +417,15 @@ export class AgledgerMcpServer {
182
417
  // introspect its own context). No NAMED scope is required, so the list
183
418
  // is empty: a valid API key suffices, but no specific scope gates it.
184
419
  _meta: { requiredScopes: [] },
185
- }, async () => {
420
+ }, async (args) => {
421
+ const refused = unknownArgumentResult('agledger_discover', DISCOVER_ARGS, args);
422
+ if (refused)
423
+ return refused;
186
424
  try {
187
425
  const [health, identity, scopeProfiles] = await Promise.allSettled([
188
- client.request('GET', '/health'),
426
+ // Anonymous, so "is the Server up" stays answerable when the
427
+ // credential is what is broken.
428
+ client.request('GET', '/health', { anonymous: true }),
189
429
  client.request('GET', '/v1/auth/me'),
190
430
  client.request('GET', '/v1/scope-profiles'),
191
431
  ]);
@@ -202,15 +442,28 @@ export class AgledgerMcpServer {
202
442
  result.identity = identity.value.body;
203
443
  }
204
444
  else {
205
- result.identity = {
206
- error: identity.reason instanceof Error
207
- ? identity.reason.message
208
- : String(identity.reason),
209
- };
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
+ };
210
453
  }
211
454
  if (scopeProfiles.status === 'fulfilled') {
212
455
  result.scopeProfiles = scopeProfiles.value.body;
213
456
  }
457
+ // Whether POSTs carry an AGLedger-On-Behalf-Of delegation, and from
458
+ // where. The token itself is never shown.
459
+ const delegationOrigin = client.delegationOrigin;
460
+ result.delegation = delegationOrigin
461
+ ? {
462
+ configured: true,
463
+ source: delegationOrigin,
464
+ note: 'Every POST carries an AGLedger-On-Behalf-Of delegation token; the Server seals it as predicate.on_behalf_of on the chain entry.',
465
+ }
466
+ : { configured: false };
214
467
  result.quickstart = QUICKSTART;
215
468
  result.docs = DOCS;
216
469
  return { content: mirrorContent(result), structuredContent: result };
@@ -235,35 +488,14 @@ export class AgledgerMcpServer {
235
488
  'independently, so there are that many current heads and no single answer. ' +
236
489
  'Filter on signed fields with criteria[key]=value, which selects on the same bytes an ' +
237
490
  'auditor verifies offline; metadata[key]=value filters an unsigned annotation instead. ' +
238
- 'If a call fails, read the suggestion field in the error response. ' +
491
+ 'If a call fails, the error says how to recover: recoveryHint on an error from the Server, ' +
492
+ 'suggestion on an error this tool raises itself (a bad argument, a timeout, a credential failure). ' +
239
493
  'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource); ' +
240
494
  'for prose orientation, GET /llms.txt (or read the agledger://llms.txt resource). ' +
241
- 'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
242
- inputSchema: {
243
- method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
244
- path: z
245
- .string()
246
- .describe('API path starting with / (e.g. /v1/records, /v1/schemas, /v1/records/{id}/completions)'),
247
- params: jsonStringField
248
- .optional()
249
- .describe('Request parameters as a JSON-encoded string, e.g. \'{"type":"notarize-generic-v1","criteria":{"task_description":"..."}}\'. ' +
250
- 'For GET/DELETE: becomes query parameters. For POST/PUT/PATCH: becomes the JSON body. ' +
251
- 'The body is not type-coerced, so write each value as the type the schema declares. ' +
252
- 'Identifier fields (externalTaskId, correlationId, platformRef, projectRef, publisher) are ' +
253
- 'strings even when the identifier is all digits: send "4821", not 4821. ' +
254
- 'Native JSON objects are also accepted for compatibility.'),
255
- idempotencyKey: z
256
- .string()
257
- .max(256)
258
- .optional()
259
- .describe('Optional dedup key for POST calls, max 256 characters. Ignored on other methods. ' +
260
- 'One is generated per call when you omit it, so a single call is already replay-safe. ' +
261
- 'Pass your own only when you are retrying a call that may have already reached the ' +
262
- 'Server (a timeout, a dropped connection): reuse the exact key from the first attempt ' +
263
- 'and the Server returns the original result instead of notarizing the work twice. ' +
264
- 'A key is bound to method, route, and body, so a retry that changes the body is ' +
265
- 'rejected with 400 rather than silently replaying the old response.'),
266
- },
495
+ 'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body. ' +
496
+ 'When agledger_discover reports a delegation, every POST carries the AGLedger-On-Behalf-Of header ' +
497
+ 'the operator configured; it is not something you pass.',
498
+ inputSchema: toolInput(API_ARGS),
267
499
  annotations: {
268
500
  readOnlyHint: false,
269
501
  // This tool dispatches to any route, including DELETE/PATCH, so it can
@@ -281,6 +513,10 @@ export class AgledgerMcpServer {
281
513
  // single scope here would be dishonest. Callers see the real missing
282
514
  // scopes in the API's 403 response (missingScopes), forwarded verbatim.
283
515
  }, async (args) => {
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`.');
517
+ if (refused)
518
+ return refused;
519
+ let sentKey;
284
520
  try {
285
521
  const { method, path, params, idempotencyKey } = args;
286
522
  if (!path.startsWith('/')) {
@@ -302,8 +538,11 @@ export class AgledgerMcpServer {
302
538
  return errorResult('Path contains control characters.', 'PATH_INVALID', 'Remove control characters (newlines, tabs, null bytes) from the path.');
303
539
  }
304
540
  const options = {};
305
- if (idempotencyKey !== undefined)
306
- 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;
307
546
  if (params !== undefined && params !== '') {
308
547
  const decoded = parseJsonObject(params, 'params');
309
548
  if (!decoded.ok)
@@ -333,11 +572,18 @@ export class AgledgerMcpServer {
333
572
  };
334
573
  }
335
574
  catch (err) {
575
+ const credentialError = credentialErrorResult(err);
576
+ if (credentialError)
577
+ return credentialError;
336
578
  if (err instanceof DOMException && err.name === 'AbortError') {
337
- 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);
338
582
  }
339
583
  if (err instanceof TypeError && err.message.includes('fetch')) {
340
- 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);
341
587
  }
342
588
  return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
343
589
  }
@@ -348,43 +594,18 @@ export class AgledgerMcpServer {
348
594
  'Decodes each entry\'s tagged COSE_Sign1 envelope (RFC 9052), recomputes ' +
349
595
  'sha256 over the envelope bytes, walks the hash chain, cross-checks the protected-' +
350
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). ' +
351
- 'No network calls. For an independent audit, pass publicKeys obtained out of band ' +
352
- '(GET /v1/verification-keys or /.well-known/scitt-keys) rather than trusting the ' +
353
- '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. ' +
354
604
  'On failure, brokenAt pinpoints the first entry that failed and its canonical code ' +
355
- '(CHAIN_HASH_MISMATCH, CHAIN_LINK_BROKEN, CHAIN_GENESIS_INVALID, CHAIN_COSE_DECODE_FAILED, ' +
356
- 'CHAIN_COSE_HEADER_MISMATCH, CHAIN_PAYLOAD_BINDING_MISMATCH, CHAIN_SIGNATURE_INVALID, ' +
357
- 'CHAIN_SIGNATURE_MISSING_KEY, CHAIN_KEY_POLICY_VIOLATION, CHAIN_ALG_MISMATCH, ' +
358
- 'CHAIN_SIGNING_KEY_DRIFT, CHAIN_UNSUPPORTED_ALGORITHM (this build cannot compute the ' +
359
- 'key\'s algorithm; upgrade, never a pass), CHAIN_POSITION_GAP, CHAIN_MALFORMED_ENTRY, ' +
360
- 'UNSUPPORTED_FORMAT, CHAIN_EMPTY). Obtain the export via agledger_api with method=GET, path=/v1/records/{id}/audit-export. ' +
605
+ `(${EXPORT_FAILURE_CODES.join(', ')}); CHAIN_UNSUPPORTED_ALGORITHM means this build ` +
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. ' +
361
607
  'For the raw COSE_Sign1 stream, use path=/v1/records/{id}/attestation.',
362
- inputSchema: {
363
- export: jsonStringField.describe('The audit export as a JSON-encoded string (the response body from ' +
364
- 'GET /v1/records/{id}/audit-export, JSON.stringify\'d). Native JSON ' +
365
- 'objects are also accepted for compatibility.'),
366
- publicKeys: jsonStringField
367
- .optional()
368
- .describe('Optional out-of-band signing keys. Accepts any of these as a JSON-encoded ' +
369
- 'string (or a native object/array): a compact map ' +
370
- '\'{"key-1":"MCowBQYDK2VwAyEA..."}\' (values are base64 SPKI DER; Ed25519 keys ' +
371
- 'start "MCowBQYDK2Vw", P-256 keys "MFkwEwYHKoZIzj0"), the list shape ' +
372
- '\'[{"keyId":"key-1","publicKey":"MCowBQYDK2VwAyEA..."}]\', or the raw ' +
373
- 'GET /v1/verification-keys response envelope (\'{"data":[...], ...}\'); the ' +
374
- '.data array is unwrapped automatically, so the agledger_api response can be ' +
375
- 'passed straight through). Merged over any keys embedded in the export.'),
376
- requireKeyId: z
377
- .string()
378
- .optional()
379
- .describe('If set, every entry must reference this keyId. Rejects exports signed by a ' +
380
- 'retired or unexpected key even if cryptographically valid.'),
381
- requireOutOfBandKeys: z
382
- .boolean()
383
- .optional()
384
- .describe('High-assurance: refuse keys embedded in the export. An entry whose only key is ' +
385
- 'export-embedded fails CHAIN_KEY_POLICY_VIOLATION, forcing verification against ' +
386
- 'keys supplied out of band via publicKeys.'),
387
- },
608
+ inputSchema: toolInput(VERIFY_ARGS),
388
609
  annotations: {
389
610
  readOnlyHint: true,
390
611
  destructiveHint: false,
@@ -396,8 +617,11 @@ export class AgledgerMcpServer {
396
617
  // required to invoke it.
397
618
  _meta: { requiredScopes: [] },
398
619
  }, async (args) => {
620
+ const refused = unknownArgumentResult('agledger_verify', VERIFY_ARGS, args);
621
+ if (refused)
622
+ return refused;
399
623
  try {
400
- const { export: exportRaw, publicKeys: publicKeysRaw, requireKeyId, requireOutOfBandKeys } = args;
624
+ const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, } = args;
401
625
  const decodedExport = parseJsonObject(exportRaw, 'export');
402
626
  if (!decodedExport.ok)
403
627
  return decodedExport.error;
@@ -405,6 +629,27 @@ export class AgledgerMcpServer {
405
629
  if (!('entries' in exportData)) {
406
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.');
407
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
+ }
408
653
  let publicKeys;
409
654
  if (publicKeysRaw !== undefined && publicKeysRaw !== '') {
410
655
  const decodedKeys = parseJsonObjectOrArray(publicKeysRaw, 'publicKeys');
@@ -412,12 +657,28 @@ export class AgledgerMcpServer {
412
657
  return decodedKeys.error;
413
658
  publicKeys = unwrapVerificationKeys(decodedKeys.value);
414
659
  }
660
+ let agentKeys;
661
+ if (agentKeysRaw !== undefined && agentKeysRaw !== '') {
662
+ const decodedAgentKeys = parseJsonObjectOrArray(agentKeysRaw, 'agentKeys');
663
+ if (!decodedAgentKeys.ok)
664
+ 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;
669
+ }
415
670
  const result = verifyAuditExport(exportData, {
416
671
  publicKeys,
672
+ agentKeys,
417
673
  requireKeyId,
418
- requireOutOfBandKeys,
674
+ requireSuppliedKeys,
675
+ ...(anchored ? { trustAnchors, distrustedKeys } : {}),
419
676
  });
420
- 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 };
421
682
  return {
422
683
  content: mirrorContent(structured),
423
684
  structuredContent: structured,
@@ -425,7 +686,10 @@ export class AgledgerMcpServer {
425
686
  };
426
687
  }
427
688
  catch (err) {
428
- 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');
429
693
  }
430
694
  });
431
695
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agledger/mcp-server",
3
- "version": "2.10.1",
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.4.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
  },