@agledger/mcp-server 2.3.0 → 2.3.2

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/src/server.ts DELETED
@@ -1,326 +0,0 @@
1
- import { z } from 'zod';
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
4
- import { verifyExport, type RecordAuditExport } from './verify/verify-export.js';
5
- import { ApiClient } from './api-client.js';
6
-
7
- export interface AgledgerMcpServerOptions {
8
- apiKey: string;
9
- apiUrl?: string;
10
- /** Request timeout in milliseconds. Default 30000. */
11
- timeoutMs?: number;
12
- }
13
-
14
- const QUICKSTART = {
15
- description: 'To track accountability for your work, follow these steps in order:',
16
- steps: [
17
- { step: 1, action: 'List available Record types', method: 'GET', path: '/v1/schemas' },
18
- { step: 2, action: 'Get schema for your Record type', method: 'GET', path: '/v1/schemas/{type}' },
19
- { step: 3, action: 'Create a record', method: 'POST', path: '/v1/records' },
20
- { step: 4, action: 'Do your work, then submit a receipt', method: 'POST', path: '/v1/records/{id}/receipts' },
21
- ],
22
- } as const;
23
-
24
- const DOCS = {
25
- description:
26
- 'Every API response includes nextSteps for self-guided workflow discovery. ' +
27
- 'Call GET /openapi.json (also exposed as the agledger://openapi resource) for the full route catalog.',
28
- openapi: '/openapi.json',
29
- openapiResource: 'agledger://openapi',
30
- } as const;
31
-
32
- /**
33
- * Structured error for CLI-origin failures (network, timeout, malformed input).
34
- * API-origin errors are forwarded verbatim without enrichment — if the API
35
- * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
36
- */
37
- function errorResult(message: string, code?: string, suggestion?: string): CallToolResult {
38
- const structuredContent: Record<string, unknown> = { error: true, message };
39
- if (code) structuredContent.code = code;
40
- if (suggestion) structuredContent.suggestion = suggestion;
41
- return {
42
- content: [{ type: 'text', text: `Error: ${message}` }],
43
- structuredContent,
44
- isError: true,
45
- };
46
- }
47
-
48
- export class AgledgerMcpServer {
49
- readonly mcp: McpServer;
50
- readonly client: ApiClient;
51
-
52
- constructor(options: AgledgerMcpServerOptions) {
53
- const apiUrl = options.apiUrl ?? 'https://agledger.example.com';
54
-
55
- this.client = new ApiClient(apiUrl, options.apiKey, options.timeoutMs);
56
-
57
- this.mcp = new McpServer(
58
- { name: 'agledger-mcp-server', version: '2.3.0' },
59
- { capabilities: { tools: {}, resources: {} } },
60
- );
61
-
62
- this.registerTools();
63
- this.registerResources();
64
- }
65
-
66
- private registerTools(): void {
67
- const client = this.client;
68
-
69
- this.mcp.registerTool(
70
- 'agledger_discover',
71
- {
72
- title: 'Discover AGLedger API',
73
- description:
74
- 'Returns API health, your identity, available scopes, and a quickstart workflow. ' +
75
- 'Call this first. The response tells you who you are and what to do next.',
76
- inputSchema: {},
77
- annotations: {
78
- readOnlyHint: true,
79
- destructiveHint: false,
80
- idempotentHint: true,
81
- openWorldHint: true,
82
- },
83
- },
84
- async () => {
85
- try {
86
- const [health, identity, scopeProfiles] = await Promise.allSettled([
87
- client.request('GET', '/health'),
88
- client.request('GET', '/v1/auth/me'),
89
- client.request('GET', '/v1/scope-profiles'),
90
- ]);
91
-
92
- const result: Record<string, unknown> = {};
93
-
94
- if (health.status === 'fulfilled') {
95
- result.health = health.value.body;
96
- } else {
97
- result.health = {
98
- error: health.reason instanceof Error ? health.reason.message : String(health.reason),
99
- };
100
- }
101
-
102
- if (identity.status === 'fulfilled') {
103
- result.identity = identity.value.body;
104
- } else {
105
- result.identity = {
106
- error:
107
- identity.reason instanceof Error
108
- ? identity.reason.message
109
- : String(identity.reason),
110
- };
111
- }
112
-
113
- if (scopeProfiles.status === 'fulfilled') {
114
- result.scopeProfiles = scopeProfiles.value.body;
115
- }
116
-
117
- result.quickstart = QUICKSTART;
118
- result.docs = DOCS;
119
-
120
- return { content: [], structuredContent: result };
121
- } catch (err) {
122
- return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
123
- }
124
- },
125
- );
126
-
127
- this.mcp.registerTool(
128
- 'agledger_api',
129
- {
130
- title: 'AGLedger API',
131
- description:
132
- 'Make any AGLedger API call. All paths start with /v1/. ' +
133
- 'The API returns nextSteps on every response — follow them. Workflow: ' +
134
- '1. GET /v1/schemas — list Record types. ' +
135
- '2. GET /v1/schemas/{type} — get required fields and examples. ' +
136
- '3. POST /v1/records — create a record. ' +
137
- '4. POST /v1/records/{id}/receipts — submit evidence when done. ' +
138
- 'If a call fails, read the suggestion field in the error response. ' +
139
- 'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource). ' +
140
- 'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
141
- inputSchema: {
142
- method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
143
- path: z
144
- .string()
145
- .describe('API path starting with / (e.g. /v1/records, /v1/schemas, /v1/records/{id}/receipts)'),
146
- params: z
147
- .record(z.string(), z.unknown())
148
- .optional()
149
- .describe(
150
- 'Request parameters. For GET/DELETE: query params. For POST/PUT/PATCH: JSON body.',
151
- ),
152
- },
153
- annotations: {
154
- readOnlyHint: false,
155
- destructiveHint: false,
156
- idempotentHint: false,
157
- openWorldHint: true,
158
- },
159
- },
160
- async (args) => {
161
- try {
162
- const { method, path, params } = args;
163
-
164
- if (!path.startsWith('/')) {
165
- return errorResult(
166
- 'Path must start with /. All API routes use /v1/ prefix. ' +
167
- 'Example: /v1/records, /v1/schemas. Call agledger_discover for the full workflow.',
168
- 'PATH_INVALID',
169
- 'Prefix the path with /v1/ (e.g. /v1/records). Call agledger_discover if unsure which path to use.',
170
- );
171
- }
172
-
173
- const options: { query?: Record<string, unknown>; body?: unknown } = {};
174
-
175
- if (params) {
176
- if (method === 'GET' || method === 'DELETE') {
177
- options.query = params;
178
- } else {
179
- options.body = params;
180
- }
181
- }
182
-
183
- const response = await client.request(method, path, options);
184
-
185
- if (response.ok) {
186
- return {
187
- content: [],
188
- structuredContent: response.body as Record<string, unknown>,
189
- };
190
- }
191
-
192
- // Forward the API error body verbatim. The API owns error guidance;
193
- // the MCP does not enrich, translate, or inject suggestions.
194
- const errorBody = (response.body ?? {}) as Record<string, unknown>;
195
- const message = (errorBody.message ??
196
- errorBody.error ??
197
- `API returned ${response.status}`) as string;
198
-
199
- return {
200
- content: [{ type: 'text', text: `Error: ${message}` }],
201
- structuredContent: errorBody,
202
- isError: true,
203
- };
204
- } catch (err) {
205
- if (err instanceof DOMException && err.name === 'AbortError') {
206
- return errorResult(
207
- 'The API did not respond in time. Retry the same request.',
208
- 'TIMEOUT',
209
- 'Retry the same request. Increase --timeout if your instance is slow to respond.',
210
- );
211
- }
212
- if (err instanceof TypeError && err.message.includes('fetch')) {
213
- return errorResult(
214
- err.message,
215
- 'NETWORK_ERROR',
216
- 'Check that the API URL is correct. Try GET /health to verify connectivity.',
217
- );
218
- }
219
- return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
220
- }
221
- },
222
- );
223
-
224
- this.mcp.registerTool(
225
- 'agledger_verify',
226
- {
227
- title: 'Verify Audit Export',
228
- description:
229
- 'Verify an AGLedger audit export offline. Recomputes RFC 8785 canonical hashes, ' +
230
- 'walks the hash chain, and verifies every Ed25519 signature. ' +
231
- 'No network calls — trust is rooted in the export\'s embedded signing keys (and/or ' +
232
- 'the publicKeys override). On failure, brokenAt pinpoints the first entry that failed ' +
233
- 'and why (payload_hash_mismatch, chain_break, signature_invalid, unknown_key, ' +
234
- 'position_gap, malformed_entry, unsupported_algorithm). ' +
235
- 'Obtain the export via agledger_api with method=GET, path=/v1/records/{id}/audit-export.',
236
- inputSchema: {
237
- export: z
238
- .record(z.string(), z.unknown())
239
- .describe(
240
- 'The parsed audit export JSON (the response body from GET /v1/records/{id}/audit-export).',
241
- ),
242
- publicKeys: z
243
- .record(z.string(), z.string())
244
- .optional()
245
- .describe(
246
- 'Optional map of signingKeyId → SPKI DER base64 public key. Merged over any keys ' +
247
- 'embedded in the export. Use this to verify against an independently-trusted key set.',
248
- ),
249
- requireKeyId: z
250
- .string()
251
- .optional()
252
- .describe(
253
- 'If set, every entry must reference this keyId. Rejects exports signed by a ' +
254
- 'retired or unexpected key even if cryptographically valid.',
255
- ),
256
- },
257
- annotations: {
258
- readOnlyHint: true,
259
- destructiveHint: false,
260
- idempotentHint: true,
261
- openWorldHint: false,
262
- },
263
- },
264
- async (args) => {
265
- try {
266
- const { export: exportData, publicKeys, requireKeyId } = args;
267
- if (!exportData || typeof exportData !== 'object' || !('entries' in exportData)) {
268
- return errorResult(
269
- 'Input is not a valid audit export. Expected an object with exportMetadata and entries.',
270
- 'INVALID_EXPORT',
271
- 'Call agledger_api with method=GET and path=/v1/records/{id}/audit-export, then pass the response body as the `export` argument.',
272
- );
273
- }
274
-
275
- const result = verifyExport(exportData as unknown as RecordAuditExport, {
276
- publicKeys,
277
- requireKeyId,
278
- });
279
-
280
- return {
281
- content: [],
282
- structuredContent: result as unknown as Record<string, unknown>,
283
- isError: !result.valid,
284
- };
285
- } catch (err) {
286
- return errorResult(err instanceof Error ? err.message : String(err), 'VERIFY_FAILED');
287
- }
288
- },
289
- );
290
- }
291
-
292
- private registerResources(): void {
293
- const client = this.client;
294
-
295
- /**
296
- * Proxies GET /openapi.json at read time. Keeps the spec fresh — no local
297
- * cache that could go stale. Clients (Claude Desktop, etc.) surface this
298
- * in their resource picker, so users/agents can pull the spec into context
299
- * without constructing an `agledger_api` call.
300
- */
301
- this.mcp.registerResource(
302
- 'agledger-openapi',
303
- 'agledger://openapi',
304
- {
305
- description:
306
- 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json — always current with the running API instance.',
307
- mimeType: 'application/json',
308
- },
309
- async () => {
310
- const response = await client.request('GET', '/openapi.json');
311
- if (!response.ok) {
312
- throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
313
- }
314
- return {
315
- contents: [
316
- {
317
- uri: 'agledger://openapi',
318
- mimeType: 'application/json',
319
- text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
320
- },
321
- ],
322
- };
323
- },
324
- );
325
- }
326
- }
@@ -1,296 +0,0 @@
1
- import { createHash, createPublicKey, verify as cryptoVerify, type KeyObject } from 'node:crypto';
2
-
3
- /**
4
- * Offline verification of an AGLedger audit export.
5
- *
6
- * Re-implements the vault's per-entry integrity check (RFC 8785 JCS → SHA-256
7
- * → Ed25519 over `{position}:{payloadHash}:{previousHash}`) and walks the hash
8
- * chain. Makes no network calls.
9
- *
10
- * Duplicated in each shipping surface (TS SDK, CLI, MCP server) on purpose —
11
- * see feedback_mcp_no_sdk.md. The CLI/MCP are not allowed to depend on
12
- * @agledger/sdk even for offline crypto. Three independent copies in this
13
- * repo, plus an independent Python port, also serves as a cross-implementation
14
- * correctness check via the shared test vectors at testdata/verifier/.
15
- */
16
-
17
- export interface AuditExportEntry {
18
- position: number;
19
- timestamp: string;
20
- entryType: string;
21
- description: string;
22
- payload: Record<string, unknown>;
23
- integrity: {
24
- payloadHash: string;
25
- hashAlg?: string;
26
- previousHash: string | null;
27
- signature: string | null;
28
- signatureAlg?: string;
29
- signingKeyId: string | null;
30
- valid: boolean;
31
- };
32
- }
33
-
34
- export interface RecordAuditExport {
35
- exportMetadata: {
36
- recordId: string;
37
- enterpriseId: string | null;
38
- type: string;
39
- exportDate: string;
40
- totalEntries: number;
41
- chainIntegrity: boolean;
42
- exportFormatVersion: string;
43
- canonicalization: string;
44
- signingPublicKey: string | null;
45
- signingPublicKeys?: Record<string, string>;
46
- };
47
- entries: AuditExportEntry[];
48
- }
49
-
50
- export interface EntryVerificationResult {
51
- position: number;
52
- valid: boolean;
53
- reason?: EntryFailureReason;
54
- detail?: string;
55
- }
56
-
57
- export type EntryFailureReason =
58
- | 'payload_hash_mismatch'
59
- | 'chain_break'
60
- | 'position_gap'
61
- | 'signature_invalid'
62
- | 'unknown_key'
63
- | 'malformed_entry'
64
- | 'unsupported_algorithm';
65
-
66
- export interface VerifyExportResult {
67
- valid: boolean;
68
- totalEntries: number;
69
- verifiedEntries: number;
70
- brokenAt?: {
71
- position: number;
72
- reason: EntryFailureReason;
73
- detail?: string;
74
- };
75
- entries: EntryVerificationResult[];
76
- recordId: string;
77
- }
78
-
79
- export interface VerifyExportOptions {
80
- publicKeys?: Record<string, string>;
81
- requireKeyId?: string;
82
- }
83
-
84
- const RFC8785 = 'RFC8785';
85
- const SUPPORTED_HASH = new Set(['SHA-256', 'sha-256', 'sha256']);
86
- const SUPPORTED_SIG = new Set(['Ed25519', 'ed25519']);
87
-
88
- export function verifyExport(
89
- exportData: RecordAuditExport,
90
- options: VerifyExportOptions = {},
91
- ): VerifyExportResult {
92
- const meta = exportData.exportMetadata;
93
- const entries = exportData.entries ?? [];
94
- const keys = new KeyCache(resolveKeys(exportData, options));
95
- const entryResults: EntryVerificationResult[] = [];
96
- let verifiedEntries = 0;
97
- let brokenAt: VerifyExportResult['brokenAt'];
98
-
99
- if (meta.canonicalization && meta.canonicalization !== RFC8785) {
100
- const detail = `Unsupported canonicalization: ${meta.canonicalization} (only RFC8785 supported)`;
101
- const result: EntryVerificationResult = {
102
- position: 0,
103
- valid: false,
104
- reason: 'unsupported_algorithm',
105
- detail,
106
- };
107
- return {
108
- valid: false,
109
- totalEntries: entries.length,
110
- verifiedEntries: 0,
111
- brokenAt: { position: 0, reason: 'unsupported_algorithm', detail },
112
- entries: [result],
113
- recordId: meta.recordId,
114
- };
115
- }
116
-
117
- let prevPayloadHash: string | null = null;
118
- for (let i = 0; i < entries.length; i++) {
119
- const entry = entries[i];
120
- const result = verifyEntry(entry, i + 1, prevPayloadHash, keys, options.requireKeyId);
121
- entryResults.push(result);
122
- if (result.valid) {
123
- verifiedEntries++;
124
- } else if (!brokenAt && result.reason) {
125
- brokenAt = { position: result.position, reason: result.reason, detail: result.detail };
126
- }
127
- prevPayloadHash = entry.integrity.payloadHash;
128
- }
129
-
130
- return {
131
- valid: verifiedEntries === entries.length && entries.length > 0,
132
- totalEntries: entries.length,
133
- verifiedEntries,
134
- brokenAt,
135
- entries: entryResults,
136
- recordId: meta.recordId,
137
- };
138
- }
139
-
140
- function resolveKeys(
141
- exportData: RecordAuditExport,
142
- options: VerifyExportOptions,
143
- ): Record<string, string> {
144
- const meta = exportData.exportMetadata;
145
- const merged: Record<string, string> = {};
146
- if (meta.signingPublicKeys) {
147
- for (const [k, v] of Object.entries(meta.signingPublicKeys)) merged[k] = v;
148
- }
149
- if (options.publicKeys) {
150
- for (const [k, v] of Object.entries(options.publicKeys)) merged[k] = v;
151
- }
152
- return merged;
153
- }
154
-
155
- class KeyCache {
156
- private readonly cache = new Map<string, KeyObject>();
157
- constructor(private readonly spki: Record<string, string>) {}
158
-
159
- get(keyId: string): KeyObject | undefined {
160
- const existing = this.cache.get(keyId);
161
- if (existing) return existing;
162
- const raw = this.spki[keyId];
163
- if (!raw) return undefined;
164
- const key = createPublicKey({ key: Buffer.from(raw, 'base64'), format: 'der', type: 'spki' });
165
- this.cache.set(keyId, key);
166
- return key;
167
- }
168
- }
169
-
170
- function verifyEntry(
171
- entry: AuditExportEntry,
172
- expectedPosition: number,
173
- expectedPrevHash: string | null,
174
- keys: KeyCache,
175
- requireKeyId: string | undefined,
176
- ): EntryVerificationResult {
177
- const position = entry.position;
178
-
179
- if (entry.position !== expectedPosition) {
180
- return {
181
- position,
182
- valid: false,
183
- reason: 'position_gap',
184
- detail: `Expected position ${expectedPosition}, got ${entry.position}`,
185
- };
186
- }
187
-
188
- const { payloadHash, previousHash, signature, signingKeyId, hashAlg, signatureAlg } =
189
- entry.integrity;
190
-
191
- if (hashAlg && !SUPPORTED_HASH.has(hashAlg)) {
192
- return { position, valid: false, reason: 'unsupported_algorithm', detail: `hashAlg=${hashAlg}` };
193
- }
194
- if (signatureAlg && !SUPPORTED_SIG.has(signatureAlg)) {
195
- return {
196
- position,
197
- valid: false,
198
- reason: 'unsupported_algorithm',
199
- detail: `signatureAlg=${signatureAlg}`,
200
- };
201
- }
202
-
203
- if (previousHash !== expectedPrevHash) {
204
- return {
205
- position,
206
- valid: false,
207
- reason: 'chain_break',
208
- detail: `Expected previousHash=${expectedPrevHash ?? 'null'}, got ${previousHash ?? 'null'}`,
209
- };
210
- }
211
-
212
- const recomputed = sha256Hex(canonicalize(entry.payload));
213
- if (recomputed !== payloadHash) {
214
- return {
215
- position,
216
- valid: false,
217
- reason: 'payload_hash_mismatch',
218
- detail: `Recomputed ${recomputed.slice(0, 16)}…, stored ${payloadHash.slice(0, 16)}…`,
219
- };
220
- }
221
-
222
- if (!signature || !signingKeyId) {
223
- return {
224
- position,
225
- valid: false,
226
- reason: 'malformed_entry',
227
- detail: 'Missing signature or signingKeyId',
228
- };
229
- }
230
-
231
- if (requireKeyId && signingKeyId !== requireKeyId) {
232
- return {
233
- position,
234
- valid: false,
235
- reason: 'unknown_key',
236
- detail: `Entry keyId=${signingKeyId} does not match requireKeyId=${requireKeyId}`,
237
- };
238
- }
239
-
240
- const publicKey = keys.get(signingKeyId);
241
- if (!publicKey) {
242
- return {
243
- position,
244
- valid: false,
245
- reason: 'unknown_key',
246
- detail: `No public key for keyId=${signingKeyId}`,
247
- };
248
- }
249
-
250
- const signInput = `${position}:${payloadHash}:${previousHash ?? 'null'}`;
251
- let sigValid = false;
252
- try {
253
- sigValid = verifyEd25519(publicKey, signInput, signature);
254
- } catch (err) {
255
- return {
256
- position,
257
- valid: false,
258
- reason: 'signature_invalid',
259
- detail: `Signature verification threw: ${(err as Error).message}`,
260
- };
261
- }
262
-
263
- if (!sigValid) {
264
- return { position, valid: false, reason: 'signature_invalid' };
265
- }
266
-
267
- return { position, valid: true };
268
- }
269
-
270
- export function canonicalize(value: unknown): string {
271
- if (value === null || value === undefined) return 'null';
272
- if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
273
- return JSON.stringify(value);
274
- }
275
- if (Array.isArray(value)) {
276
- return '[' + value.map(canonicalize).join(',') + ']';
277
- }
278
- if (typeof value === 'object') {
279
- const obj = value as Record<string, unknown>;
280
- const keys = Object.keys(obj).sort();
281
- return (
282
- '{' +
283
- keys.map((k) => JSON.stringify(k) + ':' + canonicalize(obj[k])).join(',') +
284
- '}'
285
- );
286
- }
287
- return 'null';
288
- }
289
-
290
- function sha256Hex(data: string): string {
291
- return createHash('sha256').update(data).digest('hex');
292
- }
293
-
294
- function verifyEd25519(publicKey: KeyObject, message: string, signatureHex: string): boolean {
295
- return cryptoVerify(null, Buffer.from(message), publicKey, Buffer.from(signatureHex, 'hex'));
296
- }