@agledger/mcp-server 2.0.2 → 2.1.1

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/LICENSE CHANGED
@@ -2,33 +2,126 @@ Copyright (c) 2026 AGLedger LLC. All rights reserved.
2
2
 
3
3
  PROPRIETARY SOFTWARE LICENSE
4
4
 
5
- This software and associated documentation files (the "Software") are the
6
- proprietary property of AGLedger LLC. The Software is provided for use
7
- exclusively with a self-hosted AGLedger API instance.
5
+ This software, together with its associated documentation files (the "Software"),
6
+ is the proprietary property of AGLedger LLC ("Licensor"). The Software is
7
+ licensed, not sold. Your right to use the Software is limited as set out below.
8
8
 
9
- Permission is hereby granted to use the Software solely for the purpose of
10
- integrating with AGLedger services via the AGLedger API, subject to the
11
- following conditions:
9
+ BY DOWNLOADING, INSTALLING, COPYING, OR OTHERWISE USING THE SOFTWARE (INCLUDING
10
+ VIA `npm install`, `pip install`, OR ANY EQUIVALENT PACKAGE-MANAGER COMMAND),
11
+ YOU AGREE TO THE TERMS OF THIS LICENSE. IF YOU DO NOT AGREE, DO NOT DOWNLOAD,
12
+ INSTALL, OR USE THE SOFTWARE.
12
13
 
13
- 1. You may not copy, modify, merge, publish, distribute, sublicense, or sell
14
- copies of the Software, except as required to use it with the AGLedger API.
14
+ 1. GRANT OF USE
15
15
 
16
- 2. You may not use the Software to create a competing product or service.
16
+ Licensor grants you a limited, non-exclusive, non-transferable, revocable
17
+ license to install and use the Software solely for the purpose of integrating
18
+ with a self-hosted AGLedger deployment operated by you or your organization, or
19
+ by a third party on your behalf with your authorization. The Software is not
20
+ designed for, and is not licensed for use with, any AGLedger-hosted service.
21
+ AGLedger operates the AGLedger software on a self-hosted model; there is no
22
+ hosted AGLedger API.
17
23
 
18
- 3. You may not reverse engineer, decompile, or disassemble the Software,
19
- except to the extent permitted by applicable law.
24
+ 2. RESTRICTIONS
20
25
 
21
- Use of this software is subject to the AGLedger Terms of Service at
22
- https://agledger.ai/terms.
26
+ You may not:
23
27
 
24
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27
- AGLEDGER LLC BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
28
- AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
29
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
+ (a) copy, modify, merge, publish, distribute, sublicense, sell, rent, lease,
29
+ or transfer copies of the Software, except as strictly required to use
30
+ the Software for its intended integration purpose;
31
+ (b) offer the Software, or the functionality enabled by the Software, as a
32
+ hosted or managed service to third parties, whether as a standalone
33
+ offering or embedded within a larger service;
34
+ (c) use the Software to build, train, or benchmark a product or service that
35
+ competes with AGLedger;
36
+ (d) reverse engineer, decompile, or disassemble the Software, except to the
37
+ extent expressly permitted by applicable law that cannot be waived by
38
+ contract;
39
+ (e) circumvent, disable, or tamper with any authentication, license, or usage-
40
+ enforcement mechanism of the Software or of any AGLedger deployment;
41
+ (f) remove, alter, or obscure any copyright, trademark, patent, or other
42
+ proprietary notice in the Software;
43
+ (g) use the Software in violation of U.S. Export Administration Regulations,
44
+ economic sanctions, or other applicable export and trade-control laws.
30
45
 
31
- ---
46
+ 3. OPEN SOURCE COMPONENTS
32
47
 
