@agledger/mcp-server 1.5.0 → 2.0.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 (162) hide show
  1. package/dist/api-client.d.ts +16 -0
  2. package/dist/api-client.d.ts.map +1 -0
  3. package/dist/api-client.js +52 -0
  4. package/dist/api-client.js.map +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +17 -58
  7. package/dist/index.js.map +1 -1
  8. package/dist/server.d.ts +2 -13
  9. package/dist/server.d.ts.map +1 -1
  10. package/dist/server.js +113 -109
  11. package/dist/server.js.map +1 -1
  12. package/package.json +2 -3
  13. package/src/api-client.ts +72 -0
  14. package/src/index.ts +27 -60
  15. package/src/server.ts +136 -120
  16. package/tests/api-client.test.ts +147 -0
  17. package/tests/harness.ts +8 -35
  18. package/tests/integration.test.ts +373 -0
  19. package/tests/server.test.ts +286 -0
  20. package/dist/enums.d.ts +0 -110
  21. package/dist/enums.d.ts.map +0 -1
  22. package/dist/enums.js +0 -42
  23. package/dist/enums.js.map +0 -1
  24. package/dist/errors.d.ts +0 -10
  25. package/dist/errors.d.ts.map +0 -1
  26. package/dist/errors.js +0 -49
  27. package/dist/errors.js.map +0 -1
  28. package/dist/resources/contract-types.d.ts +0 -4
  29. package/dist/resources/contract-types.d.ts.map +0 -1
  30. package/dist/resources/contract-types.js +0 -104
  31. package/dist/resources/contract-types.js.map +0 -1
  32. package/dist/tool-scopes.d.ts +0 -11
  33. package/dist/tool-scopes.d.ts.map +0 -1
  34. package/dist/tool-scopes.js +0 -164
  35. package/dist/tool-scopes.js.map +0 -1
  36. package/dist/tools/a2a.d.ts +0 -8
  37. package/dist/tools/a2a.d.ts.map +0 -1
  38. package/dist/tools/a2a.js +0 -360
  39. package/dist/tools/a2a.js.map +0 -1
  40. package/dist/tools/agent-mandates.d.ts +0 -4
  41. package/dist/tools/agent-mandates.d.ts.map +0 -1
  42. package/dist/tools/agent-mandates.js +0 -222
  43. package/dist/tools/agent-mandates.js.map +0 -1
  44. package/dist/tools/agents-refs.d.ts +0 -4
  45. package/dist/tools/agents-refs.d.ts.map +0 -1
  46. package/dist/tools/agents-refs.js +0 -196
  47. package/dist/tools/agents-refs.js.map +0 -1
  48. package/dist/tools/capabilities.d.ts +0 -4
  49. package/dist/tools/capabilities.d.ts.map +0 -1
  50. package/dist/tools/capabilities.js +0 -54
  51. package/dist/tools/capabilities.js.map +0 -1
  52. package/dist/tools/code-mode.d.ts +0 -4
  53. package/dist/tools/code-mode.d.ts.map +0 -1
  54. package/dist/tools/code-mode.js +0 -389
  55. package/dist/tools/code-mode.js.map +0 -1
  56. package/dist/tools/compliance.d.ts +0 -4
  57. package/dist/tools/compliance.d.ts.map +0 -1
  58. package/dist/tools/compliance.js +0 -63
  59. package/dist/tools/compliance.js.map +0 -1
  60. package/dist/tools/dashboard.d.ts +0 -4
  61. package/dist/tools/dashboard.d.ts.map +0 -1
  62. package/dist/tools/dashboard.js +0 -57
  63. package/dist/tools/dashboard.js.map +0 -1
  64. package/dist/tools/disputes.d.ts +0 -4
  65. package/dist/tools/disputes.d.ts.map +0 -1
  66. package/dist/tools/disputes.js +0 -103
  67. package/dist/tools/disputes.js.map +0 -1
  68. package/dist/tools/enterprises.d.ts +0 -4
  69. package/dist/tools/enterprises.d.ts.map +0 -1
  70. package/dist/tools/enterprises.js +0 -173
  71. package/dist/tools/enterprises.js.map +0 -1
  72. package/dist/tools/events.d.ts +0 -4
  73. package/dist/tools/events.d.ts.map +0 -1
  74. package/dist/tools/events.js +0 -28
  75. package/dist/tools/events.js.map +0 -1
  76. package/dist/tools/federation-admin.d.ts +0 -4
  77. package/dist/tools/federation-admin.d.ts.map +0 -1
  78. package/dist/tools/federation-admin.js +0 -567
  79. package/dist/tools/federation-admin.js.map +0 -1
  80. package/dist/tools/federation.d.ts +0 -4
  81. package/dist/tools/federation.d.ts.map +0 -1
  82. package/dist/tools/federation.js +0 -505
  83. package/dist/tools/federation.js.map +0 -1
  84. package/dist/tools/health.d.ts +0 -4
  85. package/dist/tools/health.d.ts.map +0 -1
  86. package/dist/tools/health.js +0 -25
  87. package/dist/tools/health.js.map +0 -1
  88. package/dist/tools/mandates.d.ts +0 -4
  89. package/dist/tools/mandates.d.ts.map +0 -1
  90. package/dist/tools/mandates.js +0 -227
  91. package/dist/tools/mandates.js.map +0 -1
  92. package/dist/tools/openclaw.d.ts +0 -4
  93. package/dist/tools/openclaw.d.ts.map +0 -1
  94. package/dist/tools/openclaw.js +0 -110
  95. package/dist/tools/openclaw.js.map +0 -1
  96. package/dist/tools/receipts.d.ts +0 -8
  97. package/dist/tools/receipts.d.ts.map +0 -1
  98. package/dist/tools/receipts.js +0 -111
  99. package/dist/tools/receipts.js.map +0 -1
  100. package/dist/tools/reputation.d.ts +0 -4
  101. package/dist/tools/reputation.d.ts.map +0 -1
  102. package/dist/tools/reputation.js +0 -62
  103. package/dist/tools/reputation.js.map +0 -1
  104. package/dist/tools/schemas.d.ts +0 -4
  105. package/dist/tools/schemas.d.ts.map +0 -1
  106. package/dist/tools/schemas.js +0 -453
  107. package/dist/tools/schemas.js.map +0 -1
  108. package/dist/tools/verification-keys.d.ts +0 -4
  109. package/dist/tools/verification-keys.d.ts.map +0 -1
  110. package/dist/tools/verification-keys.js +0 -27
  111. package/dist/tools/verification-keys.js.map +0 -1
  112. package/dist/tools/verification.d.ts +0 -4
  113. package/dist/tools/verification.d.ts.map +0 -1
  114. package/dist/tools/verification.js +0 -50
  115. package/dist/tools/verification.js.map +0 -1
  116. package/src/enums.ts +0 -47
  117. package/src/errors.ts +0 -44
  118. package/src/resources/contract-types.ts +0 -130
  119. package/src/tool-scopes.ts +0 -180
  120. package/src/tools/a2a.ts +0 -430
  121. package/src/tools/agent-mandates.ts +0 -259
  122. package/src/tools/agents-refs.ts +0 -232
  123. package/src/tools/capabilities.ts +0 -63
  124. package/src/tools/compliance.ts +0 -70
  125. package/src/tools/dashboard.ts +0 -64
  126. package/src/tools/disputes.ts +0 -121
  127. package/src/tools/enterprises.ts +0 -203
  128. package/src/tools/events.ts +0 -33
  129. package/src/tools/federation-admin.ts +0 -665
  130. package/src/tools/federation.ts +0 -587
  131. package/src/tools/health.ts +0 -30
  132. package/src/tools/mandates.ts +0 -264
  133. package/src/tools/openclaw.ts +0 -122
  134. package/src/tools/receipts.ts +0 -134
  135. package/src/tools/reputation.ts +0 -69
  136. package/src/tools/schemas.ts +0 -535
  137. package/src/tools/verification-keys.ts +0 -33
  138. package/src/tools/verification.ts +0 -59
  139. package/tests/conformance.test.ts +0 -197
  140. package/tests/conformance.ts +0 -65
  141. package/tests/mock-client.ts +0 -71
  142. package/tests/profiles.test.ts +0 -120
  143. package/tests/resources/contract-types.test.ts +0 -82
  144. package/tests/tools/a2a.test.ts +0 -213
  145. package/tests/tools/agent-mandates.test.ts +0 -196
  146. package/tests/tools/agents-refs.test.ts +0 -190
  147. package/tests/tools/capabilities.test.ts +0 -80
  148. package/tests/tools/compliance.test.ts +0 -123
  149. package/tests/tools/dashboard.test.ts +0 -111
  150. package/tests/tools/disputes.test.ts +0 -123
  151. package/tests/tools/enterprises.test.ts +0 -171
  152. package/tests/tools/events.test.ts +0 -56
  153. package/tests/tools/federation-admin.test.ts +0 -468
  154. package/tests/tools/federation.test.ts +0 -522
  155. package/tests/tools/health.test.ts +0 -56
  156. package/tests/tools/mandates.test.ts +0 -143
  157. package/tests/tools/openclaw.test.ts +0 -148
  158. package/tests/tools/receipts.test.ts +0 -157
  159. package/tests/tools/reputation.test.ts +0 -108
  160. package/tests/tools/schemas.test.ts +0 -374
  161. package/tests/tools/verification-keys.test.ts +0 -56
  162. package/tests/tools/verification.test.ts +0 -64
