@sparkysolutions/agentrail 0.0.0-stage → 0.1.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +249 -3
  3. package/dist/cli/mcp-stdio.d.ts +8 -0
  4. package/dist/cli/mcp-stdio.js +454 -0
  5. package/dist/cli/pipeline.d.ts +40 -0
  6. package/dist/cli/pipeline.js +114 -0
  7. package/dist/cli/sandbox.d.ts +55 -0
  8. package/dist/cli/sandbox.js +107 -0
  9. package/dist/index.d.ts +23 -0
  10. package/dist/index.js +39 -0
  11. package/dist/lib/agent-badge-issuer.d.ts +36 -0
  12. package/dist/lib/agent-badge-issuer.js +166 -0
  13. package/dist/lib/agent-registry.d.ts +136 -0
  14. package/dist/lib/agent-registry.js +124 -0
  15. package/dist/lib/agenthustle-pipeline.d.ts +68 -0
  16. package/dist/lib/agenthustle-pipeline.js +143 -0
  17. package/dist/lib/agentpass-pipeline.d.ts +44 -0
  18. package/dist/lib/agentpass-pipeline.js +84 -0
  19. package/dist/lib/audit-trail-provider.d.ts +24 -0
  20. package/dist/lib/audit-trail-provider.js +60 -0
  21. package/dist/lib/axis-clob-provider.d.ts +50 -0
  22. package/dist/lib/axis-clob-provider.js +150 -0
  23. package/dist/lib/circuit-breaker.d.ts +60 -0
  24. package/dist/lib/circuit-breaker.js +136 -0
  25. package/dist/lib/conditional-escrow.d.ts +42 -0
  26. package/dist/lib/conditional-escrow.js +126 -0
  27. package/dist/lib/mcp-server.d.ts +29 -0
  28. package/dist/lib/mcp-server.js +165 -0
  29. package/dist/lib/micro-stream.d.ts +21 -0
  30. package/dist/lib/micro-stream.js +41 -0
  31. package/dist/lib/proof-of-task.d.ts +12 -0
  32. package/dist/lib/proof-of-task.js +32 -0
  33. package/dist/lib/receipts.d.ts +153 -0
  34. package/dist/lib/receipts.js +173 -0
  35. package/dist/lib/reflector-oracle-adapter.d.ts +44 -0
  36. package/dist/lib/reflector-oracle-adapter.js +173 -0
  37. package/dist/lib/scoped-allowance.d.ts +15 -0
  38. package/dist/lib/scoped-allowance.js +116 -0
  39. package/dist/lib/ttl-keeper.d.ts +10 -0
  40. package/dist/lib/ttl-keeper.js +36 -0
  41. package/dist/lib/universal-adapters.d.ts +42 -0
  42. package/dist/lib/universal-adapters.js +69 -0
  43. package/dist/lib/x402-gateway.d.ts +86 -0
  44. package/dist/lib/x402-gateway.js +128 -0
  45. package/dist/lib/x402-pipeline.d.ts +51 -0
  46. package/dist/lib/x402-pipeline.js +105 -0
  47. package/dist/sdk/agent-client.d.ts +26 -0
  48. package/dist/sdk/agent-client.js +53 -0
  49. package/dist/types.d.ts +181 -0
  50. package/dist/types.js +5 -0
  51. package/glama.json +12 -0
  52. package/package.json +56 -6
  53. package/smithery.json +43 -0
  54. package/smithery.yaml +29 -0