33
- AGLedger™ and the Agentic Contract Specification™ are trademarks of
34
- AGLedger LLC. Patent pending.
48
+ The Software may include third-party open-source components, each subject to
49
+ its own license terms. A list of such components and their licenses is included
50
+ with or referenced from the Software. In the event of a conflict between this
51
+ License and an open-source license, the open-source license governs solely with
52
+ respect to that component.
53
+
54
+ 4. NO WARRANTY
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS" AND "AS AVAILABLE", WITHOUT WARRANTY OF ANY
57
+ KIND, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO THE
58
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
59
+ NONINFRINGEMENT. AGLEDGER LLC DOES NOT WARRANT THAT THE SOFTWARE WILL BE ERROR-
60
+ FREE, SECURE, OR UNINTERRUPTED.
61
+
62
+ 5. LIMITATION OF LIABILITY
63
+
64
+ The limitations in this Section 5 are a material inducement to AGLedger LLC to
65
+ make the Software publicly available at no charge, and they apply notwithstanding
66
+ any failure of essential purpose of any limited remedy and regardless of the
67
+ theory of liability (contract, tort, strict liability, statute, or otherwise).
68
+
69
+ TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL AGLEDGER
70
+ LLC BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY,
71
+ OR PUNITIVE DAMAGES, OR FOR LOSS OF PROFITS, REVENUE, DATA, USE, GOODWILL, OR
72
+ BUSINESS OPPORTUNITY, ARISING FROM OR RELATED TO THE SOFTWARE, EVEN IF ADVISED
73
+ OF THE POSSIBILITY OF SUCH DAMAGES. AGLEDGER LLC'S TOTAL AGGREGATE LIABILITY
74
+ FOR ALL CLAIMS RELATED TO THE SOFTWARE SHALL NOT EXCEED ONE HUNDRED U.S.
75
+ DOLLARS ($100.00). Any claim must be commenced within one (1) year after the
76
+ cause of action accrues, to the maximum extent permitted by applicable law.
77
+
78
+ 6. EXPORT COMPLIANCE
79
+
80
+ The Software may include cryptographic functionality (including Ed25519, AES-
81
+ 256-GCM, SHA-256, and X25519). AGLedger LLC classifies the Software under
82
+ ECCN 5D002 in good faith. To the extent AGLedger LLC makes the source code of
83
+ the Software publicly available through a public repository, that source code
84
+ is subject to the treatment afforded under 15 CFR § 742.15(b) of the U.S.
85
+ Export Administration Regulations. Binary and object-code distributions are
86
+ subject to License Exception ENC under 15 CFR § 740.17, subject to the one-
87
+ time notification and any required Encryption Registration to the U.S. Bureau
88
+ of Industry and Security (BIS) and the NSA ENC Encryption Request Coordinator.
89
+ This statement is not a warranty; you are responsible for independently
90
+ confirming the correct classification and license authority for your use,
91
+ destination, and end-user. You shall not export or re-export the Software to
92
+ any destination, entity, or end-use prohibited by applicable export, sanctions,
93
+ or trade-control laws.
94
+
95
+ 7. TRADEMARKS
96
+
97
+ AGLedger, Agentic Ledger, Settlement Signal, and Agentic Operations and
98
+ Accountability Protocol (AOAP) are trademarks of AGLedger LLC. All other
99
+ trademarks are the property of their respective owners.
100
+
101
+ 8. PATENTS
102
+
103
+ The Software is covered by one or more U.S. patent applications pending before
104
+ the U.S. Patent and Trademark Office in AGLedger LLC's patent portfolio.
105
+
106
+ 9. RELATIONSHIP TO OTHER AGLEDGER AGREEMENTS
107
+
108
+ If you are also a Licensee under an AGLedger Software License Agreement
109
+ executed with an Order Form, that Software License Agreement governs your
110
+ organization's use of the Licensed Software (including the Software distributed
111
+ under this License) and supersedes this License to the extent of any conflict.
112
+ Absent such an agreement, this License is the exclusive and entire license
113
+ between you and AGLedger LLC for the Software.
114
+
115
+ 10. GOVERNING LAW
116
+
117
+ This License is governed by the laws of the State of Idaho, without regard to
118
+ its conflict-of-laws provisions. Any dispute arising out of or related to this
119
+ License shall first be subject to good-faith negotiation for thirty (30) days,
120
+ and then, at AGLedger LLC's option, to binding arbitration under the rules of
121
+ the American Arbitration Association in Ada County, Idaho, or to the state or
122
+ federal courts located in Ada County, Idaho. You consent to the personal
123
+ jurisdiction and venue of those forums.
124
+
125
+ 11. CONTACT
126
+
127
+ For licensing inquiries, contact: legal@agledger.ai
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The official [MCP](https://modelcontextprotocol.io) server for the [AGLedger](https://agledger.ai) API -- accountability and audit infrastructure for agentic systems.
4
4
 
5
- Connects any MCP-compatible AI agent (Claude, Cursor, Windsurf, etc.) to the AGLedger API with just 2 universal tools. No SDK code required -- just point your agent at this server.
5
+ Connects any MCP-compatible AI agent (Claude, Cursor, Windsurf, etc.) to the AGLedger API with 2 universal API-pass-through tools plus an offline audit verifier. No SDK code required -- just point your agent at this server.
6
6
 
7
7
  ## Install
8
8
 
@@ -37,6 +37,7 @@ agledger-mcp --api-key <key> [--api-url <url>]
37
37
  |------|-------------|
38
38
  | `agledger_discover` | Returns API health, your identity, available scopes, and a quickstart workflow. Call this first. |
39
39
  | `agledger_api` | Make any AGLedger API call (method, path, params). The API returns `nextSteps` on every response for self-guided workflow discovery. |
40
+ | `agledger_verify` | Verify a mandate audit export offline (RFC 8785 hash chain + Ed25519 signatures). No network calls. Returns `valid`, `verifiedEntries`, and a `brokenAt` pointer on failure. |
40
41
 
41
42
  ### Agent workflow
42
43
 
@@ -65,15 +66,17 @@ AGLedger is the accountability layer for automated operations. It records what w
65
66
  - **Verdicts** -- principal acceptance decisions (PASS/FAIL) with settlement signals
66
67
  - **Audit trail** -- hash-chained, Ed25519-signed, tamper-evident record
67
68
 
68
- Learn more at [agledger.ai](https://agledger.ai) | [API docs](https://docs.agledger.ai)
69
+ Learn more at [agledger.ai](https://www.agledger.ai) | [API docs](https://www.agledger.ai/docs/)
70
+
71
+ Each self-hosted AGLedger instance also serves interactive Swagger UI at `{AGLEDGER_API_URL}/docs`.
69
72
 
70
73
  ## Requirements
71
74
 
72
75
  - Node.js >= 22
73
- - An AGLedger API key ([sign up](https://agledger.ai))
76
+ - A running self-hosted AGLedger API instance and an API key (see the self-hosted install guide at [agledger.ai](https://www.agledger.ai))
74
77
 
75
78
  ## License
76
79
 
77
80
  Proprietary. See [LICENSE](./LICENSE).
78
81
 
79
- AGLedger™ and the Agentic Contract Specification™ are trademarks of AGLedger LLC. Patent pending.
82
+ AGLedger, Agentic Ledger, Settlement Signal, and Agentic Operations and Accountability Protocol (AOAP) are trademarks of AGLedger LLC. Patent pending.
@@ -19,7 +19,7 @@ export class ApiClient {
19
19
  const headers = {
20
20
  Authorization: `Bearer ${this.apiKey}`,
21
21
  Accept: 'application/json',
22
- 'User-Agent': 'agledger-mcp-server/2.0.2',
22
+ 'User-Agent': 'agledger-mcp-server/2.1.0',
23
23
  };
24
24
  if (options?.body !== undefined) {
25
25
  headers['Content-Type'] = 'application/json';
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ function main() {
18
18
  strict: true,
19
19
  });
20
20
  if (values.help) {
21
- process.stderr.write(`AGLedger MCP Server v2.0.2
21
+ process.stderr.write(`AGLedger MCP Server v2.1.0
22
22
 
23
23
  Usage: agledger-mcp --api-key <key> [--api-url <url>]
24
24
 
package/dist/server.d.ts CHANGED
@@ -3,11 +3,14 @@ import { ApiClient } from './api-client.js';
3
3
  export interface AgledgerMcpServerOptions {
4
4
  apiKey: string;
5
5
  apiUrl?: string;
6
+ /** Request timeout in milliseconds. Default 30000. */
7
+ timeoutMs?: number;
6
8
  }
7
9
  export declare class AgledgerMcpServer {
8
10
  readonly mcp: McpServer;
9
11
  readonly client: ApiClient;
10
12
  constructor(options: AgledgerMcpServerOptions);
11
13
  private registerTools;
14
+ private registerResources;
12
15
  }
13
16
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAEpE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAoDD,qBAAa,iBAAiB;IAC5B,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;gBAEf,OAAO,EAAE,wBAAwB;IAa7C,OAAO,CAAC,aAAa;CAuJtB"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAIpE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sDAAsD;IACtD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAoCD,qBAAa,iBAAiB;IAC5B,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC;gBAEf,OAAO,EAAE,wBAAwB;IAc7C,OAAO,CAAC,aAAa;IA6NrB,OAAO,CAAC,iBAAiB;CAkC1B"}
package/dist/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { verifyExport } from '@agledger/sdk/verify';
3
4
  import { ApiClient } from './api-client.js';
4
5
  const QUICKSTART = {
5
6
  description: 'To track accountability for your work, follow these steps in order:',
@@ -11,50 +12,37 @@ const QUICKSTART = {
11
12
  ],
12
13
  };
13
14
  const DOCS = {
14
- quickReference: '/llms-agent.txt',
15
- fullReference: '/llms.txt',
15
+ description: 'Every API response includes nextSteps for self-guided workflow discovery. ' +
16
+ 'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog.',
17
+ openapi: '/openapi.json',
18
+ openapiResource: 'agledger://openapi',
16
19
  };
17
- function errorResult(message) {
18
- return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
19
- }
20
- function recoveryHint(status, method, path) {
21
- if (status === 400) {
22
- return `Check required fields. Call GET /v1/schemas to see valid contract types, or GET /v1/schemas/{type} for the exact schema.`;
23
- }
24
- if (status === 401) {
25
- return 'API key is invalid or expired. Call agledger_discover to verify your identity.';
26
- }
27
- if (status === 403) {
28
- return 'Your API key lacks the required scope. Check the missingScopes field above.';
29
- }
30
- if (status === 404) {
31
- if (path.includes('/mandates/') && method === 'POST' && path.includes('/receipts')) {
32
- return 'Mandate not found. Call GET /v1/mandates to list your mandates and verify the ID.';
33
- }
34
- return `Resource not found at ${path}. All routes start with /v1/. Call GET /llms-agent.txt for the full API reference.`;
35
- }
36
- if (status === 409) {
37
- return 'Conflict — the resource state does not allow this action. Check the mandate status with GET /v1/mandates/{id}.';
38
- }
39
- if (status === 422) {
40
- return 'Validation failed. Check the validationErrors field above for specific field issues. Call GET /v1/schemas/{type} for the expected format.';
41
- }
42
- if (status === 429) {
43
- return 'Rate limited. Wait a moment, then retry the same request.';
44
- }
45
- if (status >= 500) {
46
- return 'Server error. Retry the same request. If it persists, try GET /health to check API status.';
47
- }
48
- return `Unexpected status ${status}. Try GET /health to verify API status.`;
20
+ /**
21
+ * Structured error for CLI-origin failures (network, timeout, malformed input).
22
+ * API-origin errors are forwarded verbatim without enrichment — if the API
23
+ * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
24
+ */
25
+ function errorResult(message, code, suggestion) {
26
+ const structuredContent = { error: true, message };
27
+ if (code)
28
+ structuredContent.code = code;
29
+ if (suggestion)
30
+ structuredContent.suggestion = suggestion;
31
+ return {
32
+ content: [{ type: 'text', text: `Error: ${message}` }],
33
+ structuredContent,
34
+ isError: true,
35
+ };
49
36
  }
50
37
  export class AgledgerMcpServer {
51
38
  mcp;
52
39
  client;
53
40
  constructor(options) {
54
41
  const apiUrl = options.apiUrl ?? 'https://agledger.example.com';
55
- this.client = new ApiClient(apiUrl, options.apiKey);
56
- this.mcp = new McpServer({ name: 'agledger-mcp-server', version: '2.0.2' }, { capabilities: { tools: {} } });
42
+ this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
43
+ this.mcp = new McpServer({ name: 'agledger-mcp-server', version: '2.1.1' }, { capabilities: { tools: {}, resources: {} } });
57
44
  this.registerTools();
45
+ this.registerResources();
58
46
  }
59
47
  registerTools() {
60
48
  const client = this.client;
@@ -99,7 +87,7 @@ export class AgledgerMcpServer {
99
87
  return { content: [], structuredContent: result };
100
88
  }
101
89
  catch (err) {
102
- return errorResult(err instanceof Error ? err.message : String(err));
90
+ return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
103
91
  }
104
92
  });
105
93
  this.mcp.registerTool('agledger_api', {
@@ -111,7 +99,7 @@ export class AgledgerMcpServer {
111
99
  '3. POST /v1/mandates — create a mandate. ' +
112
100
  '4. POST /v1/mandates/{id}/receipts — submit evidence when done. ' +
113
101
  'If a call fails, read the suggestion field in the error response. ' +
114
- 'For full API docs: GET /llms-agent.txt. ' +
102
+ 'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource). ' +
115
103
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
116
104
  inputSchema: {
117
105
  method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
@@ -133,8 +121,8 @@ export class AgledgerMcpServer {
133
121
  try {
134
122
  const { method, path, params } = args;
135
123
  if (!path.startsWith('/')) {
136
- return errorResult('PATH_INVALID: Path must start with /. All API routes use /v1/ prefix. ' +
137
- 'Example: /v1/mandates, /v1/schemas. Call agledger_discover for the full workflow.');
124
+ return errorResult('Path must start with /. All API routes use /v1/ prefix. ' +
125
+ 'Example: /v1/mandates, /v1/schemas. Call agledger_discover for the full workflow.', 'PATH_INVALID', 'Prefix the path with /v1/ (e.g. /v1/mandates). Call agledger_discover if unsure which path to use.');
138
126
  }
139
127
  const options = {};
140
128
  if (params) {
@@ -152,13 +140,12 @@ export class AgledgerMcpServer {
152
140
  structuredContent: response.body,
153
141
  };
154
142
  }
143
+ // Forward the API error body verbatim. The API owns error guidance;
144
+ // the MCP does not enrich, translate, or inject suggestions.
155
145
  const errorBody = (response.body ?? {});
156
146
  const message = (errorBody.message ??
157
147
  errorBody.error ??
158
148
  `API returned ${response.status}`);
159
- if (!errorBody.suggestion) {
160
- errorBody.suggestion = recoveryHint(response.status, method, path);
161
- }
162
149
  return {
163
150
  content: [{ type: 'text', text: `Error: ${message}` }],
164
151
  structuredContent: errorBody,
@@ -167,15 +154,90 @@ export class AgledgerMcpServer {
167
154
  }
168
155
  catch (err) {
169
156
  if (err instanceof DOMException && err.name === 'AbortError') {
170
- return errorResult('TIMEOUT: The API did not respond within 30 seconds. ' +
171
- 'Retry the same request. If it fails again, try GET /health to check API status.');
157
+ 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.');
172
158
  }
173
159
  if (err instanceof TypeError && err.message.includes('fetch')) {
174
- return errorResult(`NETWORK_ERROR: ${err.message}. ` +
175
- 'Check that the API URL is correct. Try GET /health to verify connectivity.');
160
+ return errorResult(err.message, 'NETWORK_ERROR', 'Check that the API URL is correct. Try GET /health to verify connectivity.');
176
161
  }
177
- return errorResult(err instanceof Error ? err.message : String(err));
162
+ return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
163
+ }
164
+ });
165
+ this.mcp.registerTool('agledger_verify', {
166
+ title: 'Verify Audit Export',
167
+ description: 'Verify an AGLedger audit export offline. Recomputes RFC 8785 canonical hashes, ' +
168
+ 'walks the hash chain, and verifies every Ed25519 signature. ' +
169
+ 'No network calls — trust is rooted in the export\'s embedded signing keys (and/or ' +
170
+ 'the publicKeys override). On failure, brokenAt pinpoints the first entry that failed ' +
171
+ 'and why (payload_hash_mismatch, chain_break, signature_invalid, unknown_key, ' +
172
+ 'position_gap, malformed_entry, unsupported_algorithm). ' +
173
+ 'Obtain the export via agledger_api with method=GET, path=/v1/mandates/{id}/audit-export.',
174
+ inputSchema: {
175
+ export: z
176
+ .record(z.string(), z.unknown())
177
+ .describe('The parsed audit export JSON (the response body from GET /v1/mandates/{id}/audit-export).'),
178
+ publicKeys: z
179
+ .record(z.string(), z.string())
180
+ .optional()
181
+ .describe('Optional map of signingKeyId → SPKI DER base64 public key. Merged over any keys ' +
182
+ 'embedded in the export. Use this to verify against an independently-trusted key set.'),
183
+ requireKeyId: z
184
+ .string()
185
+ .optional()
186
+ .describe('If set, every entry must reference this keyId. Rejects exports signed by a ' +
187
+ 'retired or unexpected key even if cryptographically valid.'),
188
+ },
189
+ annotations: {
190
+ readOnlyHint: true,
191
+ destructiveHint: false,
192
+ idempotentHint: true,
193
+ openWorldHint: false,
194
+ },
195
+ }, async (args) => {
196
+ try {
197
+ const { export: exportData, publicKeys, requireKeyId } = args;
198
+ if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
199
+ 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/mandates/{id}/audit-export, then pass the response body as the `export` argument.');
200
+ }
201
+ const result = verifyExport(exportData, {
202
+ publicKeys,
203
+ requireKeyId,
204
+ });
205
+ return {
206
+ content: [],
207
+ structuredContent: result,
208
+ isError: !result.valid,
209
+ };
210
+ }
211
+ catch (err) {
212
+ return errorResult(err instanceof Error ? err.message : String(err), 'VERIFY_FAILED');
213
+ }
214
+ });
215
+ }
216
+ registerResources() {
217
+ const client = this.client;
218
+ /**
219
+ * Proxies GET /openapi.json at read time. Keeps the spec fresh — no local
220
+ * cache that could go stale. Clients (Claude Desktop, etc.) surface this
221
+ * in their resource picker, so users/agents can pull the spec into context
222
+ * without constructing an `agledger_api` call.
223
+ */
224
+ this.mcp.registerResource('agledger-openapi', 'agledger://openapi', {
225
+ description: 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json — always current with the running API instance.',
226
+ mimeType: 'application/json',
227
+ }, async () => {
228
+ const response = await client.request('GET', '/openapi.json');
229
+ if (!response.ok) {
230
+ throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
178
231
  }
232
+ return {
233
+ contents: [
234
+ {
235
+ uri: 'agledger://openapi',
236
+ mimeType: 'application/json',
237
+ text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
238
+ },
239
+ ],
240
+ };
179
241
  });
180
242
  }
181
243
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.js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SAC7B,EACD,KAAK,IAAI,EAAE;YACT,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;YAC9D,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,MAAM,IAAI,KAAK,CAAC,uCAAuC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YAC5E,CAAC;YACD,OAAO;gBACL,QAAQ,EAAE;oBACR;wBACE,GAAG,EAAE,oBAAoB;wBACzB,QAAQ,EAAE,kBAAkB;wBAC5B,IAAI,EAAE,OAAO,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC;qBACxF;iBACF;aACF,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agledger/mcp-server",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
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",
@@ -39,6 +39,7 @@
39
39
  "lint": "tsc --noEmit"
40
40
  },
41
41
  "dependencies": {
42
+ "@agledger/sdk": "0.5.1",
42
43
  "@modelcontextprotocol/sdk": "^1.29.0",
43
44
  "zod": "^4.3.6"
44
45
  },
package/src/api-client.ts CHANGED
@@ -36,7 +36,7 @@ export class ApiClient {
36
36
  const headers: Record<string, string> = {
37
37
  Authorization: `Bearer ${this.apiKey}`,
38
38
  Accept: 'application/json',
39
- 'User-Agent': 'agledger-mcp-server/2.0.2',
39
+ 'User-Agent': 'agledger-mcp-server/2.1.0',
40
40
  };
41
41
 
42
42
  if (options?.body !== undefined) {
package/src/index.ts CHANGED
@@ -25,7 +25,7 @@ function main(): void {
25
25
 
26
26
  if (values.help) {
27
27
  process.stderr.write(
28
- `AGLedger MCP Server v2.0.2
28
+ `AGLedger MCP Server v2.1.0
29
29
 
30
30
  Usage: agledger-mcp --api-key <key> [--api-url <url>]
31
31
 
package/src/server.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  import { z } from 'zod';
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
4
+ import { verifyExport } from '@agledger/sdk/verify';
5
+ import type { MandateAuditExport } from '@agledger/sdk/types';
4
6
  import { ApiClient } from './api-client.js';
5
7
 
6
8
  export interface AgledgerMcpServerOptions {
7
9
  apiKey: string;
8
10
  apiUrl?: string;
11
+ /** Request timeout in milliseconds. Default 30000. */
12
+ timeoutMs?: number;
9
13
  }
10
14
 
11
15
  const QUICKSTART = {
@@ -19,43 +23,27 @@ const QUICKSTART = {
19
23
  } as const;
20
24
 
21
25
  const DOCS = {
22
- quickReference: '/llms-agent.txt',
23
- fullReference: '/llms.txt',
26
+ description:
27
+ 'Every API response includes nextSteps for self-guided workflow discovery. ' +
28
+ 'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog.',
29
+ openapi: '/openapi.json',
30
+ openapiResource: 'agledger://openapi',
24
31
  } as const;
25
32
 
26
- function errorResult(message: string): CallToolResult {
27
- return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
28
- }
29
-
30
- function recoveryHint(status: number, method: string, path: string): string {
31
- if (status === 400) {
32
- return `Check required fields. Call GET /v1/schemas to see valid contract types, or GET /v1/schemas/{type} for the exact schema.`;
33
- }
34
- if (status === 401) {
35
- return 'API key is invalid or expired. Call agledger_discover to verify your identity.';
36
- }
37
- if (status === 403) {
38
- return 'Your API key lacks the required scope. Check the missingScopes field above.';
39
- }
40
- if (status === 404) {
41
- if (path.includes('/mandates/') && method === 'POST' && path.includes('/receipts')) {
42
- return 'Mandate not found. Call GET /v1/mandates to list your mandates and verify the ID.';
43
- }
44
- return `Resource not found at ${path}. All routes start with /v1/. Call GET /llms-agent.txt for the full API reference.`;
45
- }
46
- if (status === 409) {
47
- return 'Conflict — the resource state does not allow this action. Check the mandate status with GET /v1/mandates/{id}.';
48
- }
49
- if (status === 422) {
50
- return 'Validation failed. Check the validationErrors field above for specific field issues. Call GET /v1/schemas/{type} for the expected format.';
51
- }
52
- if (status === 429) {
53
- return 'Rate limited. Wait a moment, then retry the same request.';
54
- }
55
- if (status >= 500) {
56
- return 'Server error. Retry the same request. If it persists, try GET /health to check API status.';
57
- }
58
- return `Unexpected status ${status}. Try GET /health to verify API status.`;
33
+ /**
34
+ * Structured error for CLI-origin failures (network, timeout, malformed input).
35
+ * API-origin errors are forwarded verbatim without enrichment — if the API
36
+ * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
37
+ */
38
+ function errorResult(message: string, code?: string, suggestion?: string): CallToolResult {
39
+ const structuredContent: Record<string, unknown> = { error: true, message };
40
+ if (code) structuredContent.code = code;
41
+ if (suggestion) structuredContent.suggestion = suggestion;
42
+ return {
43
+ content: [{ type: 'text', text: `Error: ${message}` }],
44
+ structuredContent,
45
+ isError: true,
46
+ };
59
47
  }
60
48
 
61
49
  export class AgledgerMcpServer {
@@ -65,14 +53,15 @@ export class AgledgerMcpServer {
65
53
  constructor(options: AgledgerMcpServerOptions) {
66
54
  const apiUrl = options.apiUrl ?? 'https://agledger.example.com';
67
55
 
68
- this.client = new ApiClient(apiUrl, options.apiKey);
56
+ this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
69
57
 
70
58
  this.mcp = new McpServer(
71
- { name: 'agledger-mcp-server', version: '2.0.2' },
72
- { capabilities: { tools: {} } },
59
+ { name: 'agledger-mcp-server', version: '2.1.1' },
60
+ { capabilities: { tools: {}, resources: {} } },
73
61
  );
74
62
 
75
63
  this.registerTools();
64
+ this.registerResources();
76
65
  }
77
66
 
78
67
  private registerTools(): void {
@@ -126,7 +115,7 @@ export class AgledgerMcpServer {
126
115
 
127
116
  return { content: [], structuredContent: result };
128
117
  } catch (err) {
129
- return errorResult(err instanceof Error ? err.message : String(err));
118
+ return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
130
119
  }
131
120
  },
132
121
  );
@@ -143,7 +132,7 @@ export class AgledgerMcpServer {
143
132
  '3. POST /v1/mandates — create a mandate. ' +
144
133
  '4. POST /v1/mandates/{id}/receipts — submit evidence when done. ' +
145
134
  'If a call fails, read the suggestion field in the error response. ' +
146
- 'For full API docs: GET /llms-agent.txt. ' +
135
+ 'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource). ' +
147
136
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
148
137
  inputSchema: {
149
138
  method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
@@ -170,8 +159,10 @@ export class AgledgerMcpServer {
170
159
 
171
160
  if (!path.startsWith('/')) {
172
161
  return errorResult(
173
- 'PATH_INVALID: Path must start with /. All API routes use /v1/ prefix. ' +
162
+ 'Path must start with /. All API routes use /v1/ prefix. ' +
174
163
  'Example: /v1/mandates, /v1/schemas. Call agledger_discover for the full workflow.',
164
+ 'PATH_INVALID',
165
+ 'Prefix the path with /v1/ (e.g. /v1/mandates). Call agledger_discover if unsure which path to use.',
175
166
  );
176
167
  }
177
168
 
@@ -194,15 +185,13 @@ export class AgledgerMcpServer {
194
185
  };
195
186
  }
196
187
 
188
+ // Forward the API error body verbatim. The API owns error guidance;
189
+ // the MCP does not enrich, translate, or inject suggestions.
197
190
  const errorBody = (response.body ?? {}) as Record<string, unknown>;
198
191
  const message = (errorBody.message ??
199
192
  errorBody.error ??
200
193
  `API returned ${response.status}`) as string;
201
194
 
202
- if (!errorBody.suggestion) {
203
- errorBody.suggestion = recoveryHint(response.status, method, path);
204
- }
205
-
206
195
  return {
207
196
  content: [{ type: 'text', text: `Error: ${message}` }],
208
197
  structuredContent: errorBody,
@@ -211,18 +200,122 @@ export class AgledgerMcpServer {
211
200
  } catch (err) {
212
201
  if (err instanceof DOMException && err.name === 'AbortError') {
213
202
  return errorResult(
214
- 'TIMEOUT: The API did not respond within 30 seconds. ' +
215
- 'Retry the same request. If it fails again, try GET /health to check API status.',
203
+ 'The API did not respond in time. Retry the same request.',
204
+ 'TIMEOUT',
205
+ 'Retry the same request. Increase --timeout if your instance is slow to respond.',
216
206
  );
217
207
  }
218
208
  if (err instanceof TypeError && err.message.includes('fetch')) {
219
209
  return errorResult(
220
- `NETWORK_ERROR: ${err.message}. ` +
221
- 'Check that the API URL is correct. Try GET /health to verify connectivity.',
210
+ err.message,
211
+ 'NETWORK_ERROR',
212
+ 'Check that the API URL is correct. Try GET /health to verify connectivity.',
213
+ );
214
+ }
215
+ return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
216
+ }
217
+ },
218
+ );
219
+
220
+ this.mcp.registerTool(
221
+ 'agledger_verify',
222
+ {
223
+ title: 'Verify Audit Export',
224
+ description:
225
+ 'Verify an AGLedger audit export offline. Recomputes RFC 8785 canonical hashes, ' +
226
+ 'walks the hash chain, and verifies every Ed25519 signature. ' +
227
+ 'No network calls — trust is rooted in the export\'s embedded signing keys (and/or ' +
228
+ 'the publicKeys override). On failure, brokenAt pinpoints the first entry that failed ' +
229
+ 'and why (payload_hash_mismatch, chain_break, signature_invalid, unknown_key, ' +
230
+ 'position_gap, malformed_entry, unsupported_algorithm). ' +
231
+ 'Obtain the export via agledger_api with method=GET, path=/v1/mandates/{id}/audit-export.',
232
+ inputSchema: {
233
+ export: z
234
+ .record(z.string(), z.unknown())
235
+ .describe(
236
+ 'The parsed audit export JSON (the response body from GET /v1/mandates/{id}/audit-export).',
237
+ ),
238
+ publicKeys: z
239
+ .record(z.string(), z.string())
240
+ .optional()
241
+ .describe(
242
+ 'Optional map of signingKeyId → SPKI DER base64 public key. Merged over any keys ' +
243
+ 'embedded in the export. Use this to verify against an independently-trusted key set.',
244
+ ),
245
+ requireKeyId: z
246
+ .string()
247
+ .optional()
248
+ .describe(
249
+ 'If set, every entry must reference this keyId. Rejects exports signed by a ' +
250
+ 'retired or unexpected key even if cryptographically valid.',
251
+ ),
252
+ },
253
+ annotations: {
254
+ readOnlyHint: true,
255
+ destructiveHint: false,
256
+ idempotentHint: true,
257
+ openWorldHint: false,
258
+ },
259
+ },
260
+ async (args) => {
261
+ try {
262
+ const { export: exportData, publicKeys, requireKeyId } = args;
263
+ if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
264
+ return errorResult(
265
+ 'Input is not a valid audit export. Expected an object with exportMetadata and entries.',
266
+ 'INVALID_EXPORT',
267
+ 'Call agledger_api with method=GET and path=/v1/mandates/{id}/audit-export, then pass the response body as the `export` argument.',
222
268
  );
223
269
  }
224
- return errorResult(err instanceof Error ? err.message : String(err));
270
+
271
+ const result = verifyExport(exportData as unknown as MandateAuditExport, {
272
+ publicKeys,
273
+ requireKeyId,
274
+ });
275
+
276
+ return {
277
+ content: [],
278
+ structuredContent: result as unknown as Record<string, unknown>,
279
+ isError: !result.valid,
280
+ };
281
+ } catch (err) {
282
+ return errorResult(err instanceof Error ? err.message : String(err), 'VERIFY_FAILED');
283
+ }
284
+ },
285
+ );
286
+ }
287
+
288
+ private registerResources(): void {
289
+ const client = this.client;
290
+
291
+ /**
292
+ * Proxies GET /openapi.json at read time. Keeps the spec fresh — no local
293
+ * cache that could go stale. Clients (Claude Desktop, etc.) surface this
294
+ * in their resource picker, so users/agents can pull the spec into context
295
+ * without constructing an `agledger_api` call.
296
+ */
297
+ this.mcp.registerResource(
298
+ 'agledger-openapi',
299
+ 'agledger://openapi',
300
+ {
301
+ description:
302
+ 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json — always current with the running API instance.',
303
+ mimeType: 'application/json',
304
+ },
305
+ async () => {
306
+ const response = await client.request('GET', '/openapi.json');
307
+ if (!response.ok) {
308
+ throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
225
309
  }
310
+ return {
311
+ contents: [
312
+ {
313
+ uri: 'agledger://openapi',
314
+ mimeType: 'application/json',
315
+ text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
316
+ },
317
+ ],
318
+ };
226
319
  },
227
320
  );
228
321
  }
@@ -1,7 +1,14 @@
1
1
  import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
2
5
  import type { Tool } from '@modelcontextprotocol/sdk/types.js';
3
6
  import { createTestHarness, type TestHarness } from './harness.js';
4
7
 
8
+ const HERE = dirname(fileURLToPath(import.meta.url));
9
+ const VECTORS_DIR = join(HERE, '..', '..', '..', 'testdata', 'verifier');
10
+ const loadVector = (name: string) => JSON.parse(readFileSync(join(VECTORS_DIR, name), 'utf8'));
11
+
5
12
  let harness: TestHarness;
6
13
  let tools: Tool[];
7
14
 
@@ -19,8 +26,8 @@ afterEach(() => {
19
26
  });
20
27
 
21
28
  describe('tool registration', () => {
22
- it('registers exactly 2 tools', () => {
23
- expect(tools).toHaveLength(2);
29
+ it('registers exactly 3 tools', () => {
30
+ expect(tools).toHaveLength(3);
24
31
  });
25
32
 
26
33
  it('registers agledger_discover', () => {
@@ -39,6 +46,60 @@ describe('tool registration', () => {
39
46
  expect(tool!.description).toContain('/v1/schemas');
40
47
  expect(tool!.description).toContain('/v1/mandates');
41
48
  });
49
+
50
+ it('registers agledger_verify', () => {
51
+ const tool = tools.find((t) => t.name === 'agledger_verify');
52
+ expect(tool).toBeDefined();
53
+ expect(tool!.description).toContain('offline');
54
+ expect(tool!.description).toContain('Ed25519');
55
+ expect(tool!.description).toContain('audit-export');
56
+ });
57
+ });
58
+
59
+ describe('resource registration', () => {
60
+ it('registers the agledger://openapi resource', async () => {
61
+ const { resources } = await harness.client.listResources();
62
+ const openapi = resources.find((r) => r.uri === 'agledger://openapi');
63
+ expect(openapi).toBeDefined();
64
+ expect(openapi!.mimeType).toBe('application/json');
65
+ expect(openapi!.description).toContain('OpenAPI');
66
+ });
67
+
68
+ it('reads the openapi resource by proxying to GET /openapi.json', async () => {
69
+ const spec = { openapi: '3.0.3', info: { title: 'AGLedger API' }, paths: {} };
70
+ const mockFetch = vi.fn().mockResolvedValueOnce(
71
+ new Response(JSON.stringify(spec), {
72
+ status: 200,
73
+ headers: { 'content-type': 'application/json' },
74
+ }),
75
+ );
76
+ vi.stubGlobal('fetch', mockFetch);
77
+
78
+ const result = await harness.client.readResource({ uri: 'agledger://openapi' });
79
+ expect(result.contents).toHaveLength(1);
80
+ const content = result.contents[0];
81
+ expect(content.uri).toBe('agledger://openapi');
82
+ expect(content.mimeType).toBe('application/json');
83
+ expect(JSON.parse(content.text as string)).toEqual(spec);
84
+
85
+ // Confirm the proxy hit the right endpoint
86
+ const url = mockFetch.mock.calls[0][0] as string;
87
+ expect(url).toContain('/openapi.json');
88
+ });
89
+
90
+ it('surfaces upstream failure when /openapi.json is not reachable', async () => {
91
+ vi.stubGlobal(
92
+ 'fetch',
93
+ vi.fn().mockResolvedValueOnce(
94
+ new Response('not found', {
95
+ status: 404,
96
+ headers: { 'content-type': 'text/plain' },
97
+ }),
98
+ ),
99
+ );
100
+
101
+ await expect(harness.client.readResource({ uri: 'agledger://openapi' })).rejects.toThrow();
102
+ });
42
103
  });
43
104
 
44
105
  describe('agledger_discover', () => {
@@ -72,10 +133,11 @@ describe('agledger_discover', () => {
72
133
  expect(quickstart.steps[0].path).toBe('/v1/schemas');
73
134
  expect(quickstart.steps[2].path).toBe('/v1/mandates');
74
135
 
75
- // Docs links are always present
76
- const docs = content.docs as { quickReference: string; fullReference: string };
77
- expect(docs.quickReference).toBe('/llms-agent.txt');
78
- expect(docs.fullReference).toBe('/llms.txt');
136
+ // Docs hints always present — point at live API discovery and the openapi resource.
137
+ const docs = content.docs as { openapi: string; openapiResource: string; description: string };
138
+ expect(docs.openapi).toBe('/openapi.json');
139
+ expect(docs.openapiResource).toBe('agledger://openapi');
140
+ expect(docs.description).toContain('nextSteps');
79
141
  });
80
142
 
81
143
  it('returns partial results when one call fails', async () => {
@@ -156,7 +218,7 @@ describe('agledger_api', () => {
156
218
  const errorBody = {
157
219
  message: 'Mandate not found',
158
220
  code: 'NOT_FOUND',
159
- docUrl: 'https://docs.agledger.ai/errors/NOT_FOUND',
221
+ docUrl: 'https://www.agledger.ai/docs/errors/NOT_FOUND',
160
222
  suggestion: 'Check the mandate ID and try again.',
161
223
  };
162
224
  vi.stubGlobal(
@@ -176,7 +238,7 @@ describe('agledger_api', () => {
176
238
 
177
239
  expect(result.isError).toBe(true);
178
240
  const content = result.structuredContent as Record<string, unknown>;
179
- expect(content.docUrl).toBe('https://docs.agledger.ai/errors/NOT_FOUND');
241
+ expect(content.docUrl).toBe('https://www.agledger.ai/docs/errors/NOT_FOUND');
180
242
  expect(content.suggestion).toBe('Check the mandate ID and try again.');
181
243
  });
182
244
 
@@ -214,13 +276,17 @@ describe('agledger_api', () => {
214
276
  });
215
277
 
216
278
  expect(result.isError).toBe(true);
279
+ const content = result.structuredContent as Record<string, unknown>;
280
+ expect(content.code).toBe('PATH_INVALID');
217
281
  const text = (result.content as Array<{ type: string; text: string }>)[0].text;
218
- expect(text).toContain('PATH_INVALID');
219
282
  expect(text).toContain('/v1/');
220
283
  expect(text).toContain('agledger_discover');
284
+ expect(content.suggestion).toBeDefined();
221
285
  });
222
286
 
223
- it('enriches API errors with recovery hint when suggestion is missing', async () => {
287
+ it('forwards API error body verbatim when suggestion is missing (no MCP-side enrichment)', async () => {
288
+ // Thin-passthrough contract: the API owns error guidance. The MCP must not
289
+ // inject a suggestion or any other field the API didn't return.
224
290
  const errorBody = {
225
291
  message: 'Invalid contract type',
226
292
  code: 'BAD_REQUEST',
@@ -242,7 +308,8 @@ describe('agledger_api', () => {
242
308
 
243
309
  expect(result.isError).toBe(true);
244
310
  const content = result.structuredContent as Record<string, unknown>;
245
- expect(content.suggestion).toContain('/v1/schemas');
311
+ expect(content).toEqual(errorBody); // exact match — no added fields
312
+ expect(content.suggestion).toBeUndefined();
246
313
  });
247
314
 
248
315
  it('preserves existing API suggestion without overwriting', async () => {
@@ -283,9 +350,9 @@ describe('agledger_api', () => {
283
350
  });
284
351
 
285
352
  expect(result.isError).toBe(true);
286
- const text = (result.content as Array<{ type: string; text: string }>)[0].text;
287
- expect(text).toContain('NETWORK_ERROR');
288
- expect(text).toContain('/health');
353
+ const content = result.structuredContent as Record<string, unknown>;
354
+ expect(content.code).toBe('NETWORK_ERROR');
355
+ expect(content.suggestion).toContain('/health');
289
356
  });
290
357
 
291
358
  it('handles timeout with recovery directive', async () => {
@@ -304,9 +371,9 @@ describe('agledger_api', () => {
304
371
  });
305
372
 
306
373
  expect(result.isError).toBe(true);
307
- const text = (result.content as Array<{ type: string; text: string }>)[0].text;
308
- expect(text).toContain('TIMEOUT');
309
- expect(text).toContain('Retry');
374
+ const content = result.structuredContent as Record<string, unknown>;
375
+ expect(content.code).toBe('TIMEOUT');
376
+ expect(content.suggestion).toContain('Retry');
310
377
  });
311
378
 
312
379
  it('handles non-JSON responses', async () => {
@@ -354,3 +421,80 @@ describe('agledger_api', () => {
354
421
  expect(url.searchParams.get('limit')).toBe('20');
355
422
  });
356
423
  });
424
+
425
+ describe('agledger_verify', () => {
426
+ it('verifies a valid audit export offline', async () => {
427
+ const result = await harness.client.callTool({
428
+ name: 'agledger_verify',
429
+ arguments: { export: loadVector('valid-export.json') },
430
+ });
431
+
432
+ expect(result.isError).toBeFalsy();
433
+ const content = result.structuredContent as Record<string, unknown>;
434
+ expect(content.valid).toBe(true);
435
+ expect(content.verifiedEntries).toBe(3);
436
+ expect(content.totalEntries).toBe(3);
437
+ });
438
+
439
+ it('returns brokenAt for tampered payload', async () => {
440
+ const result = await harness.client.callTool({
441
+ name: 'agledger_verify',
442
+ arguments: { export: loadVector('tampered-payload.json') },
443
+ });
444
+
445
+ expect(result.isError).toBe(true);
446
+ const content = result.structuredContent as Record<string, unknown>;
447
+ expect(content.valid).toBe(false);
448
+ expect((content.brokenAt as Record<string, unknown>).position).toBe(2);
449
+ expect((content.brokenAt as Record<string, unknown>).reason).toBe('payload_hash_mismatch');
450
+ });
451
+
452
+ it('returns brokenAt for broken chain', async () => {
453
+ const result = await harness.client.callTool({
454
+ name: 'agledger_verify',
455
+ arguments: { export: loadVector('broken-chain.json') },
456
+ });
457
+
458
+ expect(result.isError).toBe(true);
459
+ const content = result.structuredContent as Record<string, unknown>;
460
+ expect((content.brokenAt as Record<string, unknown>).reason).toBe('chain_break');
461
+ });
462
+
463
+ it('makes no API calls (fully offline)', async () => {
464
+ const mockFetch = vi.fn();
465
+ vi.stubGlobal('fetch', mockFetch);
466
+
467
+ await harness.client.callTool({
468
+ name: 'agledger_verify',
469
+ arguments: { export: loadVector('valid-export.json') },
470
+ });
471
+
472
+ expect(mockFetch).not.toHaveBeenCalled();
473
+ });
474
+
475
+ it('accepts publicKeys override', async () => {
476
+ const keys = loadVector('public-keys.json');
477
+ const result = await harness.client.callTool({
478
+ name: 'agledger_verify',
479
+ arguments: {
480
+ export: loadVector('valid-export.json'),
481
+ publicKeys: keys,
482
+ },
483
+ });
484
+
485
+ expect(result.isError).toBeFalsy();
486
+ expect((result.structuredContent as Record<string, unknown>).valid).toBe(true);
487
+ });
488
+
489
+ it('rejects malformed export input', async () => {
490
+ const result = await harness.client.callTool({
491
+ name: 'agledger_verify',
492
+ arguments: { export: { notAnExport: true } },
493
+ });
494
+
495
+ expect(result.isError).toBe(true);
496
+ const content = result.structuredContent as Record<string, unknown>;
497
+ expect(content.code).toBe('INVALID_EXPORT');
498
+ expect(content.suggestion).toContain('audit-export');
499
+ });
500
+ });