package/src/index.ts CHANGED
@@ -3,58 +3,40 @@ import { parseArgs } from 'node:util';
3
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
4
  import { AgledgerMcpServer } from './server.js';
5
5
 
6
+ process.on('uncaughtException', (err) => {
7
+ process.stderr.write(`Uncaught exception: ${err.message}\n`);
8
+ });
9
+
10
+ process.on('unhandledRejection', (reason) => {
11
+ process.stderr.write(
12
+ `Unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}\n`,
13
+ );
14
+ });
15
+
6
16
  function main(): void {
7
17
  const { values } = parseArgs({
8
18
  options: {
9
- 'api-key': {
10
- type: 'string',
11
- short: 'k',
12
- },
13
- 'api-url': {
14
- type: 'string',
15
- short: 'u',
16
- },
17
- profile: {
18
- type: 'string',
19
- short: 'p',
20
- },
21
- 'enterprise-id': {
22
- type: 'string',
23
- short: 'e',
24
- },
25
- help: {
26
- type: 'boolean',
27
- short: 'h',
28
- },
19
+ 'api-key': { type: 'string', short: 'k' },
20
+ 'api-url': { type: 'string', short: 'u' },
21
+ help: { type: 'boolean', short: 'h' },
29
22
  },
30
23
  strict: true,
31
24
  });
32
25
 
33
26
  if (values.help) {
34
27
  process.stderr.write(
35
- `AGLedger™ MCP Server v1.4.0
28
+ `AGLedger MCP Server v2.0.1
36
29
 
37
- Usage: agledger-mcp --api-key <key> [--api-url <url>] [--profile <profile>]
30
+ Usage: agledger-mcp --api-key <key> [--api-url <url>]
38
31
 
39
32
  Options:
40
- --api-key, -k AGLedger API key (required)
41
- --api-url, -u AGLedger API base URL (default: https://agledger.example.com)
42
- --profile, -p Tool profile (required, see below)
33
+ --api-key, -k AGLedger API key (or AGLEDGER_API_KEY env var)
34
+ --api-url, -u AGLedger API base URL (or AGLEDGER_API_URL env var)
43
35
  --help, -h Show this help message
44
36
 
45
- Profiles:
46
- agent Standard agent workflow: create mandates, submit receipts, verdicts, verification
47
- admin Enterprise management: mandates, receipts, agents, capabilities, reputation, federation admin
48
- audit Compliance monitoring: mandates, receipts, events, verification, disputes, dashboard
49
- schema-dev Custom contract type authoring with workflow guidance
50
- openclaw Lightweight notarization for agent-to-agent agreements (5 tools)
51
- federation Federation gateway operations + admin
52
- full All tools (development/debugging only)
53
-
54
- Environment:
55
- AGLEDGER_API_KEY API key (overridden by --api-key)
56
- AGLEDGER_API_URL API URL (overridden by --api-url)
57
- AGLEDGER_PROFILE Tool profile (overridden by --profile)
37
+ Tools:
38
+ agledger_discover Returns API health, your identity, and available scopes
39
+ agledger_api Make any AGLedger API call — the API guides you via nextSteps
58
40
  `,
59
41
  );
60
42
  process.exit(0);
@@ -62,36 +44,21 @@ Environment:
62
44
 
63
45
  const apiKey = values['api-key'] ?? process.env.AGLEDGER_API_KEY;
64
46
  const apiUrl = values['api-url'] ?? process.env.AGLEDGER_API_URL;
65
- const profileRaw = values.profile ?? process.env.AGLEDGER_PROFILE;
66
- if (!profileRaw) {
67
- process.stderr.write(`Error: --profile or AGLEDGER_PROFILE is required.
68
-
69
- Choose a profile to control which tools are available:
70
- agent Standard agent workflow — create mandates, submit receipts, verdicts
71
- admin Enterprise management — mandates, receipts, agents, capabilities, reputation
72
- audit Compliance monitoring — mandates, events, verification, disputes, dashboard
73
- schema-dev Custom contract type authoring
74
- openclaw Lightweight notarization (5 tools)
75
- federation Federation gateway operations + admin
76
- full All tools (development/debugging only)
77
-
78
- Example: agledger-mcp --api-key <key> --profile agent
79
- `);
80
- process.exit(1);
81
- }
82
- const profile = profileRaw as 'full' | 'agent' | 'openclaw' | 'schema-dev' | 'admin' | 'audit' | 'federation';
83
- const enterpriseId = values['enterprise-id'] ?? process.env.AGLEDGER_ENTERPRISE_ID;
84
47
 
85
48
  if (!apiKey) {
86
- process.stderr.write('Error: --api-key or AGLEDGER_API_KEY environment variable is required.\n');
49
+ process.stderr.write(
50
+ 'Error: --api-key or AGLEDGER_API_KEY environment variable is required.\n',
51
+ );
87
52
  process.exit(1);
88
53
  }
89
54
 
90
- const server = new AgledgerMcpServer({ apiKey, apiUrl, profile, enterpriseId });
55
+ const server = new AgledgerMcpServer({ apiKey, apiUrl });
91
56
  const transport = new StdioServerTransport();
92
57
 
93
58
  server.mcp.connect(transport).catch((err: unknown) => {
94
- process.stderr.write(`Fatal: failed to start MCP server: ${err instanceof Error ? err.message : String(err)}\n`);
59
+ process.stderr.write(
60
+ `Fatal: failed to start MCP server: ${err instanceof Error ? err.message : String(err)}\n`,
61
+ );
95
62
  process.exit(1);
96
63
  });
97
64
  }
package/src/server.ts CHANGED
@@ -1,145 +1,161 @@
1
+ import { z } from 'zod';
1
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { AgledgerClient } from '@agledger/sdk';
3
-
4
- import { registerMandateTools } from './tools/mandates.js';
5
- import { registerAgentMandateTools } from './tools/agent-mandates.js';
6
- import { registerReceiptTools } from './tools/receipts.js';
7
- import { registerVerificationTools } from './tools/verification.js';
8
- import { registerDisputeTools } from './tools/disputes.js';
9
- import { registerReputationTools } from './tools/reputation.js';
10
- import { registerEventTools } from './tools/events.js';
11
- import { registerSchemaTools } from './tools/schemas.js';
12
- import { registerHealthTools } from './tools/health.js';
13
- import { registerCapabilityTools } from './tools/capabilities.js';
14
- import { registerA2aTools } from './tools/a2a.js';
15
- import { registerOpenClawTools } from './tools/openclaw.js';
16
- import { registerEnterpriseTools } from './tools/enterprises.js';
17
- import { registerDashboardTools } from './tools/dashboard.js';
18
- import { registerComplianceTools } from './tools/compliance.js';
19
- import { registerFederationTools } from './tools/federation.js';
20
- import { registerFederationAdminTools } from './tools/federation-admin.js';
21
- import { registerAgentsRefsTools } from './tools/agents-refs.js';
22
- import { registerVerificationKeysTools } from './tools/verification-keys.js';
23
- import { registerContractTypeResources } from './resources/contract-types.js';
24
-
25
- export type ToolProfile = 'full' | 'agent' | 'openclaw' | 'schema-dev' | 'admin' | 'audit' | 'federation';
3
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
4
+ import { ApiClient } from './api-client.js';
26
5
 
27
6
  export interface AgledgerMcpServerOptions {
28
7
  apiKey: string;
29
8
  apiUrl?: string;
30
- /** Tool profile: "agent", "openclaw", "schema-dev", "admin", "audit", "federation", or "full" (legacy, all individual tools). */
31
- profile?: ToolProfile;
32
- /** Enterprise ID for A2A search queries. Falls back to AGLEDGER_ENTERPRISE_ID env var. */
33
- enterpriseId?: string;
34
9
  }
35
10
 
36
- type RegisterFn = (mcp: McpServer, client: AgledgerClient) => void;
37
-
38
- function buildProfileRegistry(enterpriseId?: string): Record<ToolProfile, RegisterFn[]> {
39
- return {
40
- openclaw: [registerOpenClawTools],
41
- agent: [
42
- (mcp, client) => registerA2aTools(mcp, client, { enterpriseId }),
43
- (mcp, client) => registerReceiptTools(mcp, client, { skipSubmit: true }),
44
- registerVerificationTools,
45
- registerAgentsRefsTools,
46
- registerHealthTools,
47
- ],
48
- 'schema-dev': [registerSchemaTools, registerHealthTools],
49
- admin: [
50
- registerMandateTools,
51
- registerReceiptTools,
52
- registerEnterpriseTools,
53
- registerCapabilityTools,
54
- registerReputationTools,
55
- registerAgentsRefsTools,
56
- registerFederationAdminTools,
57
- registerHealthTools,
58
- registerVerificationKeysTools,
59
- ],
60
- federation: [
61
- registerFederationTools,
62
- registerFederationAdminTools,
63
- registerAgentsRefsTools,
64
- registerHealthTools,
65
- ],
66
- audit: [
67
- registerMandateTools,
68
- registerReceiptTools,
69
- registerEventTools,
70
- registerVerificationTools,
71
- registerDisputeTools,
72
- registerReputationTools,
73
- registerDashboardTools,
74
- registerComplianceTools,
75
- registerAgentsRefsTools,
76
- registerHealthTools,
77
- registerVerificationKeysTools,
78
- ],
79
- full: [
80
- registerMandateTools,
81
- registerAgentMandateTools,
82
- registerReceiptTools,
83
- registerVerificationTools,
84
- registerDisputeTools,
85
- registerReputationTools,
86
- registerEventTools,
87
- registerSchemaTools,
88
- registerHealthTools,
89
- registerCapabilityTools,
90
- registerEnterpriseTools,
91
- registerDashboardTools,
92
- registerComplianceTools,
93
- registerFederationTools,
94
- registerFederationAdminTools,
95
- registerAgentsRefsTools,
96
- registerVerificationKeysTools,
97
- ],
98
- };
99
- }
100
-
101
- /** Exported for testing — returns the profile registry for a given enterpriseId. */
102
- export function getProfileRegistry(enterpriseId?: string): Record<ToolProfile, RegisterFn[]> {
103
- return buildProfileRegistry(enterpriseId);
11
+ function errorResult(message: string): CallToolResult {
12
+ return { content: [{ type: 'text', text: `Error: ${message}` }], isError: true };
104
13
  }
105
14
 
106
15
  export class AgledgerMcpServer {
107
16
  readonly mcp: McpServer;
108
- readonly client: AgledgerClient;
109
- readonly profile: ToolProfile;
110
- private readonly enterpriseId?: string;
17
+ readonly client: ApiClient;
111
18
 
112
19
  constructor(options: AgledgerMcpServerOptions) {
113
- this.profile = options.profile ?? 'full';
114
- this.enterpriseId = options.enterpriseId;
20
+ const apiUrl = options.apiUrl ?? 'https://agledger.example.com';
21
+
22
+ this.client = new ApiClient(apiUrl, options.apiKey);
115
23
 
116
24
  this.mcp = new McpServer(
25
+ { name: 'agledger-mcp-server', version: '2.0.1' },
26
+ { capabilities: { tools: {} } },
27
+ );
28
+
29
+ this.registerTools();
30
+ }
31
+
32
+ private registerTools(): void {
33
+ const client = this.client;
34
+
35
+ this.mcp.registerTool(
36
+ 'agledger_discover',
117
37
  {
118
- name: 'agledger-mcp-server',
119
- version: '1.5.0',
38
+ title: 'Discover AGLedger API',
39
+ description:
40
+ 'Returns API health, your identity, and available scopes. ' +
41
+ 'Call this first to understand what you can do. ' +
42
+ 'The response includes nextSteps guiding you to available endpoints.',
43
+ inputSchema: {},
44
+ annotations: {
45
+ readOnlyHint: true,
46
+ destructiveHint: false,
47
+ idempotentHint: true,
48
+ openWorldHint: true,
49
+ },
120
50
  },
51
+ async () => {
52
+ try {
53
+ const [health, identity] = await Promise.allSettled([
54
+ client.request('GET', '/health'),
55
+ client.request('GET', '/v1/auth/me'),
56
+ ]);
57
+
58
+ const result: Record<string, unknown> = {};
59
+
60
+ if (health.status === 'fulfilled') {
61
+ result.health = health.value.body;
62
+ } else {
63
+ result.health = {
64
+ error: health.reason instanceof Error ? health.reason.message : String(health.reason),
65
+ };
66
+ }
67
+
68
+ if (identity.status === 'fulfilled') {
69
+ result.identity = identity.value.body;
70
+ } else {
71
+ result.identity = {
72
+ error:
73
+ identity.reason instanceof Error
74
+ ? identity.reason.message
75
+ : String(identity.reason),
76
+ };
77
+ }
78
+
79
+ return { content: [], structuredContent: result };
80
+ } catch (err) {
81
+ return errorResult(err instanceof Error ? err.message : String(err));
82
+ }
83
+ },
84
+ );
85
+
86
+ this.mcp.registerTool(
87
+ 'agledger_api',
121
88
  {
122
- capabilities: {
123
- tools: {},
124
- resources: {},
89
+ title: 'AGLedger API',
90
+ description:
91
+ 'Make any AGLedger API call. The API returns nextSteps on every response to guide you. ' +
92
+ 'Start with agledger_discover to see available endpoints, then follow nextSteps. ' +
93
+ 'Common entry points: /mandates, /schemas, /health, /auth/me, /agents/{agentId}/reputation. ' +
94
+ 'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body.',
95
+ inputSchema: {
96
+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
97
+ path: z.string().describe('API path (e.g. /mandates, /schemas, /mandates/{id}/receipts)'),
98
+ params: z
99
+ .record(z.string(), z.unknown())
100
+ .optional()
101
+ .describe(
102
+ 'Request parameters. For GET/DELETE: query params. For POST/PUT/PATCH: JSON body.',
103
+ ),
104
+ },
105
+ annotations: {
106
+ readOnlyHint: false,
107
+ destructiveHint: false,
108
+ idempotentHint: false,
109
+ openWorldHint: true,
125
110
  },
126
111
  },
127
- );
112
+ async (args) => {
113
+ try {
114
+ const { method, path, params } = args;
128
115
 
129
- this.client = new AgledgerClient({
130
- apiKey: options.apiKey,
131
- baseUrl: options.apiUrl ?? 'https://agledger.example.com',
132
- });
116
+ if (!path.startsWith('/')) {
117
+ return errorResult('Path must start with /');
118
+ }
133
119
 
134
- this.registerTools();
135
- }
120
+ const options: { query?: Record<string, unknown>; body?: unknown } = {};
136
121
 
137
- private registerTools(): void {
138
- const registry = buildProfileRegistry(this.enterpriseId);
139
- const fns = registry[this.profile];
140
- for (const fn of fns) {
141
- fn(this.mcp, this.client);
142
- }
143
- registerContractTypeResources(this.mcp, this.client);
122
+ if (params) {
123
+ if (method === 'GET' || method === 'DELETE') {
124
+ options.query = params;
125
+ } else {
126
+ options.body = params;
127
+ }
128
+ }
129
+
130
+ const response = await client.request(method, path, options);
131
+
132
+ if (response.ok) {
133
+ return {
134
+ content: [],
135
+ structuredContent: response.body as Record<string, unknown>,
136
+ };
137
+ }
138
+
139
+ const errorBody = (response.body ?? {}) as Record<string, unknown>;
140
+ const message = (errorBody.message ??
141
+ errorBody.error ??
142
+ `API returned ${response.status}`) as string;
143
+
144
+ return {
145
+ content: [{ type: 'text', text: `Error: ${message}` }],
146
+ structuredContent: errorBody,
147
+ isError: true,
148
+ };
149
+ } catch (err) {
150
+ if (err instanceof DOMException && err.name === 'AbortError') {
151
+ return errorResult('Request timed out. The API did not respond within 30 seconds.');
152
+ }
153
+ if (err instanceof TypeError && err.message.includes('fetch')) {
154
+ return errorResult(`Network error: ${err.message}. Check API URL and connectivity.`);
155
+ }
156
+ return errorResult(err instanceof Error ? err.message : String(err));
157
+ }
158
+ },
159
+ );
144
160
  }
145
161
  }
@@ -0,0 +1,147 @@
1
+ import { describe, it, expect, afterEach, vi } from 'vitest';
2
+ import { ApiClient } from '../src/api-client.js';
3
+
4
+ afterEach(() => {
5
+ vi.unstubAllGlobals();
6
+ });
7
+
8
+ describe('ApiClient', () => {
9
+ it('sends authorization header', async () => {
10
+ const mockFetch = vi.fn().mockResolvedValueOnce(
11
+ new Response(JSON.stringify({ ok: true }), {
12
+ status: 200,
13
+ headers: { 'content-type': 'application/json' },
14
+ }),
15
+ );
16
+ vi.stubGlobal('fetch', mockFetch);
17
+
18
+ const client = new ApiClient('https://api.test.com', 'my-secret-key');
19
+ await client.request('GET', '/health');
20
+
21
+ const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
22
+ const headers = options.headers as Record<string, string>;
23
+ expect(headers.Authorization).toBe('Bearer my-secret-key');
24
+ });
25
+
26
+ it('appends query params for GET', async () => {
27
+ const mockFetch = vi.fn().mockResolvedValueOnce(
28
+ new Response(JSON.stringify({}), {
29
+ status: 200,
30
+ headers: { 'content-type': 'application/json' },
31
+ }),
32
+ );
33
+ vi.stubGlobal('fetch', mockFetch);
34
+
35
+ const client = new ApiClient('https://api.test.com', 'key');
36
+ await client.request('GET', '/search', { query: { q: 'test', limit: 10 } });
37
+
38
+ const url = new URL(mockFetch.mock.calls[0][0] as string);
39
+ expect(url.searchParams.get('q')).toBe('test');
40
+ expect(url.searchParams.get('limit')).toBe('10');
41
+ });
42
+
43
+ it('skips undefined query params', async () => {
44
+ const mockFetch = vi.fn().mockResolvedValueOnce(
45
+ new Response(JSON.stringify({}), {
46
+ status: 200,
47
+ headers: { 'content-type': 'application/json' },
48
+ }),
49
+ );
50
+ vi.stubGlobal('fetch', mockFetch);
51
+
52
+ const client = new ApiClient('https://api.test.com', 'key');
53
+ await client.request('GET', '/search', { query: { q: 'test', missing: undefined } });
54
+
55
+ const url = new URL(mockFetch.mock.calls[0][0] as string);
56
+ expect(url.searchParams.has('missing')).toBe(false);
57
+ });
58
+
59
+ it('sends JSON body for POST', async () => {
60
+ const mockFetch = vi.fn().mockResolvedValueOnce(
61
+ new Response(JSON.stringify({ id: '1' }), {
62
+ status: 201,
63
+ headers: { 'content-type': 'application/json' },
64
+ }),
65
+ );
66
+ vi.stubGlobal('fetch', mockFetch);
67
+
68
+ const client = new ApiClient('https://api.test.com', 'key');
69
+ await client.request('POST', '/mandates', { body: { contractType: 'ACH-PROC-v1' } });
70
+
71
+ const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
72
+ const headers = options.headers as Record<string, string>;
73
+ expect(headers['Content-Type']).toBe('application/json');
74
+ expect(JSON.parse(options.body as string)).toEqual({ contractType: 'ACH-PROC-v1' });
75
+ });
76
+
77
+ it('handles non-JSON responses', async () => {
78
+ vi.stubGlobal(
79
+ 'fetch',
80
+ vi.fn().mockResolvedValueOnce(
81
+ new Response('Service Unavailable', {
82
+ status: 503,
83
+ headers: { 'content-type': 'text/plain' },
84
+ }),
85
+ ),
86
+ );
87
+
88
+ const client = new ApiClient('https://api.test.com', 'key');
89
+ const result = await client.request('GET', '/health');
90
+
91
+ expect(result.ok).toBe(false);
92
+ expect(result.status).toBe(503);
93
+ expect((result.body as Record<string, unknown>)._raw).toBe('Service Unavailable');
94
+ });
95
+
96
+ it('strips trailing slash from base URL', async () => {
97
+ const mockFetch = vi.fn().mockResolvedValueOnce(
98
+ new Response(JSON.stringify({}), {
99
+ status: 200,
100
+ headers: { 'content-type': 'application/json' },
101
+ }),
102
+ );
103
+ vi.stubGlobal('fetch', mockFetch);
104
+
105
+ const client = new ApiClient('https://api.test.com/', 'key');
106
+ await client.request('GET', '/health');
107
+
108
+ const url = mockFetch.mock.calls[0][0] as string;
109
+ expect(url).toBe('https://api.test.com/health');
110
+ });
111
+
112
+ it('sets ok=true for 2xx responses', async () => {
113
+ vi.stubGlobal(
114
+ 'fetch',
115
+ vi.fn().mockResolvedValueOnce(
116
+ new Response(JSON.stringify({ id: '1' }), {
117
+ status: 201,
118
+ headers: { 'content-type': 'application/json' },
119
+ }),
120
+ ),
121
+ );
122
+
123
+ const client = new ApiClient('https://api.test.com', 'key');
124
+ const result = await client.request('POST', '/mandates', { body: {} });
125
+
126
+ expect(result.ok).toBe(true);
127
+ expect(result.status).toBe(201);
128
+ });
129
+
130
+ it('sets ok=false for 4xx/5xx responses', async () => {
131
+ vi.stubGlobal(
132
+ 'fetch',
133
+ vi.fn().mockResolvedValueOnce(
134
+ new Response(JSON.stringify({ message: 'Not found' }), {
135
+ status: 404,
136
+ headers: { 'content-type': 'application/json' },
137
+ }),
138
+ ),
139
+ );
140
+
141
+ const client = new ApiClient('https://api.test.com', 'key');
142
+ const result = await client.request('GET', '/mandates/bad');
143
+
144
+ expect(result.ok).toBe(false);
145
+ expect(result.status).toBe(404);
146
+ });
147
+ });
package/tests/harness.ts CHANGED
@@ -1,55 +1,28 @@
1
1
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
2
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
3
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
- import type { AgledgerClient } from '@agledger/sdk';
5
- import { createMockClient, type MockOverrides } from './mock-client.js';
3
+ import { AgledgerMcpServer } from '../src/server.js';
6
4
 
7
5
  export interface TestHarness {
8
- /** MCP protocol client — use listTools(), callTool() for real round-trip tests. */
9
6
  client: Client;
10
- /** The mocked SDK client — use for configuring return values and verifying calls. */
11
- mockSdk: AgledgerClient;
12
- /** Disconnect both transports. Call in afterAll/afterEach. */
13
7
  cleanup: () => Promise<void>;
14
8
  }
15
9
 
16
- export interface HarnessOptions {
17
- /** Tool registration functions to invoke. Each receives (mcp, client). */
18
- registerFns: Array<(mcp: McpServer, client: AgledgerClient) => void>;
19
- /** SDK mock overrides. */
20
- mockOverrides?: MockOverrides;
21
- }
22
-
23
- /**
24
- * Create a full MCP Client <-> Server round-trip test harness.
25
- * Uses InMemoryTransport — no network, no subprocess, full protocol stack.
26
- */
27
- export async function createTestHarness(options: HarnessOptions): Promise<TestHarness> {
28
- const mockSdk = createMockClient(options.mockOverrides);
29
-
30
- const mcp = new McpServer(
31
- { name: 'test-agledger-mcp', version: '0.0.0-test' },
32
- { capabilities: { tools: {}, resources: {} } },
33
- );
34
-
35
- for (const fn of options.registerFns) {
36
- fn(mcp, mockSdk);
37
- }
10
+ export async function createTestHarness(): Promise<TestHarness> {
11
+ const server = new AgledgerMcpServer({
12
+ apiKey: 'test-key',
13
+ apiUrl: 'https://test.agledger.example.com',
14
+ });
38
15
 
39
16
  const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
40
17
  const client = new Client({ name: 'test-client', version: '0.0.0-test' });
41
18
 
42
- await Promise.all([
43
- mcp.connect(serverTransport),
44
- client.connect(clientTransport),
45
- ]);
19
+ await Promise.all([server.mcp.connect(serverTransport), client.connect(clientTransport)]);
46
20
 
47
21
  return {
48
22
  client,
49
- mockSdk,
50
23
  cleanup: async () => {
51
24
  await client.close();
52
- await mcp.close();
25
+ await server.mcp.close();
53
26
  },
54
27
  };
55
28
  }