@agledger/mcp-server 1.2.0 → 1.2.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.
Files changed (47) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/server.d.ts.map +1 -1
  5. package/dist/server.js +6 -2
  6. package/dist/server.js.map +1 -1
  7. package/dist/tool-scopes.d.ts.map +1 -1
  8. package/dist/tool-scopes.js +2 -0
  9. package/dist/tool-scopes.js.map +1 -1
  10. package/dist/tools/code-mode.d.ts.map +1 -1
  11. package/dist/tools/code-mode.js +4 -1
  12. package/dist/tools/code-mode.js.map +1 -1
  13. package/dist/tools/verification-keys.d.ts +5 -0
  14. package/dist/tools/verification-keys.d.ts.map +1 -0
  15. package/dist/tools/verification-keys.js +49 -0
  16. package/dist/tools/verification-keys.js.map +1 -0
  17. package/package.json +1 -6
  18. package/src/enums.ts +48 -0
  19. package/src/errors.ts +37 -0
  20. package/src/index.ts +102 -0
  21. package/src/resources/contract-types.ts +134 -0
  22. package/src/server.ts +134 -0
  23. package/src/tool-scopes.ts +193 -0
  24. package/src/tools/a2a.ts +551 -0
  25. package/src/tools/agent-mandates.ts +336 -0
  26. package/src/tools/agents-refs.ts +296 -0
  27. package/src/tools/capabilities.ts +80 -0
  28. package/src/tools/code-mode.ts +473 -0
  29. package/src/tools/compliance.ts +81 -0
  30. package/src/tools/dashboard.ts +75 -0
  31. package/src/tools/disputes.ts +160 -0
  32. package/src/tools/enterprises.ts +243 -0
  33. package/src/tools/events.ts +55 -0
  34. package/src/tools/federation-admin.ts +948 -0
  35. package/src/tools/federation.ts +806 -0
  36. package/src/tools/health.ts +46 -0
  37. package/src/tools/mandates.ts +394 -0
  38. package/src/tools/openclaw.ts +174 -0
  39. package/src/tools/receipts.ts +185 -0
  40. package/src/tools/reputation.ts +80 -0
  41. package/src/tools/schemas.ts +685 -0
  42. package/src/tools/verification-keys.ts +58 -0
  43. package/src/tools/verification.ts +89 -0
  44. package/tests/code-mode-manifest.test.ts +144 -0
  45. package/tests/enterprises.test.ts +96 -0
  46. package/tests/schemas.test.ts +531 -0
  47. package/tsconfig.json +12 -0
