@sparkysolutions/agentrail 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +249 -146
  2. package/dist/cli/mcp-stdio.d.ts +8 -0
  3. package/dist/cli/mcp-stdio.js +454 -0
  4. package/dist/cli/pipeline.d.ts +40 -0
  5. package/dist/cli/pipeline.js +114 -0
  6. package/dist/cli/sandbox.d.ts +15 -1
  7. package/dist/cli/sandbox.js +30 -5
  8. package/dist/index.d.ts +13 -0
  9. package/dist/index.js +13 -0
  10. package/dist/lib/agent-badge-issuer.d.ts +36 -0
  11. package/dist/lib/agent-badge-issuer.js +166 -0
  12. package/dist/lib/agent-registry.d.ts +136 -0
  13. package/dist/lib/agent-registry.js +124 -0
  14. package/dist/lib/agenthustle-pipeline.d.ts +68 -0
  15. package/dist/lib/agenthustle-pipeline.js +143 -0
  16. package/dist/lib/agentpass-pipeline.d.ts +44 -0
  17. package/dist/lib/agentpass-pipeline.js +84 -0
  18. package/dist/lib/audit-trail-provider.d.ts +24 -0
  19. package/dist/lib/audit-trail-provider.js +60 -0
  20. package/dist/lib/axis-clob-provider.d.ts +50 -0
  21. package/dist/lib/axis-clob-provider.js +150 -0
  22. package/dist/lib/circuit-breaker.d.ts +60 -0
  23. package/dist/lib/circuit-breaker.js +136 -0
  24. package/dist/lib/conditional-escrow.d.ts +42 -0
  25. package/dist/lib/conditional-escrow.js +126 -0
  26. package/dist/lib/mcp-server.d.ts +29 -0
  27. package/dist/lib/mcp-server.js +165 -0
  28. package/dist/lib/receipts.d.ts +153 -0
  29. package/dist/lib/receipts.js +173 -0
  30. package/dist/lib/reflector-oracle-adapter.d.ts +44 -0
  31. package/dist/lib/reflector-oracle-adapter.js +173 -0
  32. package/dist/lib/scoped-allowance.d.ts +4 -0
  33. package/dist/lib/scoped-allowance.js +22 -1
  34. package/dist/lib/universal-adapters.d.ts +42 -0
  35. package/dist/lib/universal-adapters.js +69 -0
  36. package/dist/lib/x402-gateway.d.ts +86 -0
  37. package/dist/lib/x402-gateway.js +128 -0
  38. package/dist/lib/x402-pipeline.d.ts +51 -0
  39. package/dist/lib/x402-pipeline.js +105 -0
  40. package/dist/types.d.ts +109 -0
  41. package/glama.json +12 -0
  42. package/package.json +56 -40
  43. package/smithery.json +43 -0
  44. package/smithery.yaml +29 -0
  45. package/.github/ISSUE_TEMPLATE/drips_wave_task.md +0 -33
  46. package/.github/workflows/auto-merge.yml +0 -119
  47. package/.github/workflows/ci.yml +0 -35
  48. package/BENCHMARKS.md +0 -67
  49. package/CONTRIBUTING.md +0 -40
  50. package/DRIPS_WAVE.md +0 -81
  51. package/FUNDING.json +0 -7
  52. package/ISSUES_PIPELINE.json +0 -106
  53. package/RUNBOOK.md +0 -95
  54. package/SCF_ACTIVATION_PROPOSAL.md +0 -137
  55. package/assets/sorobanagents_avatar.jpg +0 -0
  56. package/assets/sorobanagents_avatar.png +0 -0
  57. package/assets/sorobanagents_avatar_elite.png +0 -0
  58. package/contracts/agentrail/Cargo.lock +0 -1895
  59. package/contracts/agentrail/Cargo.toml +0 -25
  60. package/contracts/agentrail/src/lib.rs +0 -296
  61. package/contracts/agentrail/src/test.rs +0 -442
  62. package/contracts/agentrail/test_snapshots/test/test_circuit_breaker_pause_and_unpause.1.json +0 -195
  63. package/contracts/agentrail/test_snapshots/test/test_double_initialize_fails.1.json +0 -123
  64. package/contracts/agentrail/test_snapshots/test/test_execute_spend_deducts_and_accumulates.1.json +0 -347
  65. package/contracts/agentrail/test_snapshots/test/test_get_allowance_returns_none_for_unregistered.1.json +0 -61
  66. package/contracts/agentrail/test_snapshots/test/test_get_version_matches_cargo_toml.1.json +0 -61
  67. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_negative_amount_fails.1.json +0 -123
  68. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_success.1.json +0 -250
  69. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_zero_amount_fails.1.json +0 -123
  70. package/contracts/agentrail/test_snapshots/test/test_initialize_and_protocol_fee.1.json +0 -154
  71. package/contracts/agentrail/test_snapshots/test/test_initialize_success.1.json +0 -124
  72. package/contracts/agentrail/test_snapshots/test/test_initialize_with_excessive_fee_fails.1.json +0 -61
  73. package/contracts/agentrail/test_snapshots/test/test_max_protocol_fee_spend_boundary.1.json +0 -298
  74. package/contracts/agentrail/test_snapshots/test/test_multi_agent_allowance_isolation.1.json +0 -426
  75. package/contracts/agentrail/test_snapshots/test/test_multi_owner_isolation.1.json +0 -426
  76. package/contracts/agentrail/test_snapshots/test/test_regrant_allowance_updates_limits.1.json +0 -346
  77. package/contracts/agentrail/test_snapshots/test/test_revoke_allowance_freezes_spending.1.json +0 -292
  78. package/contracts/agentrail/test_snapshots/test/test_set_protocol_fee_by_admin.1.json +0 -165
  79. package/contracts/agentrail/test_snapshots/test/test_spend_after_expiry_fails.1.json +0 -250
  80. package/contracts/agentrail/test_snapshots/test/test_spend_exact_allowance_boundary.1.json +0 -298
  81. package/contracts/agentrail/test_snapshots/test/test_spend_exceeding_allowance_fails.1.json +0 -250
  82. package/contracts/agentrail/test_snapshots/test/test_spend_fails_when_circuit_breaker_tripped.1.json +0 -285
  83. package/contracts/agentrail/test_snapshots/test/test_spend_negative_amount_fails.1.json +0 -250
  84. package/contracts/agentrail/test_snapshots/test/test_spend_non_existent_allowance_fails.1.json +0 -123
  85. package/contracts/agentrail/test_snapshots/test/test_spend_on_revoked_allowance_fails.1.json +0 -292
  86. package/contracts/agentrail/test_snapshots/test/test_spend_with_protocol_fee.1.json +0 -286
  87. package/contracts/agentrail/test_snapshots/test/test_spend_zero_amount_fails.1.json +0 -250
  88. package/contracts/agentrail/test_snapshots/test/test_unpause_restores_spend_operations.1.json +0 -370
  89. package/contracts/agentrail/test_snapshots/test/test_zero_protocol_fee_spend.1.json +0 -298
  90. package/deployment.testnet.json +0 -15
  91. package/docs/assets/favicon.png +0 -0
  92. package/docs/assets/logo.png +0 -0
  93. package/docs/index.html +0 -840
  94. package/scripts/demo-agent.ts +0 -52
  95. package/scripts/deploy-testnet.ts +0 -228
  96. package/scripts/security-audit.mjs +0 -159
  97. package/src/cli/sandbox.ts +0 -127
  98. package/src/index.ts +0 -11
  99. package/src/lib/micro-stream.ts +0 -52
  100. package/src/lib/proof-of-task.ts +0 -39
  101. package/src/lib/scoped-allowance.ts +0 -112
  102. package/src/lib/ttl-keeper.ts +0 -44
  103. package/src/sdk/agent-client.ts +0 -66
  104. package/src/types.ts +0 -78
  105. package/tests/agent-client.test.ts +0 -62
  106. package/tests/cli.test.ts +0 -68
  107. package/tests/micro-stream.test.ts +0 -38
  108. package/tests/proof-of-task.test.ts +0 -78
  109. package/tests/scoped-allowance.test.ts +0 -135
  110. package/tests/security-audit.test.ts +0 -76
  111. package/tests/ttl-keeper.test.ts +0 -36
  112. package/tsconfig.json +0 -16
  113. package/vitest.config.ts +0 -8
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AnomalyCircuitBreaker = void 0;
4
+ /**
5
+ * Anomaly Spending Detection & Circuit Breaker Engine.
6
+ * Tracks moving-window transaction frequency, burst intervals, and cumulative volume
7
+ * per allowance and automatically pauses allowances when anomalous behavior is detected.
8
+ */
9
+ class AnomalyCircuitBreaker {
10
+ config;
11
+ records = new Map();
12
+ constructor(config) {
13
+ if (config.windowSeconds <= 0) {
14
+ throw new Error("windowSeconds must be strictly greater than zero.");
15
+ }
16
+ if (config.maxTransactionsInWindow < 1) {
17
+ throw new Error("maxTransactionsInWindow must be at least 1.");
18
+ }
19
+ this.config = { ...config };
20
+ }
21
+ /**
22
+ * Evaluate an incoming SpendRequest against moving-window anomaly rules.
23
+ * If a rule is violated, trips the circuit breaker to OPEN and sets `allowance.active = false`.
24
+ */
25
+ evaluateAndRecord(allowance, request) {
26
+ const entry = this.getOrInitEntry(allowance.id);
27
+ const now = request.timestamp;
28
+ // Check if already tripped (and whether cooldown has elapsed)
29
+ if (entry.state === "OPEN") {
30
+ if (this.config.cooldownSeconds !== undefined &&
31
+ entry.trippedAt !== undefined &&
32
+ now - entry.trippedAt >= this.config.cooldownSeconds) {
33
+ this.reset(allowance.id, allowance);
34
+ }
35
+ else {
36
+ return {
37
+ allowed: false,
38
+ code: "CIRCUIT_OPEN",
39
+ reason: entry.tripReason ??
40
+ `Circuit breaker is OPEN for allowance ${allowance.id}.`,
41
+ status: this.buildStatus(allowance.id, entry, now),
42
+ };
43
+ }
44
+ }
45
+ // Prune events outside the sliding window [now - windowSeconds, now]
46
+ this.pruneWindow(entry, now);
47
+ // 1. Check rapid-succession burst interval
48
+ const lastEvent = entry.events[entry.events.length - 1];
49
+ if (this.config.minIntervalSeconds !== undefined &&
50
+ lastEvent !== undefined &&
51
+ now - lastEvent.timestamp < this.config.minIntervalSeconds) {
52
+ return this.trip(allowance, entry, now, "CIRCUIT_TRIPPED_RAPID_BURST", `Rapid succession withdrawal detected (${now - lastEvent.timestamp}s < ${this.config.minIntervalSeconds}s minimum interval).`);
53
+ }
54
+ // 2. Check moving-window transaction count threshold
55
+ if (entry.events.length + 1 > this.config.maxTransactionsInWindow) {
56
+ return this.trip(allowance, entry, now, "CIRCUIT_TRIPPED_FREQUENCY", `Moving-window transaction count (${entry.events.length + 1}) exceeded maxTransactionsInWindow (${this.config.maxTransactionsInWindow}) within ${this.config.windowSeconds}s.`);
57
+ }
58
+ // 3. Check moving-window cumulative stroop volume
59
+ const currentVolume = entry.events.reduce((acc, ev) => acc + ev.amountStroops, 0n);
60
+ if (this.config.maxVolumeStroopsInWindow !== undefined &&
61
+ currentVolume + request.amountStroops > this.config.maxVolumeStroopsInWindow) {
62
+ return this.trip(allowance, entry, now, "CIRCUIT_TRIPPED_WINDOW_VOLUME", `Moving-window spend volume (${currentVolume + request.amountStroops} stroops) exceeded maxVolumeStroopsInWindow (${this.config.maxVolumeStroopsInWindow} stroops).`);
63
+ }
64
+ // Record normal spend event
65
+ entry.events.push({
66
+ timestamp: now,
67
+ amountStroops: request.amountStroops,
68
+ });
69
+ return {
70
+ allowed: true,
71
+ code: "CIRCUIT_CLOSED",
72
+ status: this.buildStatus(allowance.id, entry, now),
73
+ };
74
+ }
75
+ /**
76
+ * Manually reset a tripped circuit breaker back to CLOSED and optionally reactivate the allowance.
77
+ */
78
+ reset(allowanceId, allowance) {
79
+ const entry = this.getOrInitEntry(allowanceId);
80
+ entry.state = "CLOSED";
81
+ entry.trippedAt = undefined;
82
+ entry.tripReason = undefined;
83
+ entry.events = [];
84
+ if (allowance && allowance.id === allowanceId) {
85
+ allowance.active = true;
86
+ }
87
+ return this.buildStatus(allowanceId, entry, Math.floor(Date.now() / 1000));
88
+ }
89
+ /**
90
+ * Inspect current circuit breaker status for an allowance at a given timestamp.
91
+ */
92
+ getStatus(allowanceId, currentTimestamp = Math.floor(Date.now() / 1000)) {
93
+ const entry = this.getOrInitEntry(allowanceId);
94
+ this.pruneWindow(entry, currentTimestamp);
95
+ return this.buildStatus(allowanceId, entry, currentTimestamp);
96
+ }
97
+ getOrInitEntry(allowanceId) {
98
+ let entry = this.records.get(allowanceId);
99
+ if (!entry) {
100
+ entry = { state: "CLOSED", events: [] };
101
+ this.records.set(allowanceId, entry);
102
+ }
103
+ return entry;
104
+ }
105
+ pruneWindow(entry, now) {
106
+ const cutoff = now - this.config.windowSeconds;
107
+ entry.events = entry.events.filter((ev) => ev.timestamp > cutoff);
108
+ }
109
+ trip(allowance, entry, now, code, reason) {
110
+ entry.state = "OPEN";
111
+ entry.trippedAt = now;
112
+ entry.tripReason = reason;
113
+ allowance.active = false;
114
+ return {
115
+ allowed: false,
116
+ code,
117
+ reason,
118
+ status: this.buildStatus(allowance.id, entry, now),
119
+ };
120
+ }
121
+ buildStatus(allowanceId, entry, now) {
122
+ this.pruneWindow(entry, now);
123
+ const windowVolumeStroops = entry.events.reduce((acc, ev) => acc + ev.amountStroops, 0n);
124
+ const lastEvent = entry.events[entry.events.length - 1];
125
+ return {
126
+ allowanceId,
127
+ state: entry.state,
128
+ trippedAt: entry.trippedAt,
129
+ tripReason: entry.tripReason,
130
+ windowTransactionCount: entry.events.length,
131
+ windowVolumeStroops,
132
+ lastSpendTimestamp: lastEvent?.timestamp,
133
+ };
134
+ }
135
+ }
136
+ exports.AnomalyCircuitBreaker = AnomalyCircuitBreaker;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * AgentRail - Conditional Escrow & Proof-of-Task Protocol
3
+ *
4
+ * Directly resolves the #1 open problem in x402 AI payments:
5
+ * "Decentralized delivery verification & refund protection"
6
+ *
7
+ * Prevents "pay-for-garbage" failure modes:
8
+ * 1. Client locks funds in conditional escrow with expected task commitment.
9
+ * 2. Worker executes task and submits output payload + nonce.
10
+ * 3. Funds are released ONLY if cryptographic commitment matches.
11
+ * 4. Automatic 100% refund is unlocked if worker fails or deadline expires.
12
+ */
13
+ import type { EscrowTask, ProofOfTaskSubmission } from "../types.js";
14
+ import { computeTaskCommitment, verifyTaskProof } from "./proof-of-task.js";
15
+ export { computeTaskCommitment, verifyTaskProof };
16
+ export type { EscrowTask, ProofOfTaskSubmission };
17
+ export interface EscrowSettlementResult {
18
+ ok: boolean;
19
+ code: "FULFILLED" | "INVALID_PROOF" | "EXPIRED" | "REFUNDED" | "ALREADY_SETTLED";
20
+ receiptHash?: string;
21
+ refundStroops?: bigint;
22
+ message: string;
23
+ }
24
+ export declare class ConditionalEscrowManager {
25
+ readonly tokenContractId: string;
26
+ private escrows;
27
+ private receipts;
28
+ constructor(tokenContractId?: string);
29
+ /**
30
+ * Create a new conditional escrow for an autonomous AI task.
31
+ */
32
+ createEscrow(taskId: string, payerPublicKey: string, agentWorkerPublicKey: string, rewardStroops: bigint, expectedOutputPayload: string, expectedNonce: string, ttlSeconds?: number): EscrowTask;
33
+ /**
34
+ * Worker submits proof of task. If cryptographic commitment matches, payment is released.
35
+ */
36
+ fulfillTask(submission: ProofOfTaskSubmission, onChainTxHash: string, currentTimestamp?: number): EscrowSettlementResult;
37
+ /**
38
+ * Payer claims 100% refund if task deadline expired without verified proof.
39
+ */
40
+ claimRefund(taskId: string, currentTimestamp?: number): EscrowSettlementResult;
41
+ getTask(taskId: string): EscrowTask | null;
42
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ /**
3
+ * AgentRail - Conditional Escrow & Proof-of-Task Protocol
4
+ *
5
+ * Directly resolves the #1 open problem in x402 AI payments:
6
+ * "Decentralized delivery verification & refund protection"
7
+ *
8
+ * Prevents "pay-for-garbage" failure modes:
9
+ * 1. Client locks funds in conditional escrow with expected task commitment.
10
+ * 2. Worker executes task and submits output payload + nonce.
11
+ * 3. Funds are released ONLY if cryptographic commitment matches.
12
+ * 4. Automatic 100% refund is unlocked if worker fails or deadline expires.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ConditionalEscrowManager = exports.verifyTaskProof = exports.computeTaskCommitment = void 0;
16
+ const proof_of_task_js_1 = require("./proof-of-task.js");
17
+ Object.defineProperty(exports, "computeTaskCommitment", { enumerable: true, get: function () { return proof_of_task_js_1.computeTaskCommitment; } });
18
+ Object.defineProperty(exports, "verifyTaskProof", { enumerable: true, get: function () { return proof_of_task_js_1.verifyTaskProof; } });
19
+ const receipts_js_1 = require("./receipts.js");
20
+ class ConditionalEscrowManager {
21
+ tokenContractId;
22
+ escrows = new Map();
23
+ receipts = new Map();
24
+ constructor(tokenContractId = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75") {
25
+ this.tokenContractId = tokenContractId;
26
+ }
27
+ /**
28
+ * Create a new conditional escrow for an autonomous AI task.
29
+ */
30
+ createEscrow(taskId, payerPublicKey, agentWorkerPublicKey, rewardStroops, expectedOutputPayload, expectedNonce, ttlSeconds = 3600 // 1 hour default SLA
31
+ ) {
32
+ const taskCommitmentHash = (0, proof_of_task_js_1.computeTaskCommitment)(expectedOutputPayload, expectedNonce);
33
+ const now = Math.floor(Date.now() / 1000);
34
+ const task = {
35
+ taskId,
36
+ payerPublicKey,
37
+ agentWorkerPublicKey,
38
+ rewardStroops,
39
+ taskCommitmentHash,
40
+ expiresAt: now + ttlSeconds,
41
+ status: "pending",
42
+ };
43
+ this.escrows.set(taskId, task);
44
+ return task;
45
+ }
46
+ /**
47
+ * Worker submits proof of task. If cryptographic commitment matches, payment is released.
48
+ */
49
+ fulfillTask(submission, onChainTxHash, currentTimestamp = Math.floor(Date.now() / 1000)) {
50
+ const task = this.escrows.get(submission.taskId);
51
+ if (!task) {
52
+ return { ok: false, code: "ALREADY_SETTLED", message: `Task '${submission.taskId}' not found` };
53
+ }
54
+ const verification = (0, proof_of_task_js_1.verifyTaskProof)(task, submission, currentTimestamp);
55
+ if (!verification.ok) {
56
+ return {
57
+ ok: false,
58
+ code: "INVALID_PROOF",
59
+ message: verification.reason || "Proof verification failed",
60
+ };
61
+ }
62
+ // Mark fulfilled
63
+ task.status = "fulfilled";
64
+ // Generate cryptographic receipt
65
+ const receipt = (0, receipts_js_1.buildSpendReceipt)({
66
+ allowanceId: `escrow-${task.taskId}`,
67
+ agentPublicKey: task.payerPublicKey,
68
+ destination: task.agentWorkerPublicKey,
69
+ amountStroops: task.rewardStroops,
70
+ timestamp: currentTimestamp,
71
+ }, {
72
+ ok: true,
73
+ code: "PROOF_OF_TASK_FULFILLED",
74
+ message: `Task ${task.taskId} verified & settled conditionally`,
75
+ spentStroops: task.rewardStroops,
76
+ feeStroops: 100n,
77
+ netStroops: task.rewardStroops,
78
+ remainingStroops: 0n,
79
+ }, {
80
+ contractId: this.tokenContractId,
81
+ txHash: onChainTxHash,
82
+ });
83
+ const receiptHash = (0, receipts_js_1.hashReceipt)(receipt);
84
+ this.receipts.set(task.taskId, receiptHash);
85
+ return {
86
+ ok: true,
87
+ code: "FULFILLED",
88
+ receiptHash,
89
+ message: "Proof verified successfully. Escrow funds released to worker.",
90
+ };
91
+ }
92
+ /**
93
+ * Payer claims 100% refund if task deadline expired without verified proof.
94
+ */
95
+ claimRefund(taskId, currentTimestamp = Math.floor(Date.now() / 1000)) {
96
+ const task = this.escrows.get(taskId);
97
+ if (!task) {
98
+ return { ok: false, code: "ALREADY_SETTLED", message: `Task '${taskId}' not found` };
99
+ }
100
+ if (task.status !== "pending") {
101
+ return {
102
+ ok: false,
103
+ code: "ALREADY_SETTLED",
104
+ message: `Task is already ${task.status}`,
105
+ };
106
+ }
107
+ if (currentTimestamp <= task.expiresAt) {
108
+ return {
109
+ ok: false,
110
+ code: "INVALID_PROOF",
111
+ message: "Escrow deadline has not yet expired. Worker still has active SLA window.",
112
+ };
113
+ }
114
+ task.status = "refunded";
115
+ return {
116
+ ok: true,
117
+ code: "REFUNDED",
118
+ refundStroops: task.rewardStroops,
119
+ message: `Task expired without valid proof. ${task.rewardStroops} Stroops refunded to payer.`,
120
+ };
121
+ }
122
+ getTask(taskId) {
123
+ return this.escrows.get(taskId) || null;
124
+ }
125
+ }
126
+ exports.ConditionalEscrowManager = ConditionalEscrowManager;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * AgentRail - Model Context Protocol (MCP) Action Server
3
+ *
4
+ * Provides production-ready MCP tools for LLMs (Claude, Gemini, Cursor, LangChain)
5
+ * to autonomously inspect balances, discover peer agents, enforce scoped allowances,
6
+ * and settle x402 micropayments natively on Stellar Soroban.
7
+ */
8
+ import { z } from "zod";
9
+ import { AgentRegistry } from "./agent-registry.js";
10
+ import { X402Gateway } from "./x402-gateway.js";
11
+ import { ScopedAllowance } from "../types.js";
12
+ export interface McpToolDefinition {
13
+ name: string;
14
+ description: string;
15
+ inputSchema: z.ZodTypeAny;
16
+ handler: (args: any) => Promise<any> | any;
17
+ }
18
+ export declare class AgentRailMcpServer {
19
+ private readonly registry;
20
+ private readonly defaultGateway?;
21
+ private tools;
22
+ private allowances;
23
+ constructor(registry: AgentRegistry, defaultGateway?: X402Gateway | undefined);
24
+ registerAllowance(allowance: ScopedAllowance): void;
25
+ private registerCoreTools;
26
+ registerTool(tool: McpToolDefinition): void;
27
+ getTools(): McpToolDefinition[];
28
+ executeTool(name: string, args: any): Promise<any>;
29
+ }
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ /**
3
+ * AgentRail - Model Context Protocol (MCP) Action Server
4
+ *
5
+ * Provides production-ready MCP tools for LLMs (Claude, Gemini, Cursor, LangChain)
6
+ * to autonomously inspect balances, discover peer agents, enforce scoped allowances,
7
+ * and settle x402 micropayments natively on Stellar Soroban.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.AgentRailMcpServer = void 0;
11
+ const zod_1 = require("zod");
12
+ const scoped_allowance_js_1 = require("./scoped-allowance.js");
13
+ class AgentRailMcpServer {
14
+ registry;
15
+ defaultGateway;
16
+ tools = new Map();
17
+ allowances = new Map();
18
+ constructor(registry, defaultGateway) {
19
+ this.registry = registry;
20
+ this.defaultGateway = defaultGateway;
21
+ this.registerCoreTools();
22
+ }
23
+ registerAllowance(allowance) {
24
+ this.allowances.set(allowance.id, allowance);
25
+ }
26
+ registerCoreTools() {
27
+ // Tool 1: Discover Agent Services
28
+ this.registerTool({
29
+ name: "agentrail_discover_services",
30
+ description: "Discover peer AI agents and tools by tag, keyword, or max price on Stellar.",
31
+ inputSchema: zod_1.z.object({
32
+ tag: zod_1.z.string().optional().describe("Category tag (e.g., 'ocr', 'finance', 'research')"),
33
+ keyword: zod_1.z.string().optional().describe("Search term in title or description"),
34
+ maxCostStroops: zod_1.z.string().optional().describe("Maximum cost in Stroops (1 USDC = 10,000,000 Stroops)"),
35
+ }),
36
+ handler: (args) => {
37
+ const results = this.registry.discover({
38
+ tag: args.tag,
39
+ keyword: args.keyword,
40
+ maxCostStroops: args.maxCostStroops ? BigInt(args.maxCostStroops) : undefined,
41
+ });
42
+ return {
43
+ count: results.length,
44
+ services: results.map(r => ({
45
+ serviceId: r.service.serviceId,
46
+ name: r.service.name,
47
+ costUSDC: (Number(r.service.costStroops) / 1e7).toFixed(4),
48
+ costStroops: r.service.costStroops.toString(),
49
+ agentPublicKey: r.agentPublicKey,
50
+ endpointUrl: r.service.endpointUrl,
51
+ tags: r.service.tags,
52
+ reputation: r.reputationScore,
53
+ })),
54
+ };
55
+ },
56
+ });
57
+ // Tool 2: Register Agent Capability
58
+ this.registerTool({
59
+ name: "agentrail_register_service",
60
+ description: "Register an autonomous service capability to the decentralized AgentRail registry.",
61
+ inputSchema: zod_1.z.object({
62
+ agentPublicKey: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
63
+ serviceId: zod_1.z.string().min(3),
64
+ name: zod_1.z.string().min(2),
65
+ description: zod_1.z.string(),
66
+ tags: zod_1.z.array(zod_1.z.string()),
67
+ endpointUrl: zod_1.z.string().url(),
68
+ costStroops: zod_1.z.string().describe("Price per invocation in Stroops (e.g. '100000' = 0.01 USDC)"),
69
+ }),
70
+ handler: (args) => {
71
+ const service = {
72
+ serviceId: args.serviceId,
73
+ name: args.name,
74
+ description: args.description,
75
+ tags: args.tags,
76
+ endpointUrl: args.endpointUrl,
77
+ costStroops: BigInt(args.costStroops),
78
+ settlementAsset: "USDC",
79
+ slaLatencyMs: 2000,
80
+ };
81
+ const record = this.registry.registerService(args.agentPublicKey, service);
82
+ return {
83
+ success: true,
84
+ registrationHash: record.registrationHash,
85
+ ttlEpochSeconds: record.ttlEpochSeconds,
86
+ };
87
+ },
88
+ });
89
+ // Tool 3: Check and Enforce Scoped Allowance Spend Guard
90
+ this.registerTool({
91
+ name: "agentrail_evaluate_spend",
92
+ description: "Pre-flight zero-trust security check before spending funds, asserting epoch budget, rate limits, and address-poisoning defense.",
93
+ inputSchema: zod_1.z.object({
94
+ allowanceId: zod_1.z.string(),
95
+ agentPublicKey: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
96
+ destinationAddress: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
97
+ spendStroops: zod_1.z.string(),
98
+ }),
99
+ handler: (args) => {
100
+ const allowance = this.allowances.get(args.allowanceId);
101
+ if (!allowance) {
102
+ return {
103
+ authorized: false,
104
+ code: "ALLOWANCE_NOT_FOUND",
105
+ message: `Allowance '${args.allowanceId}' not registered in MCP context`,
106
+ };
107
+ }
108
+ const request = {
109
+ allowanceId: args.allowanceId,
110
+ agentPublicKey: args.agentPublicKey,
111
+ destination: args.destinationAddress,
112
+ amountStroops: BigInt(args.spendStroops),
113
+ timestamp: Math.floor(Date.now() / 1000),
114
+ };
115
+ const result = (0, scoped_allowance_js_1.verifyAndDeductSpend)(allowance, request);
116
+ return {
117
+ authorized: result.ok,
118
+ code: result.code,
119
+ spentStroops: (result.spentStroops || 0n).toString(),
120
+ remainingBudgetStroops: (result.remainingStroops || 0n).toString(),
121
+ feeStroops: (result.feeStroops || 0n).toString(),
122
+ };
123
+ },
124
+ });
125
+ // Tool 4: Settle x402 Micropayment Challenge
126
+ this.registerTool({
127
+ name: "agentrail_settle_x402_challenge",
128
+ description: "Verify and settle an HTTP 402 challenge with cryptographic proof of payment on Stellar.",
129
+ inputSchema: zod_1.z.object({
130
+ txHash: zod_1.z.string().regex(/^[0-9a-fA-F]{64}$/),
131
+ payerPublicKey: zod_1.z.string().regex(/^G[A-Z2-7]{55}$/),
132
+ amountStroops: zod_1.z.string(),
133
+ nonce: zod_1.z.string(),
134
+ }),
135
+ handler: (args) => {
136
+ if (!this.defaultGateway) {
137
+ throw new Error("No default x402 gateway configured on this MCP server");
138
+ }
139
+ const authPayload = {
140
+ txHash: args.txHash,
141
+ payerPublicKey: args.payerPublicKey,
142
+ amountStroops: args.amountStroops,
143
+ nonce: args.nonce,
144
+ timestamp: Math.floor(Date.now() / 1000),
145
+ };
146
+ return this.defaultGateway.verifyPayment(authPayload);
147
+ },
148
+ });
149
+ }
150
+ registerTool(tool) {
151
+ this.tools.set(tool.name, tool);
152
+ }
153
+ getTools() {
154
+ return Array.from(this.tools.values());
155
+ }
156
+ async executeTool(name, args) {
157
+ const tool = this.tools.get(name);
158
+ if (!tool) {
159
+ throw new Error(`Tool '${name}' not found on AgentRail MCP Server`);
160
+ }
161
+ const validatedArgs = tool.inputSchema.parse(args);
162
+ return tool.handler(validatedArgs);
163
+ }
164
+ }
165
+ exports.AgentRailMcpServer = AgentRailMcpServer;
@@ -0,0 +1,153 @@
1
+ import { z } from "zod";
2
+ import { SpendRequest, SpendResult } from "../types.js";
3
+ /**
4
+ * Opt-in public receipts for AgentRail spends and proof-of-task results.
5
+ *
6
+ * Build a canonical record, hash it, and anchor only the SHA-256 hash to a public
7
+ * Audit Trail node through an injected provider. The record itself never leaves
8
+ * the caller. Anchoring sits outside the payment path: `anchorReceipt` never throws,
9
+ * so a spend or a proof is unaffected when anchoring fails.
10
+ */
11
+ export declare const RECEIPT_VERSION = "agentrail-receipt-v1";
12
+ export declare const RECEIPT_VERIFY_URL = "https://nirium.xyz/verify";
13
+ export declare const SpendReceiptSchema: z.ZodObject<{
14
+ kind: z.ZodLiteral<"spend">;
15
+ version: z.ZodLiteral<"agentrail-receipt-v1">;
16
+ contractId: z.ZodString;
17
+ allowanceId: z.ZodString;
18
+ agentPublicKey: z.ZodString;
19
+ destination: z.ZodEffects<z.ZodString, string, string>;
20
+ amountStroops: z.ZodBigInt;
21
+ feeStroops: z.ZodBigInt;
22
+ netStroops: z.ZodBigInt;
23
+ timestamp: z.ZodNumber;
24
+ txHash: z.ZodOptional<z.ZodString>;
25
+ }, "strip", z.ZodTypeAny, {
26
+ kind: "spend";
27
+ version: "agentrail-receipt-v1";
28
+ contractId: string;
29
+ allowanceId: string;
30
+ agentPublicKey: string;
31
+ destination: string;
32
+ amountStroops: bigint;
33
+ feeStroops: bigint;
34
+ netStroops: bigint;
35
+ timestamp: number;
36
+ txHash?: string | undefined;
37
+ }, {
38
+ kind: "spend";
39
+ version: "agentrail-receipt-v1";
40
+ contractId: string;
41
+ allowanceId: string;
42
+ agentPublicKey: string;
43
+ destination: string;
44
+ amountStroops: bigint;
45
+ feeStroops: bigint;
46
+ netStroops: bigint;
47
+ timestamp: number;
48
+ txHash?: string | undefined;
49
+ }>;
50
+ export declare const TaskProofReceiptSchema: z.ZodObject<{
51
+ kind: z.ZodLiteral<"proof-of-task">;
52
+ version: z.ZodLiteral<"agentrail-receipt-v1">;
53
+ taskId: z.ZodString;
54
+ agentWorkerPublicKey: z.ZodString;
55
+ taskCommitmentHash: z.ZodString;
56
+ verified: z.ZodBoolean;
57
+ reason: z.ZodOptional<z.ZodString>;
58
+ timestamp: z.ZodNumber;
59
+ }, "strip", z.ZodTypeAny, {
60
+ kind: "proof-of-task";
61
+ version: "agentrail-receipt-v1";
62
+ timestamp: number;
63
+ taskId: string;
64
+ agentWorkerPublicKey: string;
65
+ taskCommitmentHash: string;
66
+ verified: boolean;
67
+ reason?: string | undefined;
68
+ }, {
69
+ kind: "proof-of-task";
70
+ version: "agentrail-receipt-v1";
71
+ timestamp: number;
72
+ taskId: string;
73
+ agentWorkerPublicKey: string;
74
+ taskCommitmentHash: string;
75
+ verified: boolean;
76
+ reason?: string | undefined;
77
+ }>;
78
+ export type SpendReceipt = z.infer<typeof SpendReceiptSchema>;
79
+ export type TaskProofReceipt = z.infer<typeof TaskProofReceiptSchema>;
80
+ export type Receipt = SpendReceipt | TaskProofReceipt;
81
+ /**
82
+ * Build a spend receipt from a successful `verifyAndDeductSpend` result.
83
+ * Throws if the spend was rejected (there is nothing to attest) or an input is invalid.
84
+ */
85
+ export declare function buildSpendReceipt(request: SpendRequest, result: SpendResult, extras: {
86
+ contractId: string;
87
+ txHash?: string;
88
+ }): SpendReceipt;
89
+ /**
90
+ * Build a proof-of-task receipt from the output of `verifyTaskProof`.
91
+ * Records the commitment hash and the verification result, never the raw output or nonce.
92
+ */
93
+ export declare function buildTaskProofReceipt(input: {
94
+ taskId: string;
95
+ agentWorkerPublicKey: string;
96
+ taskCommitmentHash: string;
97
+ verification: {
98
+ ok: boolean;
99
+ reason?: string;
100
+ };
101
+ timestamp: number;
102
+ }): TaskProofReceipt;
103
+ /** Deterministic JSON: sorted keys, bigint as a decimal string, undefined fields dropped. */
104
+ export declare function canonicalizeReceipt(receipt: Receipt): string;
105
+ /** SHA-256 hex of the canonical receipt. This is the only value that leaves AgentRail. */
106
+ export declare function hashReceipt(receipt: Receipt): string;
107
+ /** A service that anchors a sha-256 hash and returns a content id (see `createAuditTrailProvider`). */
108
+ export interface ReceiptAnchorProvider {
109
+ anchor(request: {
110
+ hash: string;
111
+ tag?: string;
112
+ txHash?: string;
113
+ network?: string;
114
+ agent?: {
115
+ id?: string;
116
+ key: string;
117
+ signature: string;
118
+ };
119
+ }): Promise<{
120
+ cid: string;
121
+ contentSha256: string;
122
+ gatewayUrl?: string;
123
+ anchoredAt?: string;
124
+ attestedBy?: string;
125
+ }>;
126
+ }
127
+ export type AnchorOutcome = {
128
+ ok: true;
129
+ cid: string;
130
+ contentSha256: string;
131
+ verifyUrl: string;
132
+ gatewayUrl?: string;
133
+ anchoredAt?: string;
134
+ attestedBy?: string;
135
+ } | {
136
+ ok: false;
137
+ contentSha256: string;
138
+ error: string;
139
+ };
140
+ export interface AnchorOptions {
141
+ tag?: string;
142
+ network?: string;
143
+ agentId?: string;
144
+ signerKeypair?: {
145
+ publicKey(): string;
146
+ sign(data: Buffer): Buffer;
147
+ };
148
+ }
149
+ /**
150
+ * Anchor a receipt's hash through `provider`. Never throws: a failure comes back as
151
+ * `{ ok: false }` so callers can log it and carry on.
152
+ */
153
+ export declare function anchorReceipt(receipt: Receipt, provider: ReceiptAnchorProvider, options?: AnchorOptions): Promise<AnchorOutcome>;