@agledger/mcp-server 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,12 +65,14 @@ AGLedger is the accountability layer for automated operations. It records what w
65
65
  - **Verdicts** -- principal acceptance decisions (PASS/FAIL) with settlement signals
66
66
  - **Audit trail** -- hash-chained, Ed25519-signed, tamper-evident record
67
67
 
68
- Learn more at [agledger.ai](https://agledger.ai) | [API docs](https://docs.agledger.ai)
68
+ Learn more at [agledger.ai](https://www.agledger.ai) | [API docs](https://www.agledger.ai/docs/)
69
+
70
+ Each self-hosted AGLedger instance also serves interactive Swagger UI at `{AGLEDGER_API_URL}/docs`.
69
71
 
70
72
  ## Requirements
71
73
 
72
74
  - Node.js >= 22
73
- - An AGLedger API key ([sign up](https://agledger.ai))
75
+ - 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
76
 
75
77
  ## License
76
78
 
@@ -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;AAEpE,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;IA0JrB,OAAO,CAAC,iBAAiB;CAkC1B"}
package/dist/server.js CHANGED
@@ -11,50 +11,37 @@ const QUICKSTART = {
11
11
  ],
12
12
  };
13
13
  const DOCS = {
14
- quickReference: '/llms-agent.txt',
15
- fullReference: '/llms.txt',
14
+ description: 'Every API response includes nextSteps for self-guided workflow discovery. ' +
15
+ 'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog.',
16
+ openapi: '/openapi.json',
17
+ openapiResource: 'agledger://openapi',
16
18
  };
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.`;
19
+ /**
20
+ * Structured error for CLI-origin failures (network, timeout, malformed input).
21
+ * API-origin errors are forwarded verbatim without enrichment — if the API
22
+ * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
23
+ */
24
+ function errorResult(message, code, suggestion) {
25
+ const structuredContent = { error: true, message };
26
+ if (code)
27
+ structuredContent.code = code;
28
+ if (suggestion)
29
+ structuredContent.suggestion = suggestion;
30
+ return {
31
+ content: [{ type: 'text', text: `Error: ${message}` }],
32
+ structuredContent,
33
+ isError: true,
34
+ };
49
35
  }
50
36
  export class AgledgerMcpServer {
51
37
  mcp;
52
38
  client;
53
39
  constructor(options) {
54
40
  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: {} } });
41
+ this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
42
+ this.mcp = new McpServer({ name: 'agledger-mcp-server', version: '2.1.0' }, { capabilities: { tools: {}, resources: {} } });
57
43
  this.registerTools();
44
+ this.registerResources();
58
45
  }
59
46
  registerTools() {
60
47
  const client = this.client;
@@ -99,7 +86,7 @@ export class AgledgerMcpServer {
99
86
  return { content: [], structuredContent: result };
100
87
  }
101
88
  catch (err) {
102
- return errorResult(err instanceof Error ? err.message : String(err));
89
+ return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
103
90
  }
104
91
  });
105
92
  this.mcp.registerTool('agledger_api', {
@@ -111,7 +98,7 @@ export class AgledgerMcpServer {
111
98
  '3. POST /v1/mandates — create a mandate. ' +
112
99
  '4. POST /v1/mandates/{id}/receipts — submit evidence when done. ' +
113
100
  'If a call fails, read the suggestion field in the error response. ' +
114
- 'For full API docs: GET /llms-agent.txt. ' +
101
+ 'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource). ' +
115
102
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
116
103
  inputSchema: {
117
104
  method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
@@ -133,8 +120,8 @@ export class AgledgerMcpServer {
133
120
  try {
134
121
  const { method, path, params } = args;
135
122
  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.');
123
+ return errorResult('Path must start with /. All API routes use /v1/ prefix. ' +
124
+ '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
125
  }
139
126
  const options = {};
140
127
  if (params) {
@@ -152,13 +139,12 @@ export class AgledgerMcpServer {
152
139
  structuredContent: response.body,
153
140
  };
154
141
  }
142
+ // Forward the API error body verbatim. The API owns error guidance;
143
+ // the MCP does not enrich, translate, or inject suggestions.
155
144
  const errorBody = (response.body ?? {});
156
145
  const message = (errorBody.message ??
157
146
  errorBody.error ??
158
147
  `API returned ${response.status}`);
159
- if (!errorBody.suggestion) {
160
- errorBody.suggestion = recoveryHint(response.status, method, path);
161
- }
162
148
  return {
163
149
  content: [{ type: 'text', text: `Error: ${message}` }],
164
150
  structuredContent: errorBody,
@@ -167,15 +153,40 @@ export class AgledgerMcpServer {
167
153
  }
168
154
  catch (err) {
169
155
  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.');
156
+ 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
157
  }
173
158
  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.');
159
+ return errorResult(err.message, 'NETWORK_ERROR', 'Check that the API URL is correct. Try GET /health to verify connectivity.');
176
160
  }
177
- return errorResult(err instanceof Error ? err.message : String(err));
161
+ return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
162
+ }
163
+ });
164
+ }
165
+ registerResources() {
166
+ const client = this.client;
167
+ /**
168
+ * Proxies GET /openapi.json at read time. Keeps the spec fresh — no local
169
+ * cache that could go stale. Clients (Claude Desktop, etc.) surface this
170
+ * in their resource picker, so users/agents can pull the spec into context
171
+ * without constructing an `agledger_api` call.
172
+ */
173
+ this.mcp.registerResource('agledger-openapi', 'agledger://openapi', {
174
+ description: 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json — always current with the running API instance.',
175
+ mimeType: 'application/json',
176
+ }, async () => {
177
+ const response = await client.request('GET', '/openapi.json');
178
+ if (!response.ok) {
179
+ throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
178
180
  }
181
+ return {
182
+ contents: [
183
+ {
184
+ uri: 'agledger://openapi',
185
+ mimeType: 'application/json',
186
+ text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
187
+ },
188
+ ],
189
+ };
179
190
  });
180
191
  }
181
192
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAEpE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAO5C,MAAM,UAAU,GAAG;IACjB,WAAW,EAAE,qEAAqE;IAClF,KAAK,EAAE;QACL,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,+BAA+B,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE;QACxF,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,mCAAmC,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,4BAA4B,EAAE;QAC3G,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE;QAC7E,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,qCAAqC,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,4BAA4B,EAAE;KAC/G;CACO,CAAC;AAEX,MAAM,IAAI,GAAG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C,GAAG,CAAC,gBAAgB,CACvB,kBAAkB,EAClB,oBAAoB,EACpB;YACE,WAAW,EACT,iIAAiI;YACnI,QAAQ,EAAE,kBAAkB;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.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",
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
@@ -6,6 +6,8 @@ import { ApiClient } from './api-client.js';
6
6
  export interface AgledgerMcpServerOptions {
7
7
  apiKey: string;
8
8
  apiUrl?: string;
9
+ /** Request timeout in milliseconds. Default 30000. */
10
+ timeoutMs?: number;
9
11
  }
10
12
 
11
13
  const QUICKSTART = {
@@ -19,43 +21,27 @@ const QUICKSTART = {
19
21
  } as const;
20
22
 
21
23
  const DOCS = {
22
- quickReference: '/llms-agent.txt',
23
- fullReference: '/llms.txt',
24
+ description:
25
+ 'Every API response includes nextSteps for self-guided workflow discovery. ' +
26
+ 'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog.',
27
+ openapi: '/openapi.json',
28
+ openapiResource: 'agledger://openapi',
24
29
  } as const;
25
30
 
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.`;
31
+ /**
32
+ * Structured error for CLI-origin failures (network, timeout, malformed input).
33
+ * API-origin errors are forwarded verbatim without enrichment — if the API
34
+ * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
35
+ */
36
+ function errorResult(message: string, code?: string, suggestion?: string): CallToolResult {
37
+ const structuredContent: Record<string, unknown> = { error: true, message };
38
+ if (code) structuredContent.code = code;
39
+ if (suggestion) structuredContent.suggestion = suggestion;
40
+ return {
41
+ content: [{ type: 'text', text: `Error: ${message}` }],
42
+ structuredContent,
43
+ isError: true,
44
+ };
59
45
  }
60
46
 
61
47
  export class AgledgerMcpServer {
@@ -65,14 +51,15 @@ export class AgledgerMcpServer {
65
51
  constructor(options: AgledgerMcpServerOptions) {
66
52
  const apiUrl = options.apiUrl ?? 'https://agledger.example.com';
67
53
 
68
- this.client = new ApiClient(apiUrl, options.apiKey);
54
+ this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
69
55
 
70
56
  this.mcp = new McpServer(
71
- { name: 'agledger-mcp-server', version: '2.0.2' },
72
- { capabilities: { tools: {} } },
57
+ { name: 'agledger-mcp-server', version: '2.1.0' },
58
+ { capabilities: { tools: {}, resources: {} } },
73
59
  );
74
60
 
75
61
  this.registerTools();
62
+ this.registerResources();
76
63
  }
77
64
 
78
65
  private registerTools(): void {
@@ -126,7 +113,7 @@ export class AgledgerMcpServer {
126
113
 
127
114
  return { content: [], structuredContent: result };
128
115
  } catch (err) {
129
- return errorResult(err instanceof Error ? err.message : String(err));
116
+ return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
130
117
  }
131
118
  },
132
119
  );
@@ -143,7 +130,7 @@ export class AgledgerMcpServer {
143
130
  '3. POST /v1/mandates — create a mandate. ' +
144
131
  '4. POST /v1/mandates/{id}/receipts — submit evidence when done. ' +
145
132
  'If a call fails, read the suggestion field in the error response. ' +
146
- 'For full API docs: GET /llms-agent.txt. ' +
133
+ 'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource). ' +
147
134
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
148
135
  inputSchema: {
149
136
  method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
@@ -170,8 +157,10 @@ export class AgledgerMcpServer {
170
157
 
171
158
  if (!path.startsWith('/')) {
172
159
  return errorResult(
173
- 'PATH_INVALID: Path must start with /. All API routes use /v1/ prefix. ' +
160
+ 'Path must start with /. All API routes use /v1/ prefix. ' +
174
161
  'Example: /v1/mandates, /v1/schemas. Call agledger_discover for the full workflow.',
162
+ 'PATH_INVALID',
163
+ 'Prefix the path with /v1/ (e.g. /v1/mandates). Call agledger_discover if unsure which path to use.',
175
164
  );
176
165
  }
177
166
 
@@ -194,15 +183,13 @@ export class AgledgerMcpServer {
194
183
  };
195
184
  }
196
185
 
186
+ // Forward the API error body verbatim. The API owns error guidance;
187
+ // the MCP does not enrich, translate, or inject suggestions.
197
188
  const errorBody = (response.body ?? {}) as Record<string, unknown>;
198
189
  const message = (errorBody.message ??
199
190
  errorBody.error ??
200
191
  `API returned ${response.status}`) as string;
201
192
 
202
- if (!errorBody.suggestion) {
203
- errorBody.suggestion = recoveryHint(response.status, method, path);
204
- }
205
-
206
193
  return {
207
194
  content: [{ type: 'text', text: `Error: ${message}` }],
208
195
  structuredContent: errorBody,
@@ -211,18 +198,55 @@ export class AgledgerMcpServer {
211
198
  } catch (err) {
212
199
  if (err instanceof DOMException && err.name === 'AbortError') {
213
200
  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.',
201
+ 'The API did not respond in time. Retry the same request.',
202
+ 'TIMEOUT',
203
+ 'Retry the same request. Increase --timeout if your instance is slow to respond.',
216
204
  );
217
205
  }
218
206
  if (err instanceof TypeError && err.message.includes('fetch')) {
219
207
  return errorResult(
220
- `NETWORK_ERROR: ${err.message}. ` +
221
- 'Check that the API URL is correct. Try GET /health to verify connectivity.',
208
+ err.message,
209
+ 'NETWORK_ERROR',
210
+ 'Check that the API URL is correct. Try GET /health to verify connectivity.',
222
211
  );
223
212
  }
224
- return errorResult(err instanceof Error ? err.message : String(err));
213
+ return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
214
+ }
215
+ },
216
+ );
217
+ }
218
+
219
+ private registerResources(): void {
220
+ const client = this.client;
221
+
222
+ /**
223
+ * Proxies GET /openapi.json at read time. Keeps the spec fresh — no local
224
+ * cache that could go stale. Clients (Claude Desktop, etc.) surface this
225
+ * in their resource picker, so users/agents can pull the spec into context
226
+ * without constructing an `agledger_api` call.
227
+ */
228
+ this.mcp.registerResource(
229
+ 'agledger-openapi',
230
+ 'agledger://openapi',
231
+ {
232
+ description:
233
+ 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json — always current with the running API instance.',
234
+ mimeType: 'application/json',
235
+ },
236
+ async () => {
237
+ const response = await client.request('GET', '/openapi.json');
238
+ if (!response.ok) {
239
+ throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
225
240
  }
241
+ return {
242
+ contents: [
243
+ {
244
+ uri: 'agledger://openapi',
245
+ mimeType: 'application/json',
246
+ text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
247
+ },
248
+ ],
249
+ };
226
250
  },
227
251
  );
228
252
  }
@@ -41,6 +41,52 @@ describe('tool registration', () => {
41
41
  });
42
42
  });
43
43
 
44
+ describe('resource registration', () => {
45
+ it('registers the agledger://openapi resource', async () => {
46
+ const { resources } = await harness.client.listResources();
47
+ const openapi = resources.find((r) => r.uri === 'agledger://openapi');
48
+ expect(openapi).toBeDefined();
49
+ expect(openapi!.mimeType).toBe('application/json');
50
+ expect(openapi!.description).toContain('OpenAPI');
51
+ });
52
+
53
+ it('reads the openapi resource by proxying to GET /openapi.json', async () => {
54
+ const spec = { openapi: '3.0.3', info: { title: 'AGLedger API' }, paths: {} };
55
+ const mockFetch = vi.fn().mockResolvedValueOnce(
56
+ new Response(JSON.stringify(spec), {
57
+ status: 200,
58
+ headers: { 'content-type': 'application/json' },
59
+ }),
60
+ );
61
+ vi.stubGlobal('fetch', mockFetch);
62
+
63
+ const result = await harness.client.readResource({ uri: 'agledger://openapi' });
64
+ expect(result.contents).toHaveLength(1);
65
+ const content = result.contents[0];
66
+ expect(content.uri).toBe('agledger://openapi');
67
+ expect(content.mimeType).toBe('application/json');
68
+ expect(JSON.parse(content.text as string)).toEqual(spec);
69
+
70
+ // Confirm the proxy hit the right endpoint
71
+ const url = mockFetch.mock.calls[0][0] as string;
72
+ expect(url).toContain('/openapi.json');
73
+ });
74
+
75
+ it('surfaces upstream failure when /openapi.json is not reachable', async () => {
76
+ vi.stubGlobal(
77
+ 'fetch',
78
+ vi.fn().mockResolvedValueOnce(
79
+ new Response('not found', {
80
+ status: 404,
81
+ headers: { 'content-type': 'text/plain' },
82
+ }),
83
+ ),
84
+ );
85
+
86
+ await expect(harness.client.readResource({ uri: 'agledger://openapi' })).rejects.toThrow();
87
+ });
88
+ });
89
+
44
90
  describe('agledger_discover', () => {
45
91
  it('returns health and identity on success', async () => {
46
92
  const mockFetch = vi
@@ -72,10 +118,11 @@ describe('agledger_discover', () => {
72
118
  expect(quickstart.steps[0].path).toBe('/v1/schemas');
73
119
  expect(quickstart.steps[2].path).toBe('/v1/mandates');
74
120
 
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');
121
+ // Docs hints always present — point at live API discovery and the openapi resource.
122
+ const docs = content.docs as { openapi: string; openapiResource: string; description: string };
123
+ expect(docs.openapi).toBe('/openapi.json');
124
+ expect(docs.openapiResource).toBe('agledger://openapi');
125
+ expect(docs.description).toContain('nextSteps');
79
126
  });
80
127
 
81
128
  it('returns partial results when one call fails', async () => {
@@ -214,13 +261,17 @@ describe('agledger_api', () => {
214
261
  });
215
262
 
216
263
  expect(result.isError).toBe(true);
264
+ const content = result.structuredContent as Record<string, unknown>;
265
+ expect(content.code).toBe('PATH_INVALID');
217
266
  const text = (result.content as Array<{ type: string; text: string }>)[0].text;
218
- expect(text).toContain('PATH_INVALID');
219
267
  expect(text).toContain('/v1/');
220
268
  expect(text).toContain('agledger_discover');
269
+ expect(content.suggestion).toBeDefined();
221
270
  });
222
271
 
223
- it('enriches API errors with recovery hint when suggestion is missing', async () => {
272
+ it('forwards API error body verbatim when suggestion is missing (no MCP-side enrichment)', async () => {
273
+ // Thin-passthrough contract: the API owns error guidance. The MCP must not
274
+ // inject a suggestion or any other field the API didn't return.
224
275
  const errorBody = {
225
276
  message: 'Invalid contract type',
226
277
  code: 'BAD_REQUEST',
@@ -242,7 +293,8 @@ describe('agledger_api', () => {
242
293
 
243
294
  expect(result.isError).toBe(true);
244
295
  const content = result.structuredContent as Record<string, unknown>;
245
- expect(content.suggestion).toContain('/v1/schemas');
296
+ expect(content).toEqual(errorBody); // exact match — no added fields
297
+ expect(content.suggestion).toBeUndefined();
246
298
  });
247
299
 
248
300
  it('preserves existing API suggestion without overwriting', async () => {
@@ -283,9 +335,9 @@ describe('agledger_api', () => {
283
335
  });
284
336
 
285
337
  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');
338
+ const content = result.structuredContent as Record<string, unknown>;
339
+ expect(content.code).toBe('NETWORK_ERROR');
340
+ expect(content.suggestion).toContain('/health');
289
341
  });
290
342
 
291
343
  it('handles timeout with recovery directive', async () => {
@@ -304,9 +356,9 @@ describe('agledger_api', () => {
304
356
  });
305
357
 
306
358
  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');
359
+ const content = result.structuredContent as Record<string, unknown>;
360
+ expect(content.code).toBe('TIMEOUT');
361
+ expect(content.suggestion).toContain('Retry');
310
362
  });
311
363
 
312
364
  it('handles non-JSON responses', async () => {