@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,80 @@
1
+ /** AGLedger™ — Capability MCP tools (get, declare). 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 { toolMeta } from '../tool-scopes.js';
8
+ import { ContractTypeEnum } from '../enums.js';
9
+
10
+ const CapabilitiesOutputSchema = z.object({
11
+ agentId: z.string().describe('Agent ID'),
12
+ capabilities: z.array(ContractTypeEnum).describe('Supported contract types'),
13
+ }).describe('Agent capabilities');
14
+
15
+ export function registerCapabilityTools(mcp: McpServer, client: AgledgerClient): void {
16
+ // --- get_agent_capabilities ---
17
+ mcp.registerTool(
18
+ 'get_agent_capabilities',
19
+ {
20
+ title: 'Get Agent Capabilities',
21
+ description: 'Get the declared contract type capabilities for an agent.',
22
+ inputSchema: {
23
+ agentId: z.string().describe('Agent ID to check capabilities for'),
24
+ },
25
+ outputSchema: CapabilitiesOutputSchema,
26
+ annotations: {
27
+ readOnlyHint: true,
28
+ destructiveHint: false,
29
+ idempotentHint: true,
30
+ openWorldHint: true,
31
+ },
32
+ _meta: toolMeta('get_agent_capabilities'),
33
+ },
34
+ async (args) => {
35
+ try {
36
+ const result = await client.capabilities.get(args.agentId);
37
+ return {
38
+ content: [{ type: 'text', text: `Agent ${result.agentId} supports ${result.capabilities.length} contract types.` }],
39
+ structuredContent: result as unknown as Record<string, unknown>,
40
+ };
41
+ } catch (err) {
42
+ return apiErrorResult(err);
43
+ }
44
+ },
45
+ );
46
+
47
+ // --- declare_capabilities ---
48
+ mcp.registerTool(
49
+ 'declare_capabilities',
50
+ {
51
+ title: 'Declare Capabilities',
52
+ description: 'Declare the contract types this agent supports.',
53
+ inputSchema: {
54
+ agentId: z.string().describe('Agent ID to set capabilities for'),
55
+ contractTypes: z.array(ContractTypeEnum).describe('Contract types this agent supports'),
56
+ },
57
+ outputSchema: CapabilitiesOutputSchema,
58
+ annotations: {
59
+ readOnlyHint: false,
60
+ destructiveHint: false,
61
+ idempotentHint: true,
62
+ openWorldHint: true,
63
+ },
64
+ _meta: toolMeta('declare_capabilities'),
65
+ },
66
+ async (args) => {
67
+ try {
68
+ const result = await client.capabilities.set(args.agentId, {
69
+ contractTypes: args.contractTypes,
70
+ });
71
+ return {
72
+ content: [{ type: 'text', text: `Capabilities declared for ${result.agentId}: ${result.capabilities.join(', ')}.` }],
73
+ structuredContent: result as unknown as Record<string, unknown>,
74
+ };
75
+ } catch (err) {
76
+ return apiErrorResult(err);
77
+ }
78
+ },
79
+ );
80
+ }
@@ -0,0 +1,473 @@
1
+ /** AGLedger™ — Code Mode MCP 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 { AgledgerApiError } from '@agledger/sdk';
7
+ import { apiErrorResult } from '../errors.js';
8
+ import { toolMeta } from '../tool-scopes.js';
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // SDK Manifest — static description of all resources and methods
12
+ // ---------------------------------------------------------------------------
13
+
14
+ const RESOURCE_MANIFEST: Record<string, string> = {
15
+ mandates: `## client.mandates
16
+ - create(params: CreateMandateParams): Promise<Mandate>
17
+ - createAgent(params: CreateAgentMandateParams): Promise<Mandate>
18
+ - get(id: string): Promise<Mandate>
19
+ - list(params: ListMandatesParams): Promise<Page<Mandate>>
20
+ - listAll(params: ListMandatesParams): AsyncGenerator<Mandate>
21
+ - search(params: SearchMandatesParams): Promise<Page<Mandate>>
22
+ - update(id: string, params: UpdateMandateParams): Promise<Mandate>
23
+ - transition(id: string, action: MandateTransitionAction, reason?: string): Promise<Mandate>
24
+ - cancel(id: string, reason?: string): Promise<Mandate>
25
+ - accept(id: string): Promise<Mandate>
26
+ - reject(id: string, reason?: string): Promise<Mandate>
27
+ - counterPropose(id: string, params: CounterProposeParams): Promise<Mandate>
28
+ - acceptCounter(id: string): Promise<Mandate>
29
+ - getChain(id: string): Promise<Mandate[]>
30
+ - getSubMandates(id: string): Promise<Page<Mandate>>
31
+ - delegate(id: string, params: DelegateMandateParams): Promise<Mandate>
32
+ - bulkCreate(mandates: CreateMandateParams[]): Promise<BulkCreateResult>
33
+ - getAudit(id: string): Promise<AuditChain>
34
+ - listAsPrincipal(): Promise<Page<Mandate>>
35
+ - listProposals(): Promise<Page<Mandate>>
36
+ - requestRevision(id: string, reason?: string): Promise<Mandate>
37
+ - createAndActivate(params: CreateMandateParams): Promise<Mandate>
38
+ - reportOutcome(id: string, params: ReportOutcomeParams): Promise<OutcomeResult>
39
+ - getSummary(params?: { enterpriseId?: string }): Promise<MandateStatusSummary>
40
+ - getGraph(id: string): Promise<Record<string, unknown>>
41
+ - batchGet(ids: string[]): Promise<Mandate[]>
42
+ - getValidTransitions(mandate: Mandate): readonly string[] (client-side, no API call)`,
43
+
44
+ receipts: `## client.receipts
45
+ - submit(mandateId: string, params: SubmitReceiptParams): Promise<Receipt>
46
+ - get(mandateId: string, receiptId: string): Promise<Receipt>
47
+ - list(mandateId: string, params?: ListParams): Promise<Page<Receipt>>
48
+ - listAll(mandateId: string, params?: ListParams): AsyncGenerator<Receipt>`,
49
+
50
+ verification: `## client.verification
51
+ - verify(mandateId: string, receiptIds?: string[]): Promise<VerificationResult>
52
+ - getStatus(mandateId: string): Promise<VerificationStatus>`,
53
+
54
+ disputes: `## client.disputes
55
+ - create(mandateId: string, params: CreateDisputeParams): Promise<Dispute>
56
+ - get(mandateId: string): Promise<DisputeResponse>
57
+ - escalate(mandateId: string): Promise<Dispute>
58
+ - submitEvidence(mandateId: string, params: { evidenceType: EvidenceType; payload: Record<string, unknown> }): Promise<Record<string, unknown>>`,
59
+
60
+ webhooks: `## client.webhooks
61
+ - create(params: CreateWebhookParams): Promise<Webhook>
62
+ - list(params?: ListWebhooksParams): Promise<Page<Webhook>>
63
+ - get(webhookId: string): Promise<Webhook>
64
+ - update(webhookId: string, params: Partial<CreateWebhookParams>): Promise<Webhook>
65
+ - delete(webhookId: string): Promise<void>
66
+ - pause(webhookId: string): Promise<Webhook>
67
+ - resume(webhookId: string): Promise<Webhook>
68
+ - rotate(webhookId: string): Promise<Webhook>
69
+ - ping(webhookId: string): Promise<WebhookTestResult>
70
+ - listDeliveries(webhookId: string, params?: ListParams & { status?: string }): Promise<Page<WebhookDelivery>>
71
+ - listDlq(webhookId: string, params?: ListParams): Promise<Page<WebhookDlqEntry>>
72
+ - retryAllDlq(webhookId: string): Promise<{ retried: number }>
73
+ - retryDlq(webhookId: string, dlqId: string): Promise<Record<string, unknown>>`,
74
+
75
+ reputation: `## client.reputation
76
+ - getAgent(agentId: string): Promise<Page<ReputationScore>>
77
+ - getByContractType(agentId: string, contractType: string): Promise<ReputationScore>
78
+ - getHistory(agentId: string, params?: ListParams & { from?: string; to?: string; contractType?: string; outcome?: 'PASS' | 'FAIL' }): Promise<Page<ReputationHistoryEntry>>`,
79
+
80
+ events: `## client.events
81
+ - list(params: { since: string; order?: 'asc' | 'desc' } & ListParams): Promise<Page<AgledgerEvent>>
82
+ - listAll(params: { since: string; order?: 'asc' | 'desc' } & ListParams): AsyncGenerator<AgledgerEvent>
83
+ - getAuditChain(mandateId: string): Promise<AuditChain>`,
84
+
85
+ schemas: `## client.schemas
86
+ - list(params?: { enterpriseId?: string }): Promise<Page<ContractType>>
87
+ - get(contractType: string): Promise<ContractSchema>
88
+ - delete(contractType: string): Promise<void>
89
+ - getRules(contractType: string): Promise<{ contractType; syncRuleIds; asyncRuleIds }>
90
+ - validateReceipt(contractType: string, evidence: Record<string, unknown>): Promise<SchemaValidationResult>
91
+ - getMetaSchema(): Promise<MetaSchema>
92
+ - getTemplate(contractType: string): Promise<SchemaTemplate>
93
+ - getBlankTemplate(): Promise<SchemaTemplate>
94
+ - getVersions(contractType: string): Promise<SchemaVersionDetail[]>
95
+ - getVersion(contractType: string, version: number): Promise<SchemaVersionDetail>
96
+ - diff(contractType: string, from: number, to: number): Promise<SchemaDiffResult>
97
+ - preview(input: SchemaPreviewInput): Promise<SchemaPreviewResult>
98
+ - checkCompatibility(contractType: string, schemas: { mandateSchema; receiptSchema }): Promise<SchemaCompatibilityResult>
99
+ - register(input: RegisterSchemaParams): Promise<SchemaVersionDetail>
100
+ - updateVersion(contractType: string, version: number, params: UpdateSchemaVersionParams): Promise<SchemaVersionDetail>
101
+ - exportSchema(contractType: string, opts?: ExportSchemaOptions): Promise<SchemaExportResult>
102
+ - importSchema(payload: SchemaImportPayload, opts?: ImportSchemaOptions): Promise<SchemaImportResult>
103
+ - previewImport(payload: SchemaImportPayload, opts?: ImportSchemaOptions): Promise<SchemaImportDryRunResult>`,
104
+
105
+ dashboard: `## client.dashboard
106
+ - getSummary(): Promise<DashboardSummary>
107
+ - getMetrics(params?: DashboardMetricsParams): Promise<DashboardMetrics>
108
+ - listAgents(params?: DashboardAgentParams): Promise<Page<DashboardAgent>>
109
+ - getAlerts(params?: ListParams): Promise<Page<DashboardAlert>>
110
+ - getDisputes(params?: ListParams): Promise<Page<Record<string, unknown>>>
111
+ - getAuditTrail(params?: ListParams): Promise<Page<Record<string, unknown>>>`,
112
+
113
+ compliance: `## client.compliance
114
+ - export(params: ExportComplianceParams): Promise<ComplianceExport>
115
+ - getExportStatus(exportId: string): Promise<ComplianceExport>
116
+ - downloadExport(exportId: string): Promise<Record<string, unknown>>
117
+ - waitForExport(exportId: string, opts?: { pollIntervalMs?; timeoutMs?; signal? }): Promise<ComplianceExport>
118
+ - createAssessment(mandateId: string, params: CreateAiImpactAssessmentParams): Promise<AiImpactAssessment>
119
+ - getAssessment(mandateId: string): Promise<AiImpactAssessment>
120
+ - getEuAiActReport(params?: { from?; to? }): Promise<EuAiActReport>
121
+ - getEnterpriseReport(params?: { from?; to?; format? }): Promise<Record<string, unknown>>
122
+ - analyzeAudit(mandateId: string): Promise<Record<string, unknown>>
123
+ - createRecord(mandateId: string, params: CreateComplianceRecordParams): Promise<ComplianceRecord>
124
+ - listRecords(mandateId: string, params?: ListParams): Promise<Page<ComplianceRecord>>
125
+ - getRecord(mandateId: string, recordId: string): Promise<ComplianceRecord>
126
+ - exportMandate(mandateId: string, params?: { format?: 'json' | 'csv' | 'ndjson' }): Promise<MandateAuditExport>
127
+ - stream(params: AuditStreamParams): Promise<AuditStreamResult>
128
+ - streamAll(params: AuditStreamParams): AsyncGenerator<Record<string, unknown>>`,
129
+
130
+ registration: `## client.registration
131
+ - getMe(): Promise<AccountProfile>
132
+ - register(params: RegisterParams): Promise<RegisterResult>
133
+ - registerEnterprise(params: { name: string; email?: string }): Promise<RegisterResult>
134
+ - registerAgent(params: { name: string; email?: string; agentCardUrl?: string; enterpriseId?: string }): Promise<RegisterResult>
135
+ - verifyAgentCard(agentCardUrl: string): Promise<Record<string, unknown>>
136
+ - rotateApiKey(): Promise<{ apiKey: string }>
137
+ - verifyEmail(token: string): Promise<{ sandboxMode: boolean; status: string }>
138
+ - sendVerificationEmail(email: string): Promise<{ sandboxMode: boolean; status: string }>`,
139
+
140
+ health: `## client.health
141
+ - check(): Promise<HealthResponse>
142
+ - status(): Promise<StatusResponse>
143
+ - conformance(): Promise<ConformanceResponse>`,
144
+
145
+ proxy: `## client.proxy
146
+ Unified resource with sub-resources for governance sidecar proxy operations.
147
+ - syncSession(params: SyncSessionParams): Promise<SyncSessionResult>
148
+
149
+ ### client.proxy.sessions
150
+ - create(params: CreateSessionParams): Promise<ProxySession>
151
+ - get(sessionId: string): Promise<ProxySession>
152
+ - list(params?: ListParams): Promise<Page<ProxySession>>
153
+ - sync(params: SyncSessionParams): Promise<SyncSessionResult>
154
+
155
+ ### client.proxy.toolCalls
156
+ - ingest(sessionId: string, items: ToolCallBatchItem[]): Promise<BatchResult<ProxyToolCall>>
157
+ - list(sessionId: string, params?: ListParams): Promise<Page<ProxyToolCall>>
158
+
159
+ ### client.proxy.sidecarMandates
160
+ - ingest(sessionId: string, items: SidecarMandateBatchItem[]): Promise<BatchResult<ProxySidecarMandate>>
161
+ - list(params?: ListParams & { sessionId?: string }): Promise<Page<ProxySidecarMandate>>
162
+ - listBySession(sessionId: string, params?: ListParams): Promise<Page<ProxySidecarMandate>>
163
+ - update(id: string, params: UpdateSidecarMandateParams): Promise<ProxySidecarMandate>
164
+ - formalize(id: string, formalizedMandateId: string): Promise<ProxySidecarMandate>
165
+ - dismiss(id: string): Promise<ProxySidecarMandate>
166
+
167
+ ### client.proxy.sidecarReceipts
168
+ - ingest(sessionId: string, items: SidecarReceiptBatchItem[]): Promise<BatchResult<ProxySidecarReceipt>>
169
+ - listBySession(sessionId: string, params?: ListParams): Promise<Page<ProxySidecarReceipt>>
170
+
171
+ ### client.proxy.toolCatalog
172
+ - ingest(sessionId: string, items: ToolCatalogBatchItem[]): Promise<BatchResult<ProxyToolCatalogEntry>>
173
+ - list(sessionId: string): Promise<Page<ProxyToolCatalogEntry>>
174
+
175
+ ### client.proxy.analytics
176
+ - getSession(sessionId: string): Promise<SessionAnalytics>
177
+ - getSummary(params?: { from?; to? }): Promise<AnalyticsSummary>
178
+ - getMandateSummary(sessionId: string): Promise<MandateSummary>
179
+ - getAlignment(sessionId: string): Promise<AlignmentAnalysis>`,
180
+
181
+ admin: `## client.admin
182
+ Platform-level administration. Requires platform API key.
183
+ - listEnterprises(params?: ListParams): Promise<Page<AdminEnterprise>>
184
+ - createEnterprise(params: CreateEnterpriseParams): Promise<AdminEnterprise>
185
+ - listAgents(params?: ListParams): Promise<Page<AdminAgent>>
186
+ - createAgent(params: CreateAgentParams): Promise<AdminAgent>
187
+ - updateTrustLevel(accountId: string, params: UpdateTrustLevelParams): Promise<Record<string, unknown>>
188
+ - deactivateAccount(accountId: string, params: { accountType: 'enterprise' | 'agent'; reason?: string }): Promise<Record<string, unknown>>
189
+ - setCapabilities(agentId: string, params: SetCapabilitiesParams): Promise<Record<string, unknown>>
190
+ - getFleetCapabilities(): Promise<Page<{ agentId; capabilities }>>
191
+ - getEnterpriseConfig(enterpriseId: string): Promise<EnterpriseConfig>
192
+ - replaceEnterpriseConfig(enterpriseId: string, params: SetEnterpriseConfigParams): Promise<EnterpriseConfig>
193
+ - updateEnterpriseConfig(enterpriseId: string, params: SetEnterpriseConfigParams): Promise<EnterpriseConfig>
194
+ - listApiKeys(params?: ListParams): Promise<Page<AdminApiKey>>
195
+ - createApiKey(params: CreateApiKeyParams): Promise<CreateApiKeyResult>
196
+ - toggleApiKey(keyId: string, isActive: boolean): Promise<AdminApiKey>
197
+ - bulkRevokeApiKeys(keyIds: string[]): Promise<{ revoked: number }>
198
+ - getLicense(): Promise<LicenseInfo>
199
+ - listMandates(params?: QueryAdminMandatesParams): Promise<Page<Record<string, unknown>>>
200
+ - listDlq(params?: ListParams): Promise<Page<WebhookDlqEntry>>
201
+ - retryDlq(dlqId: string): Promise<Record<string, unknown>>
202
+ - retryAllDlq(): Promise<{ retried: number }>
203
+ - getSystemHealth(): Promise<SystemHealth>
204
+ - listRateLimitExemptions(): Promise<Page<string>>
205
+ - setRateLimitExemption(ip: string): Promise<{ ip; exempt }>
206
+ - deleteRateLimitExemption(ip: string): Promise<{ ip; exempt }>
207
+ - getWebhookHealth(params?: ListParams): Promise<Page<Record<string, unknown>>>
208
+ - updateCircuitBreaker(webhookId: string, params: UpdateCircuitBreakerParams): Promise<CircuitBreakerResult>
209
+ - listVaultSigningKeys(): Promise<VaultSigningKey[]>
210
+ - rotateVaultSigningKey(): Promise<VaultSigningKey>
211
+ - listVaultAnchors(): Promise<VaultAnchor[]>
212
+ - verifyVaultAnchors(): Promise<VaultAnchorVerifyResult>
213
+ - startVaultScan(): Promise<VaultScanJob>
214
+ - getVaultScanStatus(jobId: string): Promise<VaultScanJob>
215
+ - flushAuthCache(): Promise<{ flushed: boolean }>
216
+ - getAuthCacheStats(): Promise<AuthCacheStats>
217
+ - flushSchemaCache(): Promise<{ flushed: boolean }>
218
+ - listOwnerRateLimitExemptions(): Promise<Record<string, unknown>[]>
219
+ - setOwnerRateLimitExemption(ownerId: string): Promise<Record<string, unknown>>
220
+ - deleteOwnerRateLimitExemption(ownerId: string): Promise<Record<string, unknown>>`,
221
+
222
+ a2a: `## client.a2a
223
+ Agent-to-Agent protocol (A2A). JSON-RPC 2.0 dispatch.
224
+ - getAgentCard(): Promise<AgentCard>
225
+ - dispatch(request: JsonRpcRequest): Promise<JsonRpcResponse>
226
+ - call(method: string, params?: Record<string, unknown>): Promise<JsonRpcResponse>`,
227
+
228
+ capabilities: `## client.capabilities
229
+ - get(agentId: string): Promise<{ agentId; capabilities: ContractType[] }>
230
+ - set(agentId: string, params: SetCapabilitiesParams): Promise<{ agentId; capabilities: ContractType[] }> (PUT — replaces all)`,
231
+
232
+ notarize: `## client.notarize
233
+ Agent-to-agent agreement notarization (OpenClaw flow).
234
+ - createMandate(params: NotarizeMandateParams): Promise<NotarizeMandateResult>
235
+ - getMandate(id: string): Promise<NotarizedMandate>
236
+ - getHistory(id: string): Promise<NotarizeHistory>
237
+ - acceptMandate(id: string): Promise<NotarizedMandate>
238
+ - counterPropose(id: string, params: NotarizeCounterProposeParams): Promise<NotarizeMandateResult>
239
+ - submitReceipt(id: string, params: NotarizeReceiptParams): Promise<NotarizeReceiptResult>
240
+ - renderVerdict(id: string, params: NotarizeVerdictParams): Promise<NotarizedMandate>
241
+ - verify(params: NotarizeVerifyParams): Promise<NotarizeVerifyResult>`,
242
+
243
+ enterprises: `## client.enterprises
244
+ Enterprise agent approval registry.
245
+ - approveAgent(enterpriseId: string, agentId: string, params?: ApproveAgentParams): Promise<EnterpriseAgentRecord>
246
+ - revokeAgent(enterpriseId: string, agentId: string, params?: RevokeAgentParams): Promise<void>
247
+ - updateAgentStatus(enterpriseId: string, agentId: string, params: UpdateAgentStatusParams): Promise<EnterpriseAgentRecord>
248
+ - bulkApprove(enterpriseId: string, params: BulkApproveAgentParams): Promise<BulkApproveResult>
249
+ - listAgents(enterpriseId: string, params?: ListEnterpriseAgentsParams): Promise<Page<EnterpriseAgentRecord>>
250
+ - getAgent(enterpriseId: string, agentId: string): Promise<EnterpriseAgentRecord>
251
+ `,
252
+
253
+ projects: `## client.projects
254
+ - create(params: CreateProjectParams): Promise<Project>
255
+ - list(params?: ListParams): Promise<Page<Project>>
256
+ - get(projectId: string): Promise<Project>
257
+ - update(projectId: string, params: UpdateProjectParams): Promise<Project>
258
+ - delete(projectId: string): Promise<void>`,
259
+
260
+ federation: `## client.federation
261
+ Gateway-facing federation operations. Most methods require a bearer token from register().
262
+ - register(params: RegisterGatewayParams): Promise<RegisterGatewayResult> (no auth header)
263
+ - heartbeat(params: HeartbeatParams): Promise<HeartbeatResult>
264
+ - registerAgent(params: RegisterFederatedAgentParams): Promise<{ registered: boolean }>
265
+ - listAgents(params?: ListFederatedAgentsParams): Promise<Page<FederationAgent>>
266
+ - submitStateTransition(params: SubmitStateTransitionParams): Promise<StateTransitionResult>
267
+ - relaySignal(params: RelaySignalParams): Promise<SignalRelayResult>
268
+ - rotateKey(gatewayId: string, params: RotateGatewayKeyParams): Promise<{ rotated: boolean }>
269
+ - revoke(gatewayId: string, params: RevokeGatewayParams): Promise<{ revoked; revokedAt }> (no auth header)
270
+ - catchUp(params: FederationCatchUpParams): Promise<{ data: FederationAuditEntry[]; hasMore }>
271
+ - stream(params?: { since?: string }): Promise<Record<string, unknown>>
272
+ - publishSchema(contractType: string, params: SchemaPublishParams): Promise<ContractSchema>
273
+ - confirmSchemaPublish(contractType: string, params: SchemaConfirmParams): Promise<ContractSchema>
274
+ - listContractTypes(): Promise<ContractSchema[]>
275
+ - getContractType(contractType: string): Promise<ContractSchema>
276
+ - getMandateCriteria(mandateId: string): Promise<FederationMandateCriteria>
277
+ - submitMandateCriteria(mandateId: string, params: SubmitMandateCriteriaParams): Promise<FederationMandateCriteria>
278
+ - contributeReputation(params: ContributeReputationParams): Promise<{ contributed: boolean }>
279
+ - getAgentReputation(agentId: string): Promise<FederationAgentReputation>
280
+ - broadcastRevocations(params: RevocationBroadcastParams): Promise<{ broadcast: boolean }>
281
+ - syncAgentDirectory(params: AgentDirectorySyncParams): Promise<{ synced: boolean }>`,
282
+
283
+ federationAdmin: `## client.federationAdmin
284
+ Platform admin operations for federation. Requires admin:system scope.
285
+ - createRegistrationToken(params?: CreateRegistrationTokenParams): Promise<FederationRegistrationToken>
286
+ - listGateways(params?: ListFederationGatewaysParams): Promise<Page<FederationGateway>>
287
+ - revokeGateway(gatewayId: string, params: AdminRevokeGatewayParams): Promise<{ revoked; nextSteps }>
288
+ - queryMandates(params?: QueryFederationMandatesParams): Promise<Page<FederationMandate>>
289
+ - getAuditLog(params?: FederationAuditLogParams): Promise<Page<FederationAuditEntry>>
290
+ - getHealth(): Promise<FederationHealthSummary>
291
+ - resetSequence(gatewayId: string, params?: ResetSequenceParams): Promise<{ reset; nextSteps }>
292
+ - listDlq(params?: ListOutboundDlqParams): Promise<Page<FederationDlqEntry>>
293
+ - retryDlq(dlqId: string): Promise<{ retried; nextSteps }>
294
+ - deleteDlq(dlqId: string): Promise<{ deleted: boolean }>
295
+ - rotateHubKey(): Promise<HubSigningKey>
296
+ - listHubKeys(): Promise<HubSigningKey[]>
297
+ - activateHubKey(keyId: string): Promise<HubSigningKey>
298
+ - expireHubKey(keyId: string): Promise<HubSigningKey>
299
+ - registerPeer(params: PeerRegistrationParams): Promise<FederationPeer>
300
+ - listPeers(): Promise<Page<FederationPeer>>
301
+ - getPeer(hubId: string): Promise<FederationPeer>
302
+ - revokePeer(hubId: string): Promise<{ revoked: boolean }>
303
+ - resyncPeer(hubId: string): Promise<{ synced: boolean }>
304
+ - createPeeringToken(): Promise<PeeringToken>
305
+ - deleteSchemaVersion(contractType: string, version: string): Promise<{ deleted: boolean }>
306
+ - listReputationContributions(agentId: string): Promise<ReputationContribution[]>
307
+ - resetReputation(agentId: string): Promise<{ reset: boolean }>
308
+ - getMandateCriteriaStatus(mandateId: string): Promise<MandateCriteriaStatus>`,
309
+
310
+ agents: `## client.agents
311
+ Agent identity management.
312
+ - get(agentId: string): Promise<AgentProfile>
313
+ - update(agentId: string, params: UpdateAgentParams): Promise<AgentProfile>
314
+ - addReferences(agentId: string, references: Record<string, unknown>[]): Promise<Record<string, unknown>>
315
+ - getReferences(agentId: string): Promise<Record<string, unknown>>`,
316
+
317
+ references: `## client.references
318
+ Reverse lookup for external references.
319
+ - lookup(params: { system: string; refType: string; refId: string }): Promise<ReferenceLookupResult>
320
+ - addMandateReferences(mandateId: string, references: Record<string, unknown>[]): Promise<Record<string, unknown>>
321
+ - getMandateReferences(mandateId: string): Promise<Record<string, unknown>>`,
322
+
323
+ verificationKeys: `## client.verificationKeys
324
+ Public vault signing keys for independent audit chain verification. No auth required.
325
+ - list(): Promise<VerificationKeysResponse> — returns { data: VerificationKey[], canonicalization, hashAlgorithm, signatureAlgorithm }`,
326
+ };
327
+
328
+ const RESOURCE_NAMES = Object.keys(RESOURCE_MANIFEST);
329
+
330
+ function buildFullManifest(): string {
331
+ const header = `# AGLedger SDK — Resource Manifest
332
+ 24 resources, ~200 methods. Use \`sdk_execute\` to call any method.
333
+ The \`client\` variable is a pre-configured AgledgerClient instance.
334
+
335
+ **Pagination**: \`list()\` returns \`Page<T>\` with \`.data\`, \`.total\`, \`.hasMore\`, \`.cursor\`. Use \`listAll()\` for auto-paginating async iterators.
336
+ **Options**: All methods accept an optional trailing \`RequestOptions\` parameter (timeout, idempotencyKey, authOverride).
337
+ **Errors**: SDK throws typed errors — \`AgledgerApiError\`, \`AuthenticationError\`, \`PermissionError\`, \`NotFoundError\`, \`RateLimitError\`, etc.
338
+
339
+ ---
340
+
341
+ `;
342
+ return header + RESOURCE_NAMES.map((name) => RESOURCE_MANIFEST[name]).join('\n\n');
343
+ }
344
+
345
+ const FULL_MANIFEST = buildFullManifest();
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // Tool Registration
349
+ // ---------------------------------------------------------------------------
350
+
351
+ export function registerCodeModeTools(mcp: McpServer, client: AgledgerClient): void {
352
+ // --- sdk_execute ---
353
+ mcp.registerTool(
354
+ 'sdk_execute',
355
+ {
356
+ title: 'Execute SDK Code',
357
+ description: `Execute TypeScript/JavaScript code against the AGLedger SDK client. The \`client\` variable is a pre-configured AgledgerClient instance with all 23 resources available.
358
+
359
+ Example usage:
360
+ - \`const mandate = await client.mandates.get("mnd-abc123"); return mandate;\`
361
+ - \`const page = await client.mandates.list({ status: "ACTIVE", limit: 10 }); return page.data;\`
362
+ - \`await client.mandates.transition("mnd-abc123", { action: "register" }); return "done";\`
363
+
364
+ The code runs in an async context — use \`await\` freely. Return a value to see it in the response. Use \`sdk_describe\` first to discover available resources and method signatures.
365
+
366
+ Available resources: ${RESOURCE_NAMES.join(', ')}.
367
+
368
+ SECURITY: This tool executes code in the MCP server process. It is intended for trusted agents only — the caller has the same access as the API key. Do not expose this tool to untrusted clients. A 30-second timeout prevents runaway execution.`,
369
+ inputSchema: {
370
+ code: z.string().describe('TypeScript/JavaScript code to execute. Use `client` to access the SDK. Return a value to see results.'),
371
+ },
372
+ outputSchema: z.object({
373
+ result: z.unknown().describe('The return value of the executed code'),
374
+ executionTimeMs: z.number().describe('Execution time in milliseconds'),
375
+ }),
376
+ annotations: {
377
+ readOnlyHint: false,
378
+ destructiveHint: true,
379
+ idempotentHint: false,
380
+ openWorldHint: true,
381
+ },
382
+ _meta: toolMeta('sdk_execute'),
383
+ },
384
+ async (args) => {
385
+ const TIMEOUT_MS = 30_000;
386
+ const start = Date.now();
387
+ try {
388
+ // Use AsyncFunction constructor to support top-level await
389
+ // NOTE: This executes in the same process as the MCP server — the caller
390
+ // (agent) is already trusted with the API key. The timeout prevents runaway
391
+ // code from hanging the server. For untrusted execution, use a sandbox.
392
+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
393
+ const fn = new AsyncFunction('client', args.code);
394
+ const timeout = new Promise((_, reject) =>
395
+ setTimeout(() => reject(new Error(`Execution timed out after ${TIMEOUT_MS}ms`)), TIMEOUT_MS),
396
+ );
397
+ const result = await Promise.race([fn(client), timeout]);
398
+ const executionTimeMs = Date.now() - start;
399
+ let serialized: string;
400
+ try {
401
+ serialized = JSON.stringify(result, null, 2) ?? 'undefined';
402
+ } catch {
403
+ serialized = '[Result contains circular references]';
404
+ }
405
+ return {
406
+ content: [{ type: 'text', text: `Execution completed in ${executionTimeMs}ms.\n\n${serialized}` }],
407
+ structuredContent: { result, executionTimeMs },
408
+ };
409
+ } catch (err) {
410
+ const executionTimeMs = Date.now() - start;
411
+ if (err instanceof AgledgerApiError) {
412
+ return apiErrorResult(err);
413
+ }
414
+ return {
415
+ content: [{ type: 'text', text: `Execution error after ${executionTimeMs}ms: ${err instanceof Error ? err.message : String(err)}` }],
416
+ isError: true,
417
+ };
418
+ }
419
+ },
420
+ );
421
+
422
+ // --- sdk_describe ---
423
+ mcp.registerTool(
424
+ 'sdk_describe',
425
+ {
426
+ title: 'Describe SDK Resources',
427
+ description: `Returns the AGLedger SDK resource manifest — all 23 resources with method signatures, parameters, and return types. Use this to discover what code to write for \`sdk_execute\`.
428
+
429
+ Pass a \`resource\` name (e.g., "mandates", "federation") for detailed info on one resource, or omit it for the full manifest.
430
+
431
+ Available resources: ${RESOURCE_NAMES.join(', ')}.`,
432
+ inputSchema: {
433
+ resource: z.string().optional().describe('Resource name to describe (e.g., "mandates", "federation"). Omit for full manifest.'),
434
+ },
435
+ outputSchema: z.object({
436
+ manifest: z.string().describe('SDK resource manifest with method signatures'),
437
+ resourceCount: z.number().describe('Number of resources described'),
438
+ }),
439
+ annotations: {
440
+ readOnlyHint: true,
441
+ destructiveHint: false,
442
+ idempotentHint: true,
443
+ openWorldHint: false,
444
+ },
445
+ _meta: toolMeta('sdk_describe'),
446
+ },
447
+ async (args) => {
448
+ if (args.resource) {
449
+ const name = args.resource.toLowerCase().replace(/[-_\s]/g, '');
450
+ // Try exact match first, then normalized match
451
+ const key = RESOURCE_NAMES.find(
452
+ (k) => k === args.resource || k.toLowerCase().replace(/[-_\s]/g, '') === name,
453
+ );
454
+ if (!key) {
455
+ return {
456
+ content: [{ type: 'text', text: `Unknown resource "${args.resource}". Available: ${RESOURCE_NAMES.join(', ')}` }],
457
+ isError: true,
458
+ };
459
+ }
460
+ const manifest = RESOURCE_MANIFEST[key];
461
+ return {
462
+ content: [{ type: 'text', text: manifest }],
463
+ structuredContent: { manifest, resourceCount: 1 },
464
+ };
465
+ }
466
+
467
+ return {
468
+ content: [{ type: 'text', text: FULL_MANIFEST }],
469
+ structuredContent: { manifest: FULL_MANIFEST, resourceCount: RESOURCE_NAMES.length },
470
+ };
471
+ },
472
+ );
473
+ }
@@ -0,0 +1,81 @@
1
+ /** AGLedger™ — Compliance MCP 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 { toolMeta } from '../tool-scopes.js';
8
+
9
+ export function registerComplianceTools(mcp: McpServer, client: AgledgerClient): void {
10
+ mcp.registerTool(
11
+ 'create_compliance_record',
12
+ {
13
+ title: 'Create Compliance Record',
14
+ description: 'Create a per-mandate compliance attestation. Record types: workplace_notification, affected_persons, input_data_quality, fundamental_rights_impact_assessment.',
15
+ inputSchema: {
16
+ mandateId: z.string().describe('Mandate ID to attach the record to'),
17
+ recordType: z.string().describe('Record type (e.g. workplace_notification, affected_persons)'),
18
+ attestation: z.record(z.string(), z.unknown()).describe('Attestation data'),
19
+ attestedBy: z.string().describe('Who attested (name or ID)'),
20
+ },
21
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
22
+ _meta: toolMeta('create_compliance_record'),
23
+ },
24
+ async (args) => {
25
+ try {
26
+ const record = await client.compliance.createRecord(args.mandateId, {
27
+ recordType: args.recordType as 'workplace_notification',
28
+ attestation: args.attestation,
29
+ attestedBy: args.attestedBy,
30
+ });
31
+ return {
32
+ content: [{ type: 'text', text: `Compliance record created for mandate ${args.mandateId} (type: ${args.recordType}).` }],
33
+ structuredContent: record as unknown as Record<string, unknown>,
34
+ };
35
+ } catch (err) { return apiErrorResult(err); }
36
+ },
37
+ );
38
+
39
+ mcp.registerTool(
40
+ 'list_compliance_records',
41
+ {
42
+ title: 'List Compliance Records',
43
+ description: 'List compliance attestation records for a mandate.',
44
+ inputSchema: {
45
+ mandateId: z.string().describe('Mandate ID'),
46
+ limit: z.number().optional().describe('Page size'),
47
+ },
48
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
49
+ _meta: toolMeta('list_compliance_records'),
50
+ },
51
+ async (args) => {
52
+ try {
53
+ const result = await client.compliance.listRecords(args.mandateId, { limit: args.limit });
54
+ return {
55
+ content: [{ type: 'text', text: `Found ${result.data.length} compliance records for mandate ${args.mandateId}.` }],
56
+ structuredContent: result as unknown as Record<string, unknown>,
57
+ };
58
+ } catch (err) { return apiErrorResult(err); }
59
+ },
60
+ );
61
+
62
+ mcp.registerTool(
63
+ 'get_eu_ai_act_report',
64
+ {
65
+ title: 'EU AI Act Report',
66
+ description: 'Get EU AI Act compliance report showing risk classifications, human oversight designations, and audit status across all mandates.',
67
+ inputSchema: {},
68
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
69
+ _meta: toolMeta('get_eu_ai_act_report'),
70
+ },
71
+ async () => {
72
+ try {
73
+ const report = await client.compliance.getEuAiActReport();
74
+ return {
75
+ content: [{ type: 'text', text: `EU AI Act report: ${report.summary.highRiskCount} high-risk mandates, ${report.summary.auditedCount} audited.` }],
76
+ structuredContent: report as unknown as Record<string, unknown>,
77
+ };
78
+ } catch (err) { return apiErrorResult(err); }
79
+ },
80
+ );
81
+ }