@agent402-dev/pay-mcp 0.4.0 → 0.5.0
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.
- package/README.md +25 -0
- package/dist/bond-job.d.ts +116 -0
- package/dist/bond-job.js +172 -0
- package/dist/bond-sign.d.ts +151 -0
- package/dist/bond-sign.js +258 -0
- package/dist/bond-tx.d.ts +81 -0
- package/dist/bond-tx.js +189 -0
- package/dist/bond.d.ts +188 -0
- package/dist/bond.js +114 -0
- package/dist/history.js +2 -1
- package/dist/server.js +3 -1
- package/dist/spend-lock.d.ts +1 -0
- package/dist/spend-lock.js +8 -0
- package/dist/tools.d.ts +8 -1
- package/dist/tools.js +43 -3
- package/dist/units.js +2 -0
- package/dist/wallet.d.ts +2 -0
- package/dist/wallet.js +6 -1
- package/package.json +2 -1
package/dist/bond.d.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { type RuleDeal } from '@agent402-dev/bond-client/rules';
|
|
2
|
+
import type { AccountsFetcher } from './locks.js';
|
|
3
|
+
export declare const BOND_PROGRAM = "9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK";
|
|
4
|
+
/** sha256("account:Deal")[..8] */
|
|
5
|
+
export declare const DEAL_DISCRIMINATOR: number[];
|
|
6
|
+
declare const OUTCOMES: readonly ["open", "delivered", "buyer_default", "disputed", "seller_default", "cancelled"];
|
|
7
|
+
/** Mints the program accepts on mainnet (symbol, decimals). */
|
|
8
|
+
export declare const BOND_MINTS: Record<string, {
|
|
9
|
+
symbol: string;
|
|
10
|
+
decimals: number;
|
|
11
|
+
}>;
|
|
12
|
+
export interface DealAccount extends RuleDeal {
|
|
13
|
+
seller: string;
|
|
14
|
+
buyer: string;
|
|
15
|
+
mint: string;
|
|
16
|
+
nonce: bigint;
|
|
17
|
+
outcome: (typeof OUTCOMES)[number];
|
|
18
|
+
owedSeller: bigint;
|
|
19
|
+
}
|
|
20
|
+
/** Decodes a Deal account (Anchor layout). Null if the bytes are not a Deal. */
|
|
21
|
+
export declare function decodeDealAccount(data: Uint8Array): DealAccount | null;
|
|
22
|
+
/** Solana clock via the RPC: the Clock sysvar (what the program uses), falling back to getSlot + getBlockTime. */
|
|
23
|
+
export declare function rpcClock(rpcUrl: string, f?: typeof fetch): () => Promise<bigint>;
|
|
24
|
+
export interface BondStatusDeps {
|
|
25
|
+
accounts: AccountsFetcher;
|
|
26
|
+
clock: () => Promise<bigint>;
|
|
27
|
+
wallet?: string | null;
|
|
28
|
+
}
|
|
29
|
+
/** bond_deal_status: facts about one deal account, with amounts in units and times in ISO (Solana clock). */
|
|
30
|
+
export declare function bondDealStatus(d: BondStatusDeps, deal: string): Promise<{
|
|
31
|
+
result: "not_found";
|
|
32
|
+
message: string;
|
|
33
|
+
} | {
|
|
34
|
+
result: "not_a_deal";
|
|
35
|
+
message: string;
|
|
36
|
+
} | {
|
|
37
|
+
outcome: "cancelled" | "delivered" | "buyer_default" | "disputed" | "seller_default";
|
|
38
|
+
owedToSeller: {
|
|
39
|
+
atomic: string;
|
|
40
|
+
display: string;
|
|
41
|
+
};
|
|
42
|
+
note: string;
|
|
43
|
+
asset: {
|
|
44
|
+
mint: string;
|
|
45
|
+
symbol: string;
|
|
46
|
+
decimals: number;
|
|
47
|
+
};
|
|
48
|
+
price: {
|
|
49
|
+
atomic: string;
|
|
50
|
+
display: string;
|
|
51
|
+
};
|
|
52
|
+
sellerBond: {
|
|
53
|
+
atomic: string;
|
|
54
|
+
display: string;
|
|
55
|
+
};
|
|
56
|
+
buyerDeposit: {
|
|
57
|
+
atomic: string;
|
|
58
|
+
display: string;
|
|
59
|
+
};
|
|
60
|
+
balanceToPay: {
|
|
61
|
+
atomic: string;
|
|
62
|
+
display: string;
|
|
63
|
+
};
|
|
64
|
+
openedAt: {
|
|
65
|
+
unix: string;
|
|
66
|
+
iso: string;
|
|
67
|
+
} | null;
|
|
68
|
+
deliverBy: {
|
|
69
|
+
unix: string;
|
|
70
|
+
iso: string;
|
|
71
|
+
} | null;
|
|
72
|
+
sellerMarkedAt: {
|
|
73
|
+
unix: string;
|
|
74
|
+
iso: string;
|
|
75
|
+
} | null;
|
|
76
|
+
buyerConfirmedAt: {
|
|
77
|
+
unix: string;
|
|
78
|
+
iso: string;
|
|
79
|
+
} | null;
|
|
80
|
+
balancePaid: boolean;
|
|
81
|
+
clock: {
|
|
82
|
+
unix: string;
|
|
83
|
+
iso: string;
|
|
84
|
+
} | null;
|
|
85
|
+
yourRole?: string | undefined;
|
|
86
|
+
deal: string;
|
|
87
|
+
program: string;
|
|
88
|
+
seller: string;
|
|
89
|
+
buyer: string;
|
|
90
|
+
result: "settled";
|
|
91
|
+
message?: undefined;
|
|
92
|
+
} | {
|
|
93
|
+
deadlines: {
|
|
94
|
+
lateUntil: {
|
|
95
|
+
unix: string;
|
|
96
|
+
iso: string;
|
|
97
|
+
} | null;
|
|
98
|
+
buyerConfirmOrPayUntil: {
|
|
99
|
+
unix: string;
|
|
100
|
+
iso: string;
|
|
101
|
+
} | null;
|
|
102
|
+
settleableBy: {
|
|
103
|
+
unix: string;
|
|
104
|
+
iso: string;
|
|
105
|
+
} | null;
|
|
106
|
+
};
|
|
107
|
+
lateDeductionIfConfirmed: {
|
|
108
|
+
atomic: string;
|
|
109
|
+
display: string;
|
|
110
|
+
};
|
|
111
|
+
possibleActions: {
|
|
112
|
+
until?: string | undefined;
|
|
113
|
+
action: string;
|
|
114
|
+
who: "seller" | "buyer" | "both" | "anyone";
|
|
115
|
+
}[];
|
|
116
|
+
settlement: {
|
|
117
|
+
now: boolean;
|
|
118
|
+
outcome: import("@agent402-dev/bond-client/rules").Outcome;
|
|
119
|
+
toSeller: {
|
|
120
|
+
atomic: string;
|
|
121
|
+
display: string;
|
|
122
|
+
};
|
|
123
|
+
toBuyer: {
|
|
124
|
+
atomic: string;
|
|
125
|
+
display: string;
|
|
126
|
+
};
|
|
127
|
+
earliest?: undefined;
|
|
128
|
+
note?: undefined;
|
|
129
|
+
} | {
|
|
130
|
+
now: boolean;
|
|
131
|
+
earliest: string | null;
|
|
132
|
+
note: string;
|
|
133
|
+
outcome?: undefined;
|
|
134
|
+
toSeller?: undefined;
|
|
135
|
+
toBuyer?: undefined;
|
|
136
|
+
};
|
|
137
|
+
notes: string[];
|
|
138
|
+
asset: {
|
|
139
|
+
mint: string;
|
|
140
|
+
symbol: string;
|
|
141
|
+
decimals: number;
|
|
142
|
+
};
|
|
143
|
+
price: {
|
|
144
|
+
atomic: string;
|
|
145
|
+
display: string;
|
|
146
|
+
};
|
|
147
|
+
sellerBond: {
|
|
148
|
+
atomic: string;
|
|
149
|
+
display: string;
|
|
150
|
+
};
|
|
151
|
+
buyerDeposit: {
|
|
152
|
+
atomic: string;
|
|
153
|
+
display: string;
|
|
154
|
+
};
|
|
155
|
+
balanceToPay: {
|
|
156
|
+
atomic: string;
|
|
157
|
+
display: string;
|
|
158
|
+
};
|
|
159
|
+
openedAt: {
|
|
160
|
+
unix: string;
|
|
161
|
+
iso: string;
|
|
162
|
+
} | null;
|
|
163
|
+
deliverBy: {
|
|
164
|
+
unix: string;
|
|
165
|
+
iso: string;
|
|
166
|
+
} | null;
|
|
167
|
+
sellerMarkedAt: {
|
|
168
|
+
unix: string;
|
|
169
|
+
iso: string;
|
|
170
|
+
} | null;
|
|
171
|
+
buyerConfirmedAt: {
|
|
172
|
+
unix: string;
|
|
173
|
+
iso: string;
|
|
174
|
+
} | null;
|
|
175
|
+
balancePaid: boolean;
|
|
176
|
+
clock: {
|
|
177
|
+
unix: string;
|
|
178
|
+
iso: string;
|
|
179
|
+
} | null;
|
|
180
|
+
yourRole?: string | undefined;
|
|
181
|
+
deal: string;
|
|
182
|
+
program: string;
|
|
183
|
+
seller: string;
|
|
184
|
+
buyer: string;
|
|
185
|
+
result: "open";
|
|
186
|
+
message?: undefined;
|
|
187
|
+
}>;
|
|
188
|
+
export {};
|
package/dist/bond.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Agent402 Bond, read-only: decode a deal account and explain its deadlines, possible actions and settlement.
|
|
2
|
+
// Never signs. Deadlines and settlement come from the program's rules (ported in @agent402-dev/bond-client/rules);
|
|
3
|
+
// the program on chain is the source of truth.
|
|
4
|
+
import { getBase58Decoder } from '@solana/kit';
|
|
5
|
+
import { buyerDeadline, lateDeduction, possibleActions, settleBy, settleableFrom, settlePreview, t2 } from '@agent402-dev/bond-client/rules';
|
|
6
|
+
import { formatUnits } from './units.js';
|
|
7
|
+
export const BOND_PROGRAM = '9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK';
|
|
8
|
+
/** sha256("account:Deal")[..8] */
|
|
9
|
+
export const DEAL_DISCRIMINATOR = [125, 223, 160, 234, 71, 162, 182, 219];
|
|
10
|
+
const DEAL_SIZE = 8 + 32 * 3 + 8 * 4 + 8 * 6 + 1 + 2 + 1 + 8;
|
|
11
|
+
const OUTCOMES = ['open', 'delivered', 'buyer_default', 'disputed', 'seller_default', 'cancelled'];
|
|
12
|
+
/** Mints the program accepts on mainnet (symbol, decimals). */
|
|
13
|
+
export const BOND_MINTS = {
|
|
14
|
+
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: { symbol: 'USDC', decimals: 6 },
|
|
15
|
+
So11111111111111111111111111111111111111112: { symbol: 'wSOL', decimals: 9 },
|
|
16
|
+
aTbGw3gU5JyJkAdXLj8rYZ3mCXkPbyHjtTAyCX3jQLX: { symbol: 'PREQ', decimals: 6 },
|
|
17
|
+
// devnet USDC (Circle)
|
|
18
|
+
'4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU': { symbol: 'USDC', decimals: 6 },
|
|
19
|
+
};
|
|
20
|
+
/** Decodes a Deal account (Anchor layout). Null if the bytes are not a Deal. */
|
|
21
|
+
export function decodeDealAccount(data) {
|
|
22
|
+
if (data.length < DEAL_SIZE || DEAL_DISCRIMINATOR.some((b, i) => data[i] !== b))
|
|
23
|
+
return null;
|
|
24
|
+
const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
25
|
+
const b58 = getBase58Decoder();
|
|
26
|
+
let o = 8;
|
|
27
|
+
const key = () => b58.decode(data.subarray(o, (o += 32)));
|
|
28
|
+
const u64 = () => { const x = v.getBigUint64(o, true); o += 8; return x; };
|
|
29
|
+
const i64 = () => { const x = v.getBigInt64(o, true); o += 8; return x; };
|
|
30
|
+
const seller = key(), buyer = key(), mint = key();
|
|
31
|
+
const nonce = u64(), price = u64(), sellerBond = u64(), buyerDeposit = u64();
|
|
32
|
+
const deliverBy = i64(), lateWindow = i64(), payWindow = i64(), openedAt = i64(), mark = i64(), confirm = i64();
|
|
33
|
+
const balancePaid = data[o++] === 1;
|
|
34
|
+
o += 2; // bump, vault_bump
|
|
35
|
+
const outcome = OUTCOMES[data[o++]] ?? 'open';
|
|
36
|
+
const owedSeller = u64();
|
|
37
|
+
return {
|
|
38
|
+
seller, buyer, mint, nonce, outcome, owedSeller, openedAt, balancePaid,
|
|
39
|
+
terms: { price, sellerBond, buyerDeposit, deliverBy, lateWindow, payWindow },
|
|
40
|
+
sellerMark: mark === 0n ? null : mark,
|
|
41
|
+
buyerConfirm: confirm === 0n ? null : confirm,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Solana clock via the RPC: the Clock sysvar (what the program uses), falling back to getSlot + getBlockTime. */
|
|
45
|
+
export function rpcClock(rpcUrl, f = fetch) {
|
|
46
|
+
const call = async (method, params) => {
|
|
47
|
+
const r = await f(rpcUrl, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });
|
|
48
|
+
const j = (await r.json());
|
|
49
|
+
if (j.result === undefined || j.result === null)
|
|
50
|
+
throw new Error(`rpc ${method}: ${j.error?.message ?? r.status}`);
|
|
51
|
+
return j.result;
|
|
52
|
+
};
|
|
53
|
+
return async () => {
|
|
54
|
+
try {
|
|
55
|
+
const v = (await call('getAccountInfo', ['SysvarC1ock11111111111111111111111111111111', { encoding: 'base64', commitment: 'confirmed' }]));
|
|
56
|
+
if (v.value) {
|
|
57
|
+
const b = Uint8Array.from(atob(v.value.data[0]), (c) => c.charCodeAt(0));
|
|
58
|
+
if (b.length >= 40)
|
|
59
|
+
return new DataView(b.buffer).getBigInt64(32, true);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch { /* fall back */ }
|
|
63
|
+
return BigInt((await call('getBlockTime', [await call('getSlot', [{ commitment: 'confirmed' }])])));
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const iso = (t) => new Date(Number(t) * 1000).toISOString();
|
|
67
|
+
/** bond_deal_status: facts about one deal account, with amounts in units and times in ISO (Solana clock). */
|
|
68
|
+
export async function bondDealStatus(d, deal) {
|
|
69
|
+
const [acc] = await d.accounts([deal]);
|
|
70
|
+
if (!acc)
|
|
71
|
+
return { result: 'not_found', message: 'No account at this address. A settled deal is closed once both sides have claimed.' };
|
|
72
|
+
if (acc.owner !== BOND_PROGRAM)
|
|
73
|
+
return { result: 'not_a_deal', message: `This account is not owned by the Agent402 Bond program (${BOND_PROGRAM}).` };
|
|
74
|
+
const a = decodeDealAccount(acc.data);
|
|
75
|
+
if (!a)
|
|
76
|
+
return { result: 'not_a_deal', message: 'This account is not an Agent402 Bond deal.' };
|
|
77
|
+
const now = await d.clock();
|
|
78
|
+
const m = BOND_MINTS[a.mint] ?? { symbol: 'tokens', decimals: 0 };
|
|
79
|
+
const amt = (v) => ({ atomic: v.toString(), display: formatUnits(v, m.symbol, m.decimals) });
|
|
80
|
+
const time = (t) => (t === null ? null : { unix: t.toString(), iso: iso(t) });
|
|
81
|
+
const role = d.wallet === a.buyer ? 'buyer' : d.wallet === a.seller ? 'seller' : null;
|
|
82
|
+
const base = {
|
|
83
|
+
deal, program: BOND_PROGRAM, seller: a.seller, buyer: a.buyer, ...(role ? { yourRole: role } : {}),
|
|
84
|
+
asset: { mint: a.mint, symbol: m.symbol, decimals: m.decimals },
|
|
85
|
+
price: amt(a.terms.price), sellerBond: amt(a.terms.sellerBond), buyerDeposit: amt(a.terms.buyerDeposit),
|
|
86
|
+
balanceToPay: amt(a.terms.price - a.terms.buyerDeposit),
|
|
87
|
+
openedAt: time(a.openedAt), deliverBy: time(a.terms.deliverBy),
|
|
88
|
+
sellerMarkedAt: time(a.sellerMark), buyerConfirmedAt: time(a.buyerConfirm), balancePaid: a.balancePaid,
|
|
89
|
+
clock: time(now),
|
|
90
|
+
};
|
|
91
|
+
if (a.outcome !== 'open') {
|
|
92
|
+
return {
|
|
93
|
+
result: 'settled', ...base, outcome: a.outcome,
|
|
94
|
+
owedToSeller: amt(a.owedSeller),
|
|
95
|
+
note: 'Settled. Each side claims its own share (claim_buyer, then claim_seller); anyone may send the claims.',
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const preview = settlePreview(a, now);
|
|
99
|
+
const from = settleableFrom(a, now);
|
|
100
|
+
return {
|
|
101
|
+
result: 'open', ...base,
|
|
102
|
+
deadlines: { lateUntil: time(t2(a.terms)), buyerConfirmOrPayUntil: time(buyerDeadline(a)), settleableBy: time(settleBy(a)) },
|
|
103
|
+
// What the bond loses to lateness if the buyer confirmed now (delivery time = the seller mark, or now)
|
|
104
|
+
lateDeductionIfConfirmed: amt(lateDeduction({ ...a, buyerConfirm: a.buyerConfirm ?? now })),
|
|
105
|
+
possibleActions: possibleActions(a, now).map((x) => ({ action: x.action, who: x.who, ...(x.until !== undefined ? { until: iso(x.until) } : {}) })),
|
|
106
|
+
settlement: preview
|
|
107
|
+
? { now: true, outcome: preview.outcome, toSeller: amt(preview.toSeller), toBuyer: amt(preview.toBuyer) }
|
|
108
|
+
: { now: false, earliest: from === null ? null : iso(from), note: 'Not settleable yet. If nobody acts, settlement opens at "earliest".' },
|
|
109
|
+
notes: [
|
|
110
|
+
'Predicted from the program rules; the program on chain decides. The program does not judge quality; quality disputes are resolved between the parties.',
|
|
111
|
+
'Never send tokens directly to a deal vault: anything beyond the locked amount is paid to the buyer.',
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
}
|
package/dist/history.js
CHANGED
|
@@ -17,7 +17,8 @@ export function jsonlHistory(path, mints) {
|
|
|
17
17
|
// A signed payment counts as spent regardless of result (succeeded, rejected, unknown), to be conservative
|
|
18
18
|
const signedOn = (now) => {
|
|
19
19
|
const day = now.toISOString().slice(0, 10);
|
|
20
|
-
|
|
20
|
+
// Fee-only signatures (amount "0", e.g. settling a bond deal) move no tokens and do not count as payments
|
|
21
|
+
return read().filter((e) => e.signed && e.at.slice(0, 10) === day && e.amount !== '0');
|
|
21
22
|
};
|
|
22
23
|
const usdOf = (xs, usdc) => xs.filter((e) => e.mint === usdc && e.amount).reduce((s, e) => s + Number(e.amount) / 1e6, 0);
|
|
23
24
|
const sumOf = (xs, mint) => (mint ? xs.filter((e) => e.mint === mint && e.amount && /^\d+$/.test(e.amount)).reduce((s, e) => s + BigInt(e.amount), 0n) : 0n);
|
package/dist/server.js
CHANGED
|
@@ -12,6 +12,8 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
|
12
12
|
import { historyToCsv } from './csv.js';
|
|
13
13
|
import { jsonlHistory } from './history.js';
|
|
14
14
|
import { rpcAccounts } from './locks.js';
|
|
15
|
+
import { rpcClock } from './bond.js';
|
|
16
|
+
import { bondPolicyFromEnv, bondRpc } from './bond-sign.js';
|
|
15
17
|
import { initWallet } from './init.js';
|
|
16
18
|
import { policyFromEnv } from './policy.js';
|
|
17
19
|
import { createPayServer } from './tools.js';
|
|
@@ -76,5 +78,5 @@ else {
|
|
|
76
78
|
: null;
|
|
77
79
|
const history = jsonlHistory(process.env.X402_HISTORY_PATH ?? DEFAULT_HISTORY, () => policy.mints);
|
|
78
80
|
const rpc = process.env.X402_RPC_URL ?? (policy.network.includes('EtWTRAB') ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');
|
|
79
|
-
await createPayServer({ policy, wallet, history, fetch, accounts: rpcAccounts(rpc) }).connect(new StdioServerTransport());
|
|
81
|
+
await createPayServer({ policy, wallet, history, fetch, accounts: rpcAccounts(rpc), clock: rpcClock(rpc), bondPolicy: bondPolicyFromEnv(process.env), bondRpc: bondRpc(rpc) }).connect(new StdioServerTransport());
|
|
80
82
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function withSpendLock<T>(fn: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// One spending operation at a time per process: limit check → human confirmation → sign → send → record.
|
|
2
|
+
// Without this, two tool calls in parallel could both pass the daily cap before either is recorded.
|
|
3
|
+
let tail = Promise.resolve();
|
|
4
|
+
export function withSpendLock(fn) {
|
|
5
|
+
const run = tail.then(fn, fn);
|
|
6
|
+
tail = run.catch(() => undefined);
|
|
7
|
+
return run;
|
|
8
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { type BondPolicy, type BondRpc } from './bond-sign.js';
|
|
2
3
|
import type { History } from './history.js';
|
|
3
4
|
import type { AccountsFetcher } from './locks.js';
|
|
4
5
|
import { type PayPolicy } from './policy.js';
|
|
@@ -9,7 +10,13 @@ export interface PayServerDeps {
|
|
|
9
10
|
history: History;
|
|
10
11
|
fetch: typeof fetch;
|
|
11
12
|
now?: () => Date;
|
|
12
|
-
/** Read-only account reader for seller lock checks */
|
|
13
|
+
/** Read-only account reader for seller lock checks and bond_deal_status */
|
|
13
14
|
accounts?: AccountsFetcher;
|
|
15
|
+
/** Solana clock (unix seconds) for the bond tools */
|
|
16
|
+
clock?: () => Promise<bigint>;
|
|
17
|
+
/** Agent402 Bond signing rules (bondPolicyFromEnv). Missing = bond signing tools refuse */
|
|
18
|
+
bondPolicy?: BondPolicy;
|
|
19
|
+
/** RPC for sending bond transactions */
|
|
20
|
+
bondRpc?: BondRpc;
|
|
14
21
|
}
|
|
15
22
|
export declare function createPayServer(d: PayServerDeps): McpServer;
|
package/dist/tools.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
// @agent402-dev/pay-mcp's
|
|
1
|
+
// @agent402-dev/pay-mcp's 11 tools: x402_fetch, x402_quote, wallet_status, payment_history, and Agent402 Bond: bond_deal_status (read-only), bond_open, bond_confirm_and_pay, bond_settle, and the Bond Job Protocol: bond_job_quote (read-only), bond_job_start, bond_job_result
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
4
|
import { createAgent } from './agent.js';
|
|
5
|
+
import { bondDealStatus } from './bond.js';
|
|
6
|
+
import { bondConfirmAndPay, bondOpen, bondSettle } from './bond-sign.js';
|
|
7
|
+
import { bondJobQuote, bondJobResult, bondJobStart } from './bond-job.js';
|
|
8
|
+
import { withSpendLock } from './spend-lock.js';
|
|
5
9
|
import { historyToCsv } from './csv.js';
|
|
6
10
|
import { nearLimits, tokenEnv } from './policy.js';
|
|
7
11
|
import { formatUnits } from './units.js';
|
|
@@ -37,7 +41,7 @@ function tokenLimitFields(p, t) {
|
|
|
37
41
|
};
|
|
38
42
|
}
|
|
39
43
|
export function createPayServer(d) {
|
|
40
|
-
const server = new McpServer({ name: 'a402-pay', version: '0.
|
|
44
|
+
const server = new McpServer({ name: 'a402-pay', version: '0.5.0' });
|
|
41
45
|
const confirm = async (message) => {
|
|
42
46
|
if (!server.server.getClientCapabilities()?.elicitation)
|
|
43
47
|
return 'unsupported';
|
|
@@ -49,7 +53,7 @@ export function createPayServer(d) {
|
|
|
49
53
|
};
|
|
50
54
|
const agent = createAgent({ ...d, confirm });
|
|
51
55
|
const req = { url: z.string().url(), method: z.enum(['GET', 'POST']).optional(), headers: z.record(z.string(), z.string()).optional(), body: z.string().max(100_000).optional() };
|
|
52
|
-
server.tool('x402_fetch', 'Fetch a URL and, if it answers HTTP 402 (x402), pay from the configured wallet only when every rule passes before signing: allowed domain (X402_ALLOWED_DOMAINS), trusted recipient (X402_TRUSTED_PAY_TO), allowed asset (USDC by default; PREQ only if listed; A402 (v1) is deprecated), per-payment and daily limits, and human confirmation above the configured amount. Signs at most once per call. Pass quoteId from x402_quote to refuse if the requirements changed. The wallet key never leaves this machine.', { ...req, quoteId: z.string().optional() }, async (a) => { const r = await agent.payAndFetch(a); return out(withUnits(r), !['paid', 'not_required'].includes(r.result)); });
|
|
56
|
+
server.tool('x402_fetch', 'Fetch a URL and, if it answers HTTP 402 (x402), pay from the configured wallet only when every rule passes before signing: allowed domain (X402_ALLOWED_DOMAINS), trusted recipient (X402_TRUSTED_PAY_TO), allowed asset (USDC by default; PREQ only if listed; A402 (v1) is deprecated), per-payment and daily limits, and human confirmation above the configured amount. Signs at most once per call. Pass quoteId from x402_quote to refuse if the requirements changed. The wallet key never leaves this machine.', { ...req, quoteId: z.string().optional() }, async (a) => { const r = await withSpendLock(() => agent.payAndFetch(a)); return out(withUnits(r), !['paid', 'not_required'].includes(r.result)); });
|
|
53
57
|
server.tool('x402_quote', 'Show the x402 payment requirements of a URL and whether each option passes the payment rules. Never signs or pays. Returns a quoteId that x402_fetch can use to pin the amount, asset and recipient.', req, async (a) => { const r = await agent.quote(a); return out(withUnits(r), r.result === 'refused'); });
|
|
54
58
|
server.tool('wallet_status', 'Payment wallet address, network, USDC and PREQ balances, payments signed today, and the configured limits and allowlists.', {}, async () => {
|
|
55
59
|
const usage = d.history.today(d.now?.());
|
|
@@ -82,6 +86,11 @@ export function createPayServer(d) {
|
|
|
82
86
|
units: '…Usd = US dollars (USDC); …Atomic = token smallest unit (1 PREQ = 1,000,000)',
|
|
83
87
|
},
|
|
84
88
|
allowedDomains: d.policy.allowedDomains, trustedPayTo: d.policy.trustedPayTo, allowedAssets: d.policy.allowedAssets,
|
|
89
|
+
bond: d.bondPolicy ? {
|
|
90
|
+
sellers: d.bondPolicy.sellers, maxUsdPerDeal: d.bondPolicy.maxPriceUsd ?? 'not set (X402_BOND_MAX_USD) — bond_open refused',
|
|
91
|
+
minSellerBondBps: d.bondPolicy.minBondBps.toString(), maxDays: d.bondPolicy.maxDays, confirmAboveUsd: d.bondPolicy.confirmAboveUsd,
|
|
92
|
+
note: 'Bond deposits and balances count toward the daily USDC cap and payment count.',
|
|
93
|
+
} : 'off',
|
|
85
94
|
...(d.policy.warnings.length || near.length ? { warnings: [...d.policy.warnings, ...near] } : {}),
|
|
86
95
|
...(d.wallet ? {} : { note: 'No wallet configured (X402_KEYPAIR_PATH): x402_fetch will not pay.' }),
|
|
87
96
|
}));
|
|
@@ -90,5 +99,36 @@ export function createPayServer(d) {
|
|
|
90
99
|
const xs = d.history.list(limit ?? 20);
|
|
91
100
|
return format === 'csv' ? { content: [{ type: 'text', text: historyToCsv([...xs].reverse()) }] } : out(withUnits(xs));
|
|
92
101
|
});
|
|
102
|
+
server.tool('bond_deal_status', 'Read-only. Show an Agent402 Bond deal (program 9hiCZZ6ddFG9oJBR1Su43Pj4JRFHeHC5cGiCgXtTuAaK): parties, amounts with units, deadlines on the Solana clock, what each side can still do, and the settlement that applies now or the earliest time it opens. Never signs. Predicted from the program rules; the program on chain decides.', { deal: z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'Solana base58 deal account address') }, async ({ deal }) => {
|
|
103
|
+
if (!d.accounts || !d.clock)
|
|
104
|
+
return out({ result: 'unavailable', message: 'No RPC configured for reading accounts (X402_RPC_URL).' }, true);
|
|
105
|
+
try {
|
|
106
|
+
const r = await bondDealStatus({ accounts: d.accounts, clock: d.clock, wallet: d.wallet?.address ?? null }, deal);
|
|
107
|
+
return out(r, r.result === 'not_found' || r.result === 'not_a_deal');
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return out({ result: 'rpc_error', message: 'Could not read the deal from the configured RPC.' }, true);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
// Signing tools refuse by themselves when there is no wallet (signer null)
|
|
114
|
+
const bondDeps = () => (d.accounts && d.clock && d.bondPolicy && d.bondRpc
|
|
115
|
+
? { policy: d.policy, bond: d.bondPolicy, signer: d.wallet ? { address: d.wallet.address, signBytes: (m) => d.wallet.signBytes(m) } : null,
|
|
116
|
+
rpc: d.bondRpc, history: d.history, confirm, accounts: d.accounts, clock: d.clock, wallet: d.wallet?.address ?? null, now: d.now, fetch: d.fetch }
|
|
117
|
+
: null);
|
|
118
|
+
const noBond = () => out({ result: 'refused', reasons: ['Agent402 Bond is not configured (RPC and bond rules)'] }, true);
|
|
119
|
+
const ADDR = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'Solana base58 address');
|
|
120
|
+
server.tool('bond_open', 'Agent402 Bond, buyer side. Sign an `open` transaction that the seller built and signed as fee payer (base64, legacy). Before signing, the instruction is rebuilt for this wallet from its own terms and must match byte for byte (one instruction, seller and this wallet as the only signers, USDC). Rules: seller in X402_BOND_SELLERS, price at most X402_BOND_MAX_USD, seller bond at least X402_BOND_MIN_SELLER_BOND_BPS (default 5%), delivery within X402_BOND_MAX_DAYS (default 30), the deposit within the daily USDC cap, and human confirmation (by default always). Empty settings refuse everything. Locks this wallet\'s deposit in the deal vault.', { transaction: z.string().min(100).max(4000) }, async ({ transaction }) => { const b = bondDeps(); if (!b)
|
|
121
|
+
return noBond(); const r = await withSpendLock(() => bondOpen(b, transaction)); return out(r, r.result !== 'opened'); });
|
|
122
|
+
server.tool('bond_confirm_and_pay', 'Agent402 Bond, buyer side. Confirm receipt and pay the balance (price minus deposit) directly to the seller. Only for deals where this wallet is the buyer, before the buyer deadline, within the daily USDC cap, with human confirmation (by default always). Confirming releases the seller bond and the deposit to the seller; the program does not judge quality.', { deal: ADDR }, async ({ deal }) => { const b = bondDeps(); if (!b)
|
|
123
|
+
return noBond(); const r = await withSpendLock(() => bondConfirmAndPay(b, deal)); return out(r, r.result !== 'confirmed_and_paid'); });
|
|
124
|
+
server.tool('bond_settle', 'Agent402 Bond. Settle a deal whose outcome is fixed by signatures and time, then send both claims in the same transaction (buyer share, then seller share). Only for deals where this wallet is the buyer or the seller; this wallet pays only the network fee.', { deal: ADDR }, async ({ deal }) => { const b = bondDeps(); if (!b)
|
|
125
|
+
return noBond(); const r = await withSpendLock(() => bondSettle(b, deal)); return out(r, r.result !== 'settled'); });
|
|
126
|
+
const URL_ = z.string().url();
|
|
127
|
+
server.tool('bond_job_quote', 'Agent402 Bond Job Protocol v1. Read a seller\'s job quote (GET {url}/quote) and check it against this wallet\'s bond rules: seller in X402_BOND_SELLERS, price at most X402_BOND_MAX_USD, seller bond at least the minimum share, delivery time, and the daily USDC cap. The URL host must be in X402_ALLOWED_DOMAINS. Never signs.', { url: URL_ }, async ({ url }) => { const b = bondDeps(); if (!b)
|
|
128
|
+
return noBond(); const r = await bondJobQuote(b, url); return out(r, r.result !== 'ok'); });
|
|
129
|
+
server.tool('bond_job_start', 'Agent402 Bond Job Protocol v1, buyer side. Send the job input (POST {url}/open), receive the seller-signed open transaction, check that the quote, the reported terms and the transaction terms all agree, then run bond_open (rebuild and compare, bond rules, human confirmation). Locks your deposit. Returns the deal address.', { url: URL_, input: z.string().min(1).max(16_384) }, async ({ url, input }) => { const b = bondDeps(); if (!b)
|
|
130
|
+
return noBond(); const r = await withSpendLock(() => bondJobStart(b, url, input)); return out(r, r.result !== 'opened'); });
|
|
131
|
+
server.tool('bond_job_result', 'Agent402 Bond Job Protocol v1, buyer side. Fetch the delivered work for a deal where this wallet is the buyer (POST {url}/deliver with a signed request; the signed bytes start with 0xff so they can never be a transaction). Does not confirm or pay: check the work, then call bond_confirm_and_pay only if it is acceptable.', { url: URL_, deal: ADDR }, async ({ url, deal }) => { const b = bondDeps(); if (!b)
|
|
132
|
+
return noBond(); const r = await bondJobResult(b, url, deal); return out(r, r.result !== 'delivered'); });
|
|
93
133
|
return server;
|
|
94
134
|
}
|
package/dist/units.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export const DECIMALS = 6;
|
|
3
3
|
/** Base-unit integer → "140,000 PREQ" */
|
|
4
4
|
export function formatUnits(atomic, symbol, decimals = DECIMALS) {
|
|
5
|
+
if (decimals === 0)
|
|
6
|
+
return `${atomic.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} ${symbol}`;
|
|
5
7
|
const s = atomic.toString().padStart(decimals + 1, '0');
|
|
6
8
|
const int = s.slice(0, -decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
7
9
|
const frac = s.slice(-decimals).replace(/0+$/, '');
|
package/dist/wallet.d.ts
CHANGED
|
@@ -8,5 +8,7 @@ export interface Wallet {
|
|
|
8
8
|
/** Number of signatures made in this process */
|
|
9
9
|
readonly signedCount: number;
|
|
10
10
|
balances(): Promise<Record<string, string>>;
|
|
11
|
+
/** Raw ed25519 signature over transaction message bytes (Agent402 Bond tools only; every rule is checked by the caller first) */
|
|
12
|
+
signBytes(message: Uint8Array): Promise<Uint8Array>;
|
|
11
13
|
}
|
|
12
14
|
export declare function loadWallet(keyPath: string, policy: PayPolicy, rpcUrl?: string): Promise<Wallet>;
|
package/dist/wallet.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Payment wallet: signs x402 exact payment transactions with a key file on the user's computer (official @x402 client).
|
|
2
2
|
// The key is never sent to the server; only the partially signed transaction goes in the PAYMENT-SIGNATURE header. This module signs only one requirement that passed the policy check
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
|
-
import { createKeyPairSignerFromBytes } from '@solana/kit';
|
|
4
|
+
import { createKeyPairSignerFromBytes, signBytes } from '@solana/kit';
|
|
5
5
|
import { encodePaymentSignatureHeader } from '@x402/core/http';
|
|
6
6
|
import { x402Client } from '@x402/fetch';
|
|
7
7
|
import { toClientSvmSigner } from '@x402/svm';
|
|
@@ -32,6 +32,11 @@ export async function loadWallet(keyPath, policy, rpcUrl) {
|
|
|
32
32
|
address: signer.address,
|
|
33
33
|
network: policy.network,
|
|
34
34
|
get signedCount() { return signed; },
|
|
35
|
+
async signBytes(message) {
|
|
36
|
+
const sig = new Uint8Array(await signBytes(signer.keyPair.privateKey, message));
|
|
37
|
+
signed++;
|
|
38
|
+
return sig;
|
|
39
|
+
},
|
|
35
40
|
async sign(resource, requirement) {
|
|
36
41
|
const payload = await client.createPaymentPayload({ x402Version: 2, resource, accepts: [requirement] });
|
|
37
42
|
signed++;
|
package/package.json
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
+
"@agent402-dev/bond-client": "^0.2.0",
|
|
23
24
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
24
25
|
"@solana/kit": "8.6.0",
|
|
25
26
|
"@x402/core": "2.31.0",
|
|
@@ -27,7 +28,7 @@
|
|
|
27
28
|
"@x402/svm": "2.31.0",
|
|
28
29
|
"zod": "^4.6.7"
|
|
29
30
|
},
|
|
30
|
-
"version": "0.
|
|
31
|
+
"version": "0.5.0",
|
|
31
32
|
"author": "Agent402",
|
|
32
33
|
"license": "Apache-2.0",
|
|
33
34
|
"type": "module",
|