@@ -0,0 +1,685 @@
1
+ /** AGLedger™ — Schema MCP tools (list, get, and schema development tools). Patent Pending. Copyright 2026 AGLedger LLC. All rights reserved. */
2
+
3
+ import { z } from 'zod';
4
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import type { AgledgerClient } from '@agledger/sdk';
6
+ import { apiErrorResult } from '../errors.js';
7
+ import { ContractTypeEnum } from '../enums.js';
8
+ import { toolMeta } from '../tool-scopes.js';
9
+
10
+ /** Accepts both standard and custom contract type identifiers. */
11
+ const ContractTypeString = z.string().describe('Contract type identifier (e.g., ACH-PROC-v1 or a custom type)');
12
+
13
+ const FieldMappingValueType = z.enum(['number', 'denomination', 'string', 'boolean', 'datetime', 'expression'])
14
+ .describe('Value type for field mapping. Use "expression" for expression-based verification rules');
15
+
16
+ const FieldMappingSchema = z.object({
17
+ ruleId: z.string().describe('Verification rule identifier'),
18
+ criteriaPath: z.string().describe('JSON path to the mandate criteria field'),
19
+ evidencePath: z.string().describe('JSON path to the receipt evidence field'),
20
+ toleranceField: z.string().optional().describe('JSON path to the tolerance specification field'),
21
+ valueType: FieldMappingValueType,
22
+ expression: z.string().optional().describe('Safe expression string. Required when valueType is "expression"'),
23
+ }).describe('Field mapping between mandate criteria and receipt evidence for verification');
24
+
25
+ const ContractTypeListOutputSchema = z.object({
26
+ contractTypes: z.array(ContractTypeEnum).describe('Array of all available contract type identifiers'),
27
+ }).describe('List of all AGLedger contract types');
28
+
29
+ const ContractSchemaOutputSchema = z.object({
30
+ contractType: ContractTypeEnum,
31
+ mandateSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for mandate criteria of this contract type'),
32
+ receiptSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for receipt evidence of this contract type'),
33
+ rulesConfig: z.object({
34
+ syncRuleIds: z.array(z.string()).describe('Synchronous verification rule IDs'),
35
+ asyncRuleIds: z.array(z.string()).describe('Asynchronous verification rule IDs'),
36
+ }).passthrough().nullable().optional().describe('Verification rules configuration'),
37
+ fieldMappings: z.array(FieldMappingSchema).optional().describe('Field mappings between criteria and evidence, including expression-based rules'),
38
+ quickStart: z.object({
39
+ criteria: z.record(z.string(), z.unknown()).describe('Example mandate criteria payload — copy-paste ready'),
40
+ evidence: z.record(z.string(), z.unknown()).describe('Example receipt evidence payload — copy-paste ready'),
41
+ }).optional().describe('Quick-start examples with copy-pasteable payloads for this contract type'),
42
+ }).passthrough().describe('Contract type schema with mandate/receipt JSON Schemas, rules, field mappings, and quickStart examples');
43
+
44
+ const MetaSchemaOutputSchema = z.object({
45
+ constraints: z.object({
46
+ maxDepth: z.number().describe('Maximum nesting depth for schema properties'),
47
+ maxNodes: z.number().describe('Maximum number of schema nodes'),
48
+ maxSizeBytes: z.number().describe('Maximum schema size in bytes'),
49
+ maxCombinerEntries: z.number().describe('Maximum entries in anyOf/oneOf/allOf'),
50
+ rootTypeMustBe: z.string().describe('Required root type for schemas'),
51
+ rootMustHaveRequired: z.boolean().describe('Whether root must have required fields'),
52
+ blockedKeywords: z.array(z.string()).describe('Blocked JSON Schema keywords'),
53
+ }).passthrough().describe('Schema authoring constraints'),
54
+ allowedFormats: z.array(z.string()).describe('Allowed JSON Schema format values'),
55
+ allowedRefs: z.array(z.string()).describe('Allowed $ref targets'),
56
+ limits: z.object({
57
+ contractTypeMaxLength: z.number().describe('Maximum length for contract type identifiers'),
58
+ maxFieldMappings: z.number().describe('Maximum number of field mappings per schema'),
59
+ ruleIdPattern: z.string().describe('Regex pattern for rule IDs'),
60
+ ruleIdMaxLength: z.number().describe('Maximum length for rule IDs'),
61
+ reservedPrefixes: z.array(z.string()).describe('Reserved contract type prefixes'),
62
+ }).passthrough().describe('Limits for schema registration'),
63
+ fieldMappingValueTypes: z.array(z.string()).describe('Allowed field mapping value types including "expression"'),
64
+ builtinRuleIds: z.array(z.string()).describe('Built-in verification rule IDs'),
65
+ expressionHelpers: z.array(z.string()).optional().describe('Available helper functions for expression-based rules'),
66
+ expressionLimits: z.object({
67
+ maxLength: z.number().describe('Maximum expression string length'),
68
+ maxAstNodes: z.number().describe('Maximum AST nodes in expression'),
69
+ maxAstDepth: z.number().describe('Maximum AST nesting depth'),
70
+ maxOperations: z.number().describe('Maximum operations in expression'),
71
+ allowedContexts: z.array(z.string()).describe('Allowed expression context variables'),
72
+ }).optional().describe('Limits for expression-based verification rules'),
73
+ sharedSchemas: z.record(z.string(), z.unknown()).describe('Reusable schema definitions'),
74
+ examples: z.object({
75
+ minimalMandate: z.record(z.string(), z.unknown()).describe('Minimal example mandate schema'),
76
+ minimalReceipt: z.record(z.string(), z.unknown()).describe('Minimal example receipt schema'),
77
+ }).passthrough().describe('Example schemas for reference'),
78
+ }).passthrough().describe('Meta-schema describing constraints and limits for custom schema authoring');
79
+
80
+ const SchemaPreviewOutputSchema = z.object({
81
+ valid: z.boolean().describe('Whether the schema is valid'),
82
+ compiled: z.record(z.string(), z.unknown()).optional().describe('Compiled schema output if valid'),
83
+ errors: z.array(z.object({
84
+ code: z.string().describe('Error code'),
85
+ message: z.string().describe('Error message'),
86
+ path: z.string().optional().describe('JSON path to the error location'),
87
+ })).optional().describe('Validation errors if invalid'),
88
+ }).describe('Schema preview/validation result');
89
+
90
+ const SchemaVersionOutputSchema = z.object({
91
+ id: z.string().describe('Version record ID'),
92
+ contractType: ContractTypeString,
93
+ version: z.number().describe('Version number'),
94
+ enterpriseId: z.string().nullable().describe('Enterprise ID if enterprise-scoped, null for global'),
95
+ displayName: z.string().describe('Human-readable name'),
96
+ description: z.string().describe('Schema description'),
97
+ category: z.string().describe('Schema category'),
98
+ compatibilityMode: z.string().describe('Compatibility mode: FULL, BACKWARD, FORWARD, or NONE'),
99
+ status: z.string().describe('Version status: ACTIVE, DEPRECATED, or DRAFT'),
100
+ isBuiltin: z.boolean().describe('Whether this is a built-in AGLedger schema'),
101
+ createdAt: z.string().describe('ISO 8601 creation timestamp'),
102
+ updatedAt: z.string().describe('ISO 8601 last update timestamp'),
103
+ }).passthrough().describe('Schema version detail');
104
+
105
+ const SchemaDiffChangeSchema = z.object({
106
+ type: z.string().describe('Change type: added, removed, modified, renamed'),
107
+ path: z.string().describe('JSON path of the changed field'),
108
+ before: z.unknown().optional().describe('Previous value'),
109
+ after: z.unknown().optional().describe('New value'),
110
+ }).describe('A single schema change');
111
+
112
+ const SchemaDiffOutputSchema = z.object({
113
+ contractType: ContractTypeString,
114
+ from: z.object({
115
+ version: z.number(),
116
+ createdAt: z.string(),
117
+ status: z.string(),
118
+ }).describe('Source version info'),
119
+ to: z.object({
120
+ version: z.number(),
121
+ createdAt: z.string(),
122
+ status: z.string(),
123
+ }).describe('Target version info'),
124
+ mandate: z.object({
125
+ changes: z.array(SchemaDiffChangeSchema),
126
+ }).describe('Changes to mandate criteria schema'),
127
+ receipt: z.object({
128
+ changes: z.array(SchemaDiffChangeSchema),
129
+ }).describe('Changes to receipt evidence schema'),
130
+ }).passthrough().describe('Diff between two schema versions');
131
+
132
+ const CompatibilityModeEnum = z.enum(['FULL', 'BACKWARD', 'FORWARD', 'NONE'])
133
+ .describe('Schema compatibility mode');
134
+
135
+ export function registerSchemaTools(mcp: McpServer, client: AgledgerClient): void {
136
+ // --- list_contract_schemas ---
137
+ mcp.registerTool(
138
+ 'list_contract_schemas',
139
+ {
140
+ title: 'List Contract Schemas',
141
+ description: 'List all AGLedger contract type identifiers (built-in and custom). Each type now includes quickStart examples. Start here when building a new schema — use the returned types as reference patterns, then call get_contract_schema on a similar type to see its structure and quickStart guide.',
142
+ inputSchema: {},
143
+ outputSchema: ContractTypeListOutputSchema,
144
+ annotations: {
145
+ readOnlyHint: true,
146
+ destructiveHint: false,
147
+ idempotentHint: true,
148
+ openWorldHint: true,
149
+ },
150
+ _meta: toolMeta('list_contract_schemas'),
151
+ },
152
+ async () => {
153
+ try {
154
+ const result = await client.schemas.list();
155
+ return {
156
+ content: [{ type: 'text', text: `${result.data.length} contract types available: ${result.data.join(', ')}.` }],
157
+ structuredContent: { contractTypes: result.data } as unknown as Record<string, unknown>,
158
+ };
159
+ } catch (err) {
160
+ return apiErrorResult(err);
161
+ }
162
+ },
163
+ );
164
+
165
+ // --- get_contract_schema ---
166
+ mcp.registerTool(
167
+ 'get_contract_schema',
168
+ {
169
+ title: 'Get Contract Schema',
170
+ description: 'Get the full JSON Schema for a contract type, including mandate/receipt schemas, verification rules, field mappings, and quickStart examples with copy-pasteable payloads. Use this to understand an existing type before creating a custom one.',
171
+ inputSchema: {
172
+ contractType: ContractTypeEnum.describe('Contract type to retrieve the schema for'),
173
+ },
174
+ outputSchema: ContractSchemaOutputSchema,
175
+ annotations: {
176
+ readOnlyHint: true,
177
+ destructiveHint: false,
178
+ idempotentHint: true,
179
+ openWorldHint: true,
180
+ },
181
+ _meta: toolMeta('get_contract_schema'),
182
+ },
183
+ async (args) => {
184
+ try {
185
+ const schema = await client.schemas.get(args.contractType);
186
+ return {
187
+ content: [{ type: 'text', text: `Schema for ${schema.contractType}: mandate schema has ${Object.keys(schema.mandateSchema).length} fields, receipt schema has ${Object.keys(schema.receiptSchema).length} fields.${(schema as any).quickStart ? ' Includes quickStart examples with copy-pasteable payloads.' : ''}` }],
188
+ structuredContent: schema as unknown as Record<string, unknown>,
189
+ };
190
+ } catch (err) {
191
+ return apiErrorResult(err);
192
+ }
193
+ },
194
+ );
195
+
196
+ // --- get_meta_schema ---
197
+ mcp.registerTool(
198
+ 'get_meta_schema',
199
+ {
200
+ title: 'Get Meta-Schema',
201
+ description: 'Get the meta-schema that defines constraints and limits for custom schema authoring (max depth, allowed formats, field mapping types, expression limits). Review this BEFORE designing a custom schema.',
202
+ inputSchema: {},
203
+ outputSchema: MetaSchemaOutputSchema,
204
+ annotations: {
205
+ readOnlyHint: true,
206
+ destructiveHint: false,
207
+ idempotentHint: true,
208
+ openWorldHint: true,
209
+ },
210
+ _meta: toolMeta('get_meta_schema'),
211
+ },
212
+ async () => {
213
+ try {
214
+ const metaSchema = await client.schemas.getMetaSchema();
215
+ return {
216
+ content: [{ type: 'text', text: `Meta-schema: max depth ${metaSchema.constraints.maxDepth}, max nodes ${metaSchema.constraints.maxNodes}, max size ${metaSchema.constraints.maxSizeBytes} bytes. ${metaSchema.allowedFormats.length} allowed formats, max ${metaSchema.limits.maxFieldMappings} field mappings, ${metaSchema.fieldMappingValueTypes.length} value types (${metaSchema.fieldMappingValueTypes.join(', ')}). Next: call get_schema_template or get_blank_schema_template to start building.` }],
217
+ structuredContent: metaSchema as unknown as Record<string, unknown>,
218
+ };
219
+ } catch (err) {
220
+ return apiErrorResult(err);
221
+ }
222
+ },
223
+ );
224
+
225
+ // --- preview_schema ---
226
+ mcp.registerTool(
227
+ 'preview_schema',
228
+ {
229
+ title: 'Preview Schema',
230
+ description: 'Preview and validate a custom contract type schema before registration. Returns validation errors (with examplePayload showing correct structure) or the compiled output. Supports expression-based field mappings in fieldMappings array.',
231
+ inputSchema: {
232
+ contractType: ContractTypeString.describe('Custom contract type identifier (e.g., ACH-CUSTOM-v1)'),
233
+ displayName: z.string().describe('Human-readable name for the contract type'),
234
+ description: z.string().optional().describe('Description of the contract type'),
235
+ category: z.string().optional().describe('Category for the contract type'),
236
+ mandateSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for mandate criteria'),
237
+ receiptSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for receipt evidence'),
238
+ fieldMappings: z.array(FieldMappingSchema).optional().describe('Field mappings for verification rules, including expression-based rules'),
239
+ compatibilityMode: CompatibilityModeEnum.optional().describe('Compatibility mode for version evolution'),
240
+ },
241
+ outputSchema: SchemaPreviewOutputSchema,
242
+ annotations: {
243
+ readOnlyHint: true,
244
+ destructiveHint: false,
245
+ idempotentHint: true,
246
+ openWorldHint: true,
247
+ },
248
+ _meta: toolMeta('preview_schema'),
249
+ },
250
+ async (args) => {
251
+ try {
252
+ const result = await client.schemas.preview({
253
+ contractType: args.contractType,
254
+ displayName: args.displayName,
255
+ description: args.description,
256
+ category: args.category,
257
+ mandateSchema: args.mandateSchema,
258
+ receiptSchema: args.receiptSchema,
259
+ fieldMappings: args.fieldMappings,
260
+ compatibilityMode: args.compatibilityMode,
261
+ });
262
+ const status = result.valid
263
+ ? `valid. Schema is valid. Next: call register_schema to register it.`
264
+ : `invalid (${result.errors?.length ?? 0} errors). Fix the errors above, then call preview_schema again.`;
265
+ return {
266
+ content: [{ type: 'text', text: `Schema preview for ${args.contractType}: ${status}` }],
267
+ structuredContent: result as unknown as Record<string, unknown>,
268
+ };
269
+ } catch (err) {
270
+ return apiErrorResult(err);
271
+ }
272
+ },
273
+ );
274
+
275
+ // --- register_schema ---
276
+ mcp.registerTool(
277
+ 'register_schema',
278
+ {
279
+ title: 'Register Schema',
280
+ description: 'Register a new custom contract type schema. Use preview_schema first to validate. Supports expression-based field mappings. On validation error, returns examplePayload with correct structure. Returns the created schema version detail on success.',
281
+ inputSchema: {
282
+ contractType: ContractTypeString.describe('Custom contract type identifier (e.g., ACH-CUSTOM-v1)'),
283
+ displayName: z.string().describe('Human-readable name for the contract type'),
284
+ description: z.string().optional().describe('Description of the contract type'),
285
+ category: z.string().optional().describe('Category for the contract type'),
286
+ mandateSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for mandate criteria'),
287
+ receiptSchema: z.record(z.string(), z.unknown()).describe('JSON Schema for receipt evidence'),
288
+ fieldMappings: z.array(FieldMappingSchema).optional().describe('Field mappings for verification rules, including expression-based rules'),
289
+ compatibilityMode: CompatibilityModeEnum.optional().describe('Compatibility mode for version evolution'),
290
+ },
291
+ outputSchema: SchemaVersionOutputSchema,
292
+ annotations: {
293
+ readOnlyHint: false,
294
+ destructiveHint: false,
295
+ idempotentHint: false,
296
+ openWorldHint: true,
297
+ },
298
+ _meta: toolMeta('register_schema'),
299
+ },
300
+ async (args) => {
301
+ try {
302
+ const result = await client.schemas.register({
303
+ contractType: args.contractType,
304
+ displayName: args.displayName,
305
+ description: args.description,
306
+ category: args.category,
307
+ mandateSchema: args.mandateSchema,
308
+ receiptSchema: args.receiptSchema,
309
+ fieldMappings: args.fieldMappings,
310
+ compatibilityMode: args.compatibilityMode,
311
+ });
312
+ return {
313
+ content: [{ type: 'text', text: `Registered ${result.contractType} v${result.version} (${result.status}). Schema registered. Use get_schema_versions to see all versions.` }],
314
+ structuredContent: result as unknown as Record<string, unknown>,
315
+ };
316
+ } catch (err) {
317
+ return apiErrorResult(err);
318
+ }
319
+ },
320
+ );
321
+
322
+ // --- get_schema_versions ---
323
+ mcp.registerTool(
324
+ 'get_schema_versions',
325
+ {
326
+ title: 'Get Schema Versions',
327
+ description: 'List all versions of a contract type schema, including version numbers, status, compatibility mode, and timestamps.',
328
+ inputSchema: {
329
+ contractType: ContractTypeString.describe('Contract type to list versions for'),
330
+ },
331
+ outputSchema: z.object({
332
+ contractType: ContractTypeString,
333
+ versions: z.array(SchemaVersionOutputSchema),
334
+ }).describe('All versions of a contract type schema'),
335
+ annotations: {
336
+ readOnlyHint: true,
337
+ destructiveHint: false,
338
+ idempotentHint: true,
339
+ openWorldHint: true,
340
+ },
341
+ _meta: toolMeta('get_schema_versions'),
342
+ },
343
+ async (args) => {
344
+ try {
345
+ const versions = await client.schemas.getVersions(args.contractType as Parameters<typeof client.schemas.getVersions>[0]);
346
+ return {
347
+ content: [{ type: 'text', text: `${args.contractType}: ${versions.length} version(s). Latest: v${versions.length > 0 ? versions[versions.length - 1].version : 'none'}. Use get_schema_version to inspect a specific version, or diff_schema_versions to compare two.` }],
348
+ structuredContent: { contractType: args.contractType, versions } as unknown as Record<string, unknown>,
349
+ };
350
+ } catch (err) {
351
+ return apiErrorResult(err);
352
+ }
353
+ },
354
+ );
355
+
356
+ // --- diff_schema_versions ---
357
+ mcp.registerTool(
358
+ 'diff_schema_versions',
359
+ {
360
+ title: 'Diff Schema Versions',
361
+ description: 'Compare two versions of a contract type schema. Shows added, removed, modified, and renamed fields in both mandate and receipt schemas.',
362
+ inputSchema: {
363
+ contractType: ContractTypeString.describe('Contract type to diff'),
364
+ from: z.number().int().min(1).describe('Source version number'),
365
+ to: z.number().int().min(1).describe('Target version number'),
366
+ },
367
+ outputSchema: SchemaDiffOutputSchema,
368
+ annotations: {
369
+ readOnlyHint: true,
370
+ destructiveHint: false,
371
+ idempotentHint: true,
372
+ openWorldHint: true,
373
+ },
374
+ _meta: toolMeta('diff_schema_versions'),
375
+ },
376
+ async (args) => {
377
+ try {
378
+ const diff = await client.schemas.diff(
379
+ args.contractType as Parameters<typeof client.schemas.diff>[0],
380
+ args.from,
381
+ args.to,
382
+ );
383
+ const mandateChanges = diff.mandate.changes.length;
384
+ const receiptChanges = diff.receipt.changes.length;
385
+ return {
386
+ content: [{ type: 'text', text: `Diff ${args.contractType} v${args.from} → v${args.to}: ${mandateChanges} mandate change(s), ${receiptChanges} receipt change(s).` }],
387
+ structuredContent: diff as unknown as Record<string, unknown>,
388
+ };
389
+ } catch (err) {
390
+ return apiErrorResult(err);
391
+ }
392
+ },
393
+ );
394
+
395
+ // --- get_schema_template ---
396
+ mcp.registerTool(
397
+ 'get_schema_template',
398
+ {
399
+ title: 'Get Schema Template',
400
+ description: 'Get a starter template from an existing contract type. Use this to scaffold a new custom schema based on a similar built-in type. After getting the template, modify it and use preview_schema to validate.',
401
+ inputSchema: {
402
+ contractType: ContractTypeString.describe('Contract type to use as template (e.g. ACH-PROC-v1)'),
403
+ },
404
+ annotations: {
405
+ readOnlyHint: true,
406
+ destructiveHint: false,
407
+ idempotentHint: true,
408
+ openWorldHint: true,
409
+ },
410
+ _meta: toolMeta('get_schema_template'),
411
+ },
412
+ async (args) => {
413
+ try {
414
+ const template = await client.schemas.getTemplate(args.contractType as Parameters<typeof client.schemas.getTemplate>[0]);
415
+ return {
416
+ content: [{ type: 'text', text: `Template from ${args.contractType}. Next: modify the template, then call preview_schema to validate before registration.` }],
417
+ structuredContent: template as unknown as Record<string, unknown>,
418
+ };
419
+ } catch (err) {
420
+ return apiErrorResult(err);
421
+ }
422
+ },
423
+ );
424
+
425
+ // --- get_blank_schema_template ---
426
+ mcp.registerTool(
427
+ 'get_blank_schema_template',
428
+ {
429
+ title: 'Get Blank Schema Template',
430
+ description: 'Get a blank template for creating a custom contract type from scratch. Returns the minimal valid structure with placeholder fields. After filling in, use preview_schema to validate.',
431
+ inputSchema: {},
432
+ annotations: {
433
+ readOnlyHint: true,
434
+ destructiveHint: false,
435
+ idempotentHint: true,
436
+ openWorldHint: true,
437
+ },
438
+ _meta: toolMeta('get_blank_schema_template'),
439
+ },
440
+ async () => {
441
+ try {
442
+ const template = await client.schemas.getBlankTemplate();
443
+ return {
444
+ content: [{ type: 'text', text: `Blank schema template ready. Next: fill in contractType, mandateSchema, receiptSchema, then call preview_schema.` }],
445
+ structuredContent: template as unknown as Record<string, unknown>,
446
+ };
447
+ } catch (err) {
448
+ return apiErrorResult(err);
449
+ }
450
+ },
451
+ );
452
+
453
+ // --- check_schema_compatibility ---
454
+ mcp.registerTool(
455
+ 'check_schema_compatibility',
456
+ {
457
+ title: 'Check Schema Compatibility',
458
+ description: 'Check if schema changes are backward/forward compatible with the existing version. Run this BEFORE register_schema to catch breaking changes early.',
459
+ inputSchema: {
460
+ contractType: ContractTypeString.describe('Contract type to check compatibility against'),
461
+ mandateSchema: z.record(z.string(), z.unknown()).describe('Proposed mandate criteria JSON Schema'),
462
+ receiptSchema: z.record(z.string(), z.unknown()).describe('Proposed receipt evidence JSON Schema'),
463
+ },
464
+ annotations: {
465
+ readOnlyHint: true,
466
+ destructiveHint: false,
467
+ idempotentHint: true,
468
+ openWorldHint: true,
469
+ },
470
+ _meta: toolMeta('check_schema_compatibility'),
471
+ },
472
+ async (args) => {
473
+ try {
474
+ const result = await client.schemas.checkCompatibility(
475
+ args.contractType as Parameters<typeof client.schemas.checkCompatibility>[0],
476
+ { mandateSchema: args.mandateSchema, receiptSchema: args.receiptSchema },
477
+ );
478
+ return {
479
+ content: [{ type: 'text', text: `Compatibility check for ${args.contractType}: ${JSON.stringify(result)}.` }],
480
+ structuredContent: result as unknown as Record<string, unknown>,
481
+ };
482
+ } catch (err) {
483
+ return apiErrorResult(err);
484
+ }
485
+ },
486
+ );
487
+
488
+ // --- get_schema_version ---
489
+ mcp.registerTool(
490
+ 'get_schema_version',
491
+ {
492
+ title: 'Get Schema Version',
493
+ description: 'Get a specific version of a contract type schema. Use get_schema_versions first to see available versions, then this to inspect a particular one.',
494
+ inputSchema: {
495
+ contractType: ContractTypeString.describe('Contract type to retrieve'),
496
+ version: z.number().int().describe('Version number'),
497
+ },
498
+ outputSchema: SchemaVersionOutputSchema,
499
+ annotations: {
500
+ readOnlyHint: true,
501
+ destructiveHint: false,
502
+ idempotentHint: true,
503
+ openWorldHint: true,
504
+ },
505
+ _meta: toolMeta('get_schema_version'),
506
+ },
507
+ async (args) => {
508
+ try {
509
+ const result = await client.schemas.getVersion(
510
+ args.contractType as Parameters<typeof client.schemas.getVersion>[0],
511
+ args.version,
512
+ );
513
+ return {
514
+ content: [{ type: 'text', text: `${result.contractType} v${result.version} (${result.status}), created ${result.createdAt}.` }],
515
+ structuredContent: result as unknown as Record<string, unknown>,
516
+ };
517
+ } catch (err) {
518
+ return apiErrorResult(err);
519
+ }
520
+ },
521
+ );
522
+
523
+ // --- validate_receipt_schema ---
524
+ mcp.registerTool(
525
+ 'validate_receipt_schema',
526
+ {
527
+ title: 'Validate Receipt Schema',
528
+ description: 'Dry-run validate receipt evidence against a contract type schema. Use this BEFORE calling submit_receipt to check if your evidence structure is correct.',
529
+ inputSchema: {
530
+ contractType: ContractTypeString.describe('Contract type to validate against (e.g., ACH-PROC-v1)'),
531
+ evidence: z.record(z.string(), z.unknown()).describe('Evidence object to validate'),
532
+ },
533
+ annotations: {
534
+ readOnlyHint: true,
535
+ destructiveHint: false,
536
+ idempotentHint: true,
537
+ openWorldHint: true,
538
+ },
539
+ _meta: toolMeta('validate_receipt_schema'),
540
+ },
541
+ async (args) => {
542
+ try {
543
+ const result = await client.schemas.validateReceipt(
544
+ args.contractType as Parameters<typeof client.schemas.validateReceipt>[0],
545
+ args.evidence,
546
+ );
547
+ if (result.valid) {
548
+ return {
549
+ content: [{ type: 'text', text: `Evidence is valid for ${args.contractType}. You can now call submit_receipt.` }],
550
+ structuredContent: result as unknown as Record<string, unknown>,
551
+ };
552
+ }
553
+ const errorCount = result.errors?.length ?? 0;
554
+ const errorDetails = result.errors?.map(e => `- ${e.instancePath ?? '/'}: ${e.message}`).join('\n') ?? '';
555
+ return {
556
+ content: [{ type: 'text', text: `Evidence is invalid for ${args.contractType} (${errorCount} error(s)):\n${errorDetails}\n\nFix the errors and try again.` }],
557
+ structuredContent: result as unknown as Record<string, unknown>,
558
+ };
559
+ } catch (err) {
560
+ return apiErrorResult(err);
561
+ }
562
+ },
563
+ );
564
+
565
+ // --- get_schema_rules ---
566
+ mcp.registerTool(
567
+ 'get_schema_rules',
568
+ {
569
+ title: 'Get Schema Rules',
570
+ description: 'Get verification rule IDs configured for a contract type. Rules define how mandate criteria are verified against receipt evidence.',
571
+ inputSchema: {
572
+ contractType: ContractTypeString.describe('Contract type to get rules for'),
573
+ },
574
+ annotations: {
575
+ readOnlyHint: true,
576
+ destructiveHint: false,
577
+ idempotentHint: true,
578
+ openWorldHint: true,
579
+ },
580
+ _meta: toolMeta('get_schema_rules'),
581
+ },
582
+ async (args) => {
583
+ try {
584
+ const result = await client.schemas.getRules(args.contractType as Parameters<typeof client.schemas.getRules>[0]);
585
+ const total = result.syncRuleIds.length + result.asyncRuleIds.length;
586
+ return {
587
+ content: [{ type: 'text', text: `${args.contractType}: ${total} rule(s) — ${result.syncRuleIds.length} sync, ${result.asyncRuleIds.length} async.` }],
588
+ structuredContent: result as unknown as Record<string, unknown>,
589
+ };
590
+ } catch (err) {
591
+ return apiErrorResult(err);
592
+ }
593
+ },
594
+ );
595
+
596
+ // --- delete_schema ---
597
+ mcp.registerTool(
598
+ 'delete_schema',
599
+ {
600
+ title: 'Delete Schema',
601
+ description: 'Delete a custom contract type schema. Cannot delete built-in types.',
602
+ inputSchema: {
603
+ contractType: ContractTypeString.describe('Custom contract type identifier to delete'),
604
+ },
605
+ annotations: {
606
+ readOnlyHint: false,
607
+ destructiveHint: true,
608
+ idempotentHint: true,
609
+ openWorldHint: true,
610
+ },
611
+ _meta: toolMeta('delete_schema'),
612
+ },
613
+ async (args) => {
614
+ try {
615
+ const result = await client.schemas.delete(args.contractType);
616
+ return {
617
+ content: [{ type: 'text', text: `Schema ${args.contractType} deleted.` }],
618
+ structuredContent: result as unknown as Record<string, unknown>,
619
+ };
620
+ } catch (err) {
621
+ return apiErrorResult(err);
622
+ }
623
+ },
624
+ );
625
+
626
+ // --- export_schema ---
627
+ mcp.registerTool(
628
+ 'export_schema',
629
+ {
630
+ title: 'Export Schema',
631
+ description: 'Export a schema bundle for promotion to another environment.',
632
+ inputSchema: {
633
+ contractType: ContractTypeString.describe('Contract type to export'),
634
+ },
635
+ annotations: {
636
+ readOnlyHint: true,
637
+ destructiveHint: false,
638
+ idempotentHint: true,
639
+ openWorldHint: true,
640
+ },
641
+ _meta: toolMeta('export_schema'),
642
+ },
643
+ async (args) => {
644
+ try {
645
+ const bundle = await client.schemas.exportSchema(args.contractType);
646
+ return {
647
+ content: [{ type: 'text', text: `Exported schema bundle for ${args.contractType}. Use import_schema to import into another environment.` }],
648
+ structuredContent: bundle as unknown as Record<string, unknown>,
649
+ };
650
+ } catch (err) {
651
+ return apiErrorResult(err);
652
+ }
653
+ },
654
+ );
655
+
656
+ // --- import_schema ---
657
+ mcp.registerTool(
658
+ 'import_schema',
659
+ {
660
+ title: 'Import Schema',
661
+ description: 'Import a schema bundle from another environment.',
662
+ inputSchema: {
663
+ bundle: z.record(z.string(), z.unknown()).describe('Schema bundle object from export_schema'),
664
+ },
665
+ annotations: {
666
+ readOnlyHint: false,
667
+ destructiveHint: false,
668
+ idempotentHint: true,
669
+ openWorldHint: true,
670
+ },
671
+ _meta: toolMeta('import_schema'),
672
+ },
673
+ async (args) => {
674
+ try {
675
+ const result = await client.schemas.importSchema(args.bundle as any);
676
+ return {
677
+ content: [{ type: 'text', text: `Schema imported successfully.` }],
678
+ structuredContent: result as unknown as Record<string, unknown>,
679
+ };
680
+ } catch (err) {
681
+ return apiErrorResult(err);
682
+ }
683
+ },
684
+ );
685
+ }