@@ -0,0 +1,60 @@
1
+ import { ScopedAllowance, SpendRequest } from "../types.js";
2
+ /**
3
+ * Configuration rules for the anomaly spending detection & circuit breaker module.
4
+ */
5
+ export interface CircuitBreakerConfig {
6
+ /** Sliding time window duration in seconds (e.g., 60s). */
7
+ windowSeconds: number;
8
+ /** Maximum number of spend transactions permitted within the sliding window before tripping. */
9
+ maxTransactionsInWindow: number;
10
+ /** Optional minimum interval in seconds between consecutive withdrawals to prevent burst draining. */
11
+ minIntervalSeconds?: number;
12
+ /** Optional maximum cumulative stroops allowed within the sliding window. */
13
+ maxVolumeStroopsInWindow?: bigint;
14
+ /** Optional cooldown duration in seconds after which a tripped breaker can auto-recover. */
15
+ cooldownSeconds?: number;
16
+ }
17
+ /**
18
+ * Snapshot of the circuit breaker's state for an allowance.
19
+ */
20
+ export interface CircuitBreakerStatus {
21
+ allowanceId: string;
22
+ state: "CLOSED" | "OPEN";
23
+ trippedAt?: number;
24
+ tripReason?: string;
25
+ windowTransactionCount: number;
26
+ windowVolumeStroops: bigint;
27
+ lastSpendTimestamp?: number;
28
+ }
29
+ /**
30
+ * Anomaly Spending Detection & Circuit Breaker Engine.
31
+ * Tracks moving-window transaction frequency, burst intervals, and cumulative volume
32
+ * per allowance and automatically pauses allowances when anomalous behavior is detected.
33
+ */
34
+ export declare class AnomalyCircuitBreaker {
35
+ private readonly config;
36
+ private readonly records;
37
+ constructor(config: CircuitBreakerConfig);
38
+ /**
39
+ * Evaluate an incoming SpendRequest against moving-window anomaly rules.
40
+ * If a rule is violated, trips the circuit breaker to OPEN and sets `allowance.active = false`.
41
+ */
42
+ evaluateAndRecord(allowance: ScopedAllowance, request: SpendRequest): {
43
+ allowed: boolean;
44
+ code: "CIRCUIT_CLOSED" | "CIRCUIT_TRIPPED_FREQUENCY" | "CIRCUIT_TRIPPED_RAPID_BURST" | "CIRCUIT_TRIPPED_WINDOW_VOLUME" | "CIRCUIT_OPEN";
45
+ reason?: string;
46
+ status: CircuitBreakerStatus;
47
+ };
48
+ /**
49
+ * Manually reset a tripped circuit breaker back to CLOSED and optionally reactivate the allowance.
50
+ */
51
+ reset(allowanceId: string, allowance?: ScopedAllowance): CircuitBreakerStatus;
52
+ /**
53
+ * Inspect current circuit breaker status for an allowance at a given timestamp.
54
+ */
55
+ getStatus(allowanceId: string, currentTimestamp?: number): CircuitBreakerStatus;
56
+ private getOrInitEntry;
57
+ private pruneWindow;
58
+ private trip;
59
+ private buildStatus;
60
+ }
@@ -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,21 @@
1
+ /**
2
+ * Real-time micro-payment streaming calculations for LLM inference, API usage, and continuous work.
3
+ */
4
+ export interface TokenPricingRate {
5
+ /** Cost in stroops per 1,000 prompt tokens (1 USDC = 10,000,000 stroops). */
6
+ promptStroopsPer1k: bigint;
7
+ /** Cost in stroops per 1,000 completion tokens. */
8
+ completionStroopsPer1k: bigint;
9
+ }
10
+ /**
11
+ * Calculate the exact stroop amount for given token usage.
12
+ */
13
+ export declare function calculateTokenCost(promptTokens: number, completionTokens: number, rates: TokenPricingRate): bigint;
14
+ /**
15
+ * Convert human-readable decimal USDC amount string to integer stroops (7 decimals).
16
+ */
17
+ export declare function usdcToStroops(usdcAmount: string): bigint;
18
+ /**
19
+ * Convert stroops integer to human-readable 7-decimal USDC string.
20
+ */
21
+ export declare function stroopsToUsdc(stroops: bigint): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * Real-time micro-payment streaming calculations for LLM inference, API usage, and continuous work.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.calculateTokenCost = calculateTokenCost;
7
+ exports.usdcToStroops = usdcToStroops;
8
+ exports.stroopsToUsdc = stroopsToUsdc;
9
+ /**
10
+ * Calculate the exact stroop amount for given token usage.
11
+ */
12
+ function calculateTokenCost(promptTokens, completionTokens, rates) {
13
+ if (promptTokens < 0 || completionTokens < 0) {
14
+ throw new Error("Token counts must be non-negative");
15
+ }
16
+ const promptCost = (BigInt(promptTokens) * rates.promptStroopsPer1k) / 1000n;
17
+ const completionCost = (BigInt(completionTokens) * rates.completionStroopsPer1k) / 1000n;
18
+ return promptCost + completionCost;
19
+ }
20
+ /**
21
+ * Convert human-readable decimal USDC amount string to integer stroops (7 decimals).
22
+ */
23
+ function usdcToStroops(usdcAmount) {
24
+ const parts = usdcAmount.trim().split(".");
25
+ if (parts.length > 2)
26
+ throw new Error("Invalid decimal format");
27
+ const whole = BigInt(parts[0] || "0");
28
+ const fractionStr = (parts[1] || "").slice(0, 7).padEnd(7, "0");
29
+ const fraction = BigInt(fractionStr);
30
+ return whole * 10000000n + fraction;
31
+ }
32
+ /**
33
+ * Convert stroops integer to human-readable 7-decimal USDC string.
34
+ */
35
+ function stroopsToUsdc(stroops) {
36
+ if (stroops < 0n)
37
+ throw new Error("Stroops must be non-negative");
38
+ const whole = stroops / 10000000n;
39
+ const fraction = stroops % 10000000n;
40
+ return `${whole}.${fraction.toString().padStart(7, "0")}`;
41
+ }
@@ -0,0 +1,12 @@
1
+ import { EscrowTask, ProofOfTaskSubmission } from "../types.js";
2
+ /**
3
+ * Compute the canonical SHA-256 commitment hash for a task output and nonce.
4
+ */
5
+ export declare function computeTaskCommitment(outputPayload: string, nonce: string): string;
6
+ /**
7
+ * Verify an autonomous AI agent's submitted proof against the on-chain task escrow.
8
+ */
9
+ export declare function verifyTaskProof(task: EscrowTask, submission: ProofOfTaskSubmission, currentTimestamp: number): {
10
+ ok: boolean;
11
+ reason?: string;
12
+ };
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeTaskCommitment = computeTaskCommitment;
4
+ exports.verifyTaskProof = verifyTaskProof;
5
+ const node_crypto_1 = require("node:crypto");
6
+ /**
7
+ * Compute the canonical SHA-256 commitment hash for a task output and nonce.
8
+ */
9
+ function computeTaskCommitment(outputPayload, nonce) {
10
+ return (0, node_crypto_1.createHash)("sha256")
11
+ .update(`${outputPayload}:${nonce}`, "utf8")
12
+ .digest("hex");
13
+ }
14
+ /**
15
+ * Verify an autonomous AI agent's submitted proof against the on-chain task escrow.
16
+ */
17
+ function verifyTaskProof(task, submission, currentTimestamp) {
18
+ if (task.status !== "pending") {
19
+ return { ok: false, reason: `Task is not pending (status: ${task.status})` };
20
+ }
21
+ if (submission.agentWorkerPublicKey !== task.agentWorkerPublicKey) {
22
+ return { ok: false, reason: "Proof submitter does not match designated worker key" };
23
+ }
24
+ if (currentTimestamp > task.expiresAt) {
25
+ return { ok: false, reason: "Task escrow deadline has expired; refund available" };
26
+ }
27
+ const computedHash = computeTaskCommitment(submission.outputPayload, submission.nonce);
28
+ if (computedHash !== task.taskCommitmentHash) {
29
+ return { ok: false, reason: "Cryptographic commitment hash mismatch" };
30
+ }
31
+ return { ok: true };
32
+ }