@agentwonderland/mcp 0.1.23 → 0.1.25

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 (95) hide show
  1. package/dist/core/__tests__/amount-utils.test.d.ts +1 -0
  2. package/dist/core/__tests__/amount-utils.test.js +11 -0
  3. package/dist/core/__tests__/card-setup.test.d.ts +1 -0
  4. package/dist/core/__tests__/card-setup.test.js +99 -0
  5. package/dist/core/__tests__/formatters.test.d.ts +1 -0
  6. package/dist/core/__tests__/formatters.test.js +15 -0
  7. package/dist/core/__tests__/passes.test.d.ts +1 -0
  8. package/dist/core/__tests__/passes.test.js +82 -0
  9. package/dist/core/__tests__/payments.test.d.ts +1 -0
  10. package/dist/core/__tests__/payments.test.js +101 -0
  11. package/dist/core/__tests__/principal.test.d.ts +1 -0
  12. package/dist/core/__tests__/principal.test.js +67 -0
  13. package/dist/core/__tests__/spend-policy.test.d.ts +1 -0
  14. package/dist/core/__tests__/spend-policy.test.js +40 -0
  15. package/dist/core/amount-utils.d.ts +1 -0
  16. package/dist/core/amount-utils.js +4 -0
  17. package/dist/core/api-client.d.ts +9 -4
  18. package/dist/core/api-client.js +52 -22
  19. package/dist/core/base-charge.js +3 -2
  20. package/dist/core/card-setup.d.ts +20 -13
  21. package/dist/core/card-setup.js +85 -29
  22. package/dist/core/config.d.ts +22 -0
  23. package/dist/core/config.js +46 -2
  24. package/dist/core/formatters.d.ts +4 -3
  25. package/dist/core/formatters.js +10 -8
  26. package/dist/core/index.d.ts +2 -0
  27. package/dist/core/index.js +2 -0
  28. package/dist/core/ows-adapter.d.ts +10 -2
  29. package/dist/core/ows-adapter.js +54 -10
  30. package/dist/core/passes.d.ts +40 -0
  31. package/dist/core/passes.js +32 -0
  32. package/dist/core/payments.d.ts +8 -0
  33. package/dist/core/payments.js +111 -17
  34. package/dist/core/principal.d.ts +2 -0
  35. package/dist/core/principal.js +109 -0
  36. package/dist/core/solana-charge.d.ts +9 -0
  37. package/dist/core/solana-charge.js +96 -0
  38. package/dist/core/spend-policy.d.ts +12 -0
  39. package/dist/core/spend-policy.js +53 -0
  40. package/dist/core/types.d.ts +11 -2
  41. package/dist/index.js +11 -3
  42. package/dist/prompts/index.js +4 -2
  43. package/dist/resources/agents.js +1 -1
  44. package/dist/resources/wallet.js +8 -1
  45. package/dist/tools/__tests__/_payment-confirmation.test.d.ts +1 -0
  46. package/dist/tools/__tests__/_payment-confirmation.test.js +30 -0
  47. package/dist/tools/_payment-confirmation.d.ts +6 -0
  48. package/dist/tools/_payment-confirmation.js +28 -0
  49. package/dist/tools/agent-info.js +16 -2
  50. package/dist/tools/favorites.js +1 -1
  51. package/dist/tools/index.d.ts +1 -0
  52. package/dist/tools/index.js +1 -0
  53. package/dist/tools/observability.d.ts +2 -0
  54. package/dist/tools/observability.js +20 -0
  55. package/dist/tools/passes.d.ts +2 -0
  56. package/dist/tools/passes.js +157 -0
  57. package/dist/tools/run.js +127 -53
  58. package/dist/tools/solve.js +115 -51
  59. package/dist/tools/wallet.js +110 -59
  60. package/package.json +3 -1
  61. package/src/core/__tests__/amount-utils.test.ts +13 -0
  62. package/src/core/__tests__/card-setup.test.ts +118 -0
  63. package/src/core/__tests__/formatters.test.ts +17 -0
  64. package/src/core/__tests__/passes.test.ts +94 -0
  65. package/src/core/__tests__/payments.test.ts +122 -0
  66. package/src/core/__tests__/principal.test.ts +87 -0
  67. package/src/core/__tests__/spend-policy.test.ts +58 -0
  68. package/src/core/amount-utils.ts +5 -0
  69. package/src/core/api-client.ts +70 -23
  70. package/src/core/base-charge.ts +3 -2
  71. package/src/core/card-setup.ts +109 -34
  72. package/src/core/config.ts +74 -3
  73. package/src/core/formatters.ts +13 -9
  74. package/src/core/index.ts +2 -0
  75. package/src/core/ows-adapter.ts +74 -8
  76. package/src/core/passes.ts +74 -0
  77. package/src/core/payments.ts +130 -17
  78. package/src/core/principal.ts +128 -0
  79. package/src/core/solana-charge.ts +150 -0
  80. package/src/core/spend-policy.ts +69 -0
  81. package/src/core/types.ts +11 -2
  82. package/src/index.ts +11 -3
  83. package/src/prompts/index.ts +4 -2
  84. package/src/resources/agents.ts +1 -1
  85. package/src/resources/wallet.ts +8 -1
  86. package/src/tools/__tests__/_payment-confirmation.test.ts +45 -0
  87. package/src/tools/_payment-confirmation.ts +52 -0
  88. package/src/tools/agent-info.ts +25 -2
  89. package/src/tools/favorites.ts +1 -4
  90. package/src/tools/index.ts +1 -0
  91. package/src/tools/observability.ts +43 -0
  92. package/src/tools/passes.ts +228 -0
  93. package/src/tools/run.ts +174 -57
  94. package/src/tools/solve.ts +147 -59
  95. package/src/tools/wallet.ts +132 -62
@@ -19,9 +19,23 @@ import {
19
19
  getApiUrl,
20
20
  type WalletEntry,
21
21
  } from "./config.js";
22
+ import type { AgentRecord } from "./types.js";
22
23
 
23
24
  // Cache per wallet+chain combo to avoid re-initializing
24
25
  const fetchCache = new Map<string, typeof fetch>();
26
+ const REGISTRY_METHOD_MAP: Record<string, string> = {
27
+ tempo: "tempo_usdc",
28
+ base: "base_usdc",
29
+ solana: "solana_usdc",
30
+ card: "stripe_card",
31
+ };
32
+
33
+ const METHOD_REGISTRY_MAP: Record<string, string> = {
34
+ tempo_usdc: "tempo",
35
+ base_usdc: "base",
36
+ solana_usdc: "solana",
37
+ stripe_card: "card",
38
+ };
25
39
 
26
40
  // ── Helpers ─────────────────────────────────────────────────────
27
41
 
@@ -33,9 +47,26 @@ function cacheKey(walletId: string, chain: string): string {
33
47
  return `${walletId}:${chain}`;
34
48
  }
35
49
 
50
+ function cardCacheKey(): string | null {
51
+ const card = getCardConfig();
52
+ if (!card) return null;
53
+ return `card:${getApiUrl()}:${card.consumerToken}:${card.paymentMethodId ?? ""}`;
54
+ }
55
+
56
+ function clearStaleCardCache(activeKey?: string): void {
57
+ for (const key of fetchCache.keys()) {
58
+ if (key.startsWith("card:") && key !== activeKey) {
59
+ fetchCache.delete(key);
60
+ }
61
+ }
62
+ }
63
+
36
64
  // ── Per-protocol initializers ───────────────────────────────────
37
65
 
38
- async function initMpp(wallet: WalletEntry): Promise<typeof fetch | null> {
66
+ async function initEvmMppForChain(
67
+ wallet: WalletEntry,
68
+ chain: "tempo" | "base",
69
+ ): Promise<typeof fetch | null> {
39
70
  try {
40
71
  const { Mppx, tempo } = await import("mppx/client");
41
72
  let account;
@@ -50,8 +81,32 @@ async function initMpp(wallet: WalletEntry): Promise<typeof fetch | null> {
50
81
  return null;
51
82
  }
52
83
 
53
- const { baseChargeClient } = await import("./base-charge.js");
54
- const mppx = Mppx.create({ methods: [tempo({ account }), baseChargeClient({ account })] as any });
84
+ const methods = [];
85
+ if (chain === "tempo") {
86
+ methods.push(tempo({ account }));
87
+ } else {
88
+ const { baseChargeClient } = await import("./base-charge.js");
89
+ methods.push(baseChargeClient({ account }));
90
+ }
91
+
92
+ const mppx = Mppx.create({ methods: methods as any });
93
+ return mppx.fetch.bind(mppx) as typeof fetch;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ async function initSolanaMpp(wallet: WalletEntry): Promise<typeof fetch | null> {
100
+ try {
101
+ if (wallet.keyType !== "ows" && !wallet.key) {
102
+ return null;
103
+ }
104
+
105
+ const { Mppx } = await import("mppx/client");
106
+ const { solanaChargeClient } = await import("./solana-charge.js");
107
+ const mppx = Mppx.create({
108
+ methods: [solanaChargeClient({ wallet })] as any,
109
+ });
55
110
  return mppx.fetch.bind(mppx) as typeof fetch;
56
111
  } catch {
57
112
  return null;
@@ -101,8 +156,14 @@ async function initCard(): Promise<typeof fetch | null> {
101
156
  /**
102
157
  * Initialize a payment-aware fetch for a given wallet + chain.
103
158
  */
104
- async function initForChain(wallet: WalletEntry, _chain: string): Promise<typeof fetch | null> {
105
- return initMpp(wallet);
159
+ async function initForChain(wallet: WalletEntry, chain: string): Promise<typeof fetch | null> {
160
+ if (chain === "solana") {
161
+ return initSolanaMpp(wallet);
162
+ }
163
+ if (chain === "tempo" || chain === "base") {
164
+ return initEvmMppForChain(wallet, chain);
165
+ }
166
+ return null;
106
167
  }
107
168
 
108
169
  // ── Public API ──────────────────────────────────────────────────
@@ -116,7 +177,11 @@ async function initForChain(wallet: WalletEntry, _chain: string): Promise<typeof
116
177
  export async function getPaymentFetch(method?: string): Promise<typeof fetch> {
117
178
  // Card payment
118
179
  if (method === "card") {
119
- const ck = "card:card";
180
+ const ck = cardCacheKey();
181
+ clearStaleCardCache(ck ?? undefined);
182
+ if (!ck) {
183
+ throw new Error('Payment method "card" is not configured. Use the wallet_setup tool to configure a wallet');
184
+ }
120
185
  if (fetchCache.has(ck)) return fetchCache.get(ck)!;
121
186
  const pf = await initCard();
122
187
  if (pf) {
@@ -148,7 +213,16 @@ export async function getPaymentFetch(method?: string): Promise<typeof fetch> {
148
213
 
149
214
  for (const m of configured) {
150
215
  if (m === "card") {
151
- const ck = "card:card";
216
+ const ck = cardCacheKey();
217
+ clearStaleCardCache(ck ?? undefined);
218
+ if (!ck) {
219
+ if (m === defaultMethod) {
220
+ const others = configured.filter((x) => x !== m);
221
+ const altText = others.length > 0 ? ` Available alternatives: ${others.join(", ")}` : "";
222
+ throw new Error(`Card payment failed to initialize. Check your card with wallet_status.${altText}`);
223
+ }
224
+ continue;
225
+ }
152
226
  if (fetchCache.has(ck)) return fetchCache.get(ck)!;
153
227
  const pf = await initCard();
154
228
  if (pf) {
@@ -230,6 +304,16 @@ export function getConfiguredMethods(): string[] {
230
304
  return methods;
231
305
  }
232
306
 
307
+ /**
308
+ * Normalize a requested payment method into the MCP-visible method identifier.
309
+ * Accepts chain names, wallet IDs, or "card".
310
+ */
311
+ export function normalizePaymentMethod(method: string): string | null {
312
+ if (method === "card") return "card";
313
+ const resolved = resolveWalletAndChain(method);
314
+ return resolved?.chain ?? null;
315
+ }
316
+
233
317
  /**
234
318
  * Human-friendly display name for a payment method identifier.
235
319
  */
@@ -250,13 +334,33 @@ export function paymentMethodDisplayName(method: string): string {
250
334
  */
251
335
  export function getAcceptedPaymentMethods(): string[] {
252
336
  const methods = getConfiguredMethods();
253
- const map: Record<string, string> = {
254
- tempo: "tempo_usdc",
255
- base: "base_usdc",
256
- solana: "solana_usdc",
257
- card: "stripe_card",
258
- };
259
- return methods.map((m) => map[m]).filter(Boolean);
337
+ return methods
338
+ .map((m) => REGISTRY_METHOD_MAP[m])
339
+ .filter(Boolean);
340
+ }
341
+
342
+ export function toRegistryPaymentMethod(method: string): string | null {
343
+ const normalized = normalizePaymentMethod(method);
344
+ if (!normalized) return null;
345
+ return REGISTRY_METHOD_MAP[normalized] ?? null;
346
+ }
347
+
348
+ export function getCompatiblePaymentMethods(
349
+ agent: Pick<AgentRecord, "payment"> | null | undefined,
350
+ configuredMethods = getConfiguredMethods(),
351
+ ): string[] {
352
+ const acceptedPayments = agent?.payment?.accepted_payments;
353
+ if (!Array.isArray(acceptedPayments) || acceptedPayments.length === 0) {
354
+ return [...configuredMethods];
355
+ }
356
+
357
+ const acceptedMethods = new Set(
358
+ acceptedPayments
359
+ .map((payment) => METHOD_REGISTRY_MAP[payment])
360
+ .filter(Boolean),
361
+ );
362
+
363
+ return configuredMethods.filter((method) => acceptedMethods.has(method));
260
364
  }
261
365
 
262
366
  /**
@@ -270,13 +374,16 @@ export function hasWalletConfigured(): boolean {
270
374
  * Get address for a specific method, or the first configured one.
271
375
  */
272
376
  export async function getWalletAddress(method?: string): Promise<string | null> {
377
+ let chain: string | undefined;
273
378
  let wallet: WalletEntry | undefined;
274
379
 
275
380
  if (method && method !== "card") {
276
381
  const resolved = resolveWalletAndChain(method);
277
382
  wallet = resolved?.wallet;
383
+ chain = resolved?.chain;
278
384
  } else if (!method) {
279
385
  wallet = getDefaultWallet();
386
+ chain = wallet?.defaultChain ?? wallet?.chains[0];
280
387
  }
281
388
 
282
389
  if (!wallet) return null;
@@ -284,14 +391,20 @@ export async function getWalletAddress(method?: string): Promise<string | null>
284
391
  // OWS-managed wallet: derive address via the adapter
285
392
  if (wallet.keyType === "ows" && wallet.owsWalletId) {
286
393
  try {
287
- const { owsAccountFromWalletId } = await import("./ows-adapter.js");
288
- const account = await owsAccountFromWalletId(wallet.owsWalletId);
289
- return account.address;
394
+ const { getOwsWalletAddress } = await import("./ows-adapter.js");
395
+ return await getOwsWalletAddress(
396
+ wallet.owsWalletId,
397
+ chain === "solana" ? "solana" : "evm",
398
+ );
290
399
  } catch {
291
400
  return null;
292
401
  }
293
402
  }
294
403
 
404
+ if (chain === "solana") {
405
+ return null;
406
+ }
407
+
295
408
  // Raw EVM key path
296
409
  if (!wallet.key) return null;
297
410
 
@@ -0,0 +1,128 @@
1
+ import { addWallet, getDefaultWallet, getWallets, type WalletEntry } from "./config.js";
2
+ import { getWalletAddress } from "./payments.js";
3
+ import {
4
+ createOwsWallet,
5
+ isOwsAvailable,
6
+ listOwsWallets,
7
+ } from "./ows-adapter.js";
8
+
9
+ const BASE_CHAIN_ID = "8453";
10
+ const SOLANA_CHAIN_ID = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
11
+ const AUTO_IDENTITY_LABEL = "AW Identity";
12
+
13
+ function principalFromAddress(address: string, type: "evm" | "solana"): string {
14
+ if (type === "evm") {
15
+ return `did:pkh:eip155:${BASE_CHAIN_ID}:${address.toLowerCase()}`;
16
+ }
17
+ return `did:pkh:${SOLANA_CHAIN_ID}:${address}`;
18
+ }
19
+
20
+ function walletSupportsEvm(wallet: WalletEntry): boolean {
21
+ return wallet.chains.some((chain) => chain !== "solana");
22
+ }
23
+
24
+ function walletSupportsSolana(wallet: WalletEntry): boolean {
25
+ return wallet.chains.includes("solana");
26
+ }
27
+
28
+ async function walletPrincipal(wallet: WalletEntry): Promise<string | null> {
29
+ if (walletSupportsEvm(wallet)) {
30
+ const address = await getWalletAddress(wallet.id);
31
+ return address ? principalFromAddress(address, "evm") : null;
32
+ }
33
+
34
+ if (walletSupportsSolana(wallet)) {
35
+ const address = await getWalletAddress(wallet.id);
36
+ return address ? principalFromAddress(address, "solana") : null;
37
+ }
38
+
39
+ return null;
40
+ }
41
+
42
+ function preferredWallets(): WalletEntry[] {
43
+ const wallets = getWallets();
44
+ const defaultWallet = getDefaultWallet();
45
+ const ordered = defaultWallet
46
+ ? [defaultWallet, ...wallets.filter((wallet) => wallet.id !== defaultWallet.id)]
47
+ : wallets;
48
+
49
+ return ordered.sort((a, b) => {
50
+ const aScore = walletSupportsEvm(a) ? 0 : walletSupportsSolana(a) ? 1 : 2;
51
+ const bScore = walletSupportsEvm(b) ? 0 : walletSupportsSolana(b) ? 1 : 2;
52
+ return aScore - bScore;
53
+ });
54
+ }
55
+
56
+ async function createFallbackIdentityWallet(): Promise<WalletEntry> {
57
+ const { generatePrivateKey } = await import("viem/accounts");
58
+ const walletName = `aw-identity-${Date.now()}`;
59
+ const entry: WalletEntry = {
60
+ id: walletName,
61
+ keyType: "evm",
62
+ key: generatePrivateKey(),
63
+ chains: ["tempo", "base"],
64
+ defaultChain: "base",
65
+ label: AUTO_IDENTITY_LABEL,
66
+ };
67
+ addWallet(entry);
68
+ return entry;
69
+ }
70
+
71
+ async function ensureIdentityWallet(): Promise<WalletEntry> {
72
+ const wallets = preferredWallets();
73
+ const existing = wallets.find((wallet) => walletSupportsEvm(wallet) || walletSupportsSolana(wallet));
74
+ if (existing) return existing;
75
+
76
+ if (await isOwsAvailable()) {
77
+ const existingOwsWallets = await listOwsWallets();
78
+ const linked = existingOwsWallets[0];
79
+ if (linked) {
80
+ const entry: WalletEntry = {
81
+ id: linked.name,
82
+ keyType: "ows",
83
+ owsWalletId: linked.id,
84
+ chains: ["tempo", "base"],
85
+ defaultChain: "base",
86
+ label: linked.name,
87
+ };
88
+ addWallet(entry);
89
+ return entry;
90
+ }
91
+
92
+ const walletName = `aw-identity-${Date.now()}`;
93
+ const created = await createOwsWallet(walletName, "evm");
94
+ const entry: WalletEntry = {
95
+ id: walletName,
96
+ keyType: "ows",
97
+ owsWalletId: created.walletId,
98
+ chains: ["tempo", "base"],
99
+ defaultChain: "base",
100
+ label: AUTO_IDENTITY_LABEL,
101
+ };
102
+ addWallet(entry);
103
+ return entry;
104
+ }
105
+
106
+ return createFallbackIdentityWallet();
107
+ }
108
+
109
+ export async function getConsumerPrincipal(): Promise<string | null> {
110
+ for (const wallet of preferredWallets()) {
111
+ const principal = await walletPrincipal(wallet);
112
+ if (principal) return principal;
113
+ }
114
+
115
+ return null;
116
+ }
117
+
118
+ export async function ensureConsumerPrincipal(): Promise<string> {
119
+ const existing = await getConsumerPrincipal();
120
+ if (existing) return existing;
121
+
122
+ const identityWallet = await ensureIdentityWallet();
123
+ const principal = await walletPrincipal(identityWallet);
124
+ if (!principal) {
125
+ throw new Error("Could not derive a consumer principal from the configured identity wallet.");
126
+ }
127
+ return principal;
128
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Custom MPP payment method: Solana USDC charge (client-side).
3
+ *
4
+ * Sends an SPL Token transfer on Solana mainnet and returns the transaction
5
+ * signature as the payment credential.
6
+ */
7
+ import { Credential, Method, z } from "mppx";
8
+ import { Connection, Keypair, PublicKey, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
9
+ import {
10
+ ASSOCIATED_TOKEN_PROGRAM_ID,
11
+ TOKEN_PROGRAM_ID,
12
+ createTransferCheckedInstruction,
13
+ getAssociatedTokenAddressSync,
14
+ } from "@solana/spl-token";
15
+ import type { WalletEntry } from "./config.js";
16
+ import { toAtomicAmount } from "./amount-utils.js";
17
+
18
+ export const SOLANA_USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" as const;
19
+ export const SOLANA_CHAIN_ID = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" as const;
20
+ const SOLANA_RPC = "https://api.mainnet-beta.solana.com";
21
+
22
+ const solanaChargeMethod = Method.from({
23
+ name: "solana" as const,
24
+ intent: "charge" as const,
25
+ schema: {
26
+ credential: {
27
+ payload: z.object({
28
+ signature: z.string(),
29
+ type: z.literal("signature"),
30
+ }),
31
+ },
32
+ request: z.pipe(
33
+ z.object({
34
+ amount: z.string(),
35
+ currency: z.string(),
36
+ recipient: z.string(),
37
+ chainId: z.optional(z.string()),
38
+ decimals: z.optional(z.number()),
39
+ }),
40
+ z.transform((value: any) => ({
41
+ ...value,
42
+ methodDetails: { chainId: value.chainId ?? SOLANA_CHAIN_ID },
43
+ })),
44
+ ),
45
+ },
46
+ });
47
+
48
+ function keypairFromPrivateKeyHex(privateKeyHex: string): Keypair {
49
+ const normalized = privateKeyHex.startsWith("0x")
50
+ ? privateKeyHex.slice(2)
51
+ : privateKeyHex;
52
+ const bytes = Uint8Array.from(Buffer.from(normalized, "hex"));
53
+ if (bytes.length === 32) {
54
+ return Keypair.fromSeed(bytes);
55
+ }
56
+ if (bytes.length === 64) {
57
+ return Keypair.fromSecretKey(bytes);
58
+ }
59
+ throw new Error(`Unsupported Solana private key length: ${bytes.length} bytes.`);
60
+ }
61
+
62
+ async function getKeypair(wallet: WalletEntry): Promise<Keypair> {
63
+ if (wallet.keyType === "ows" && wallet.owsWalletId) {
64
+ const { owsSolanaKeypairFromWalletId } = await import("./ows-adapter.js");
65
+ return owsSolanaKeypairFromWalletId(wallet.owsWalletId);
66
+ }
67
+ if (wallet.key) {
68
+ return keypairFromPrivateKeyHex(wallet.key);
69
+ }
70
+ throw new Error(`Wallet "${wallet.id}" cannot sign Solana transactions.`);
71
+ }
72
+
73
+ interface SolanaChargeClientConfig {
74
+ wallet: WalletEntry;
75
+ rpcUrl?: string;
76
+ }
77
+
78
+ async function resolveRecipientTokenAccount(
79
+ connection: Connection,
80
+ mint: PublicKey,
81
+ recipient: PublicKey,
82
+ ): Promise<PublicKey> {
83
+ const accountInfo = await connection.getParsedAccountInfo(recipient, "confirmed");
84
+ const owner = accountInfo.value?.owner;
85
+ if (owner && owner.toBase58() === TOKEN_PROGRAM_ID.toBase58()) {
86
+ return recipient;
87
+ }
88
+
89
+ return getAssociatedTokenAddressSync(
90
+ mint,
91
+ recipient,
92
+ false,
93
+ TOKEN_PROGRAM_ID,
94
+ ASSOCIATED_TOKEN_PROGRAM_ID,
95
+ );
96
+ }
97
+
98
+ export function solanaChargeClient(config: SolanaChargeClientConfig) {
99
+ return Method.toClient(solanaChargeMethod as any, {
100
+ async createCredential({ challenge }: any) {
101
+ const { request } = challenge;
102
+ const amount = toAtomicAmount(request.amount, request.decimals ?? 6);
103
+ const decimals = request.decimals ?? 6;
104
+ const mint = new PublicKey(request.currency ?? SOLANA_USDC_MINT);
105
+ const recipient = new PublicKey(request.recipient);
106
+ const keypair = await getKeypair(config.wallet);
107
+ const owner = keypair.publicKey;
108
+ const connection = new Connection(config.rpcUrl ?? SOLANA_RPC, "confirmed");
109
+
110
+ const sourceTokenAccount = getAssociatedTokenAddressSync(
111
+ mint,
112
+ owner,
113
+ false,
114
+ TOKEN_PROGRAM_ID,
115
+ ASSOCIATED_TOKEN_PROGRAM_ID,
116
+ );
117
+ const destinationTokenAccount = await resolveRecipientTokenAccount(
118
+ connection,
119
+ mint,
120
+ recipient,
121
+ );
122
+
123
+ const instruction = createTransferCheckedInstruction(
124
+ sourceTokenAccount,
125
+ mint,
126
+ destinationTokenAccount,
127
+ owner,
128
+ amount,
129
+ decimals,
130
+ );
131
+
132
+ const { blockhash } = await connection.getLatestBlockhash("confirmed");
133
+
134
+ const transaction = new Transaction({
135
+ feePayer: owner,
136
+ recentBlockhash: blockhash,
137
+ }).add(instruction);
138
+
139
+ const signature = await sendAndConfirmTransaction(connection, transaction, [keypair], {
140
+ commitment: "confirmed",
141
+ });
142
+
143
+ return Credential.serialize({
144
+ challenge,
145
+ payload: { signature, type: "signature" as const },
146
+ source: `did:pkh:${SOLANA_CHAIN_ID}:${owner.toBase58()}`,
147
+ });
148
+ },
149
+ });
150
+ }
@@ -0,0 +1,69 @@
1
+ import {
2
+ getSpendLedger,
3
+ getSpendPolicy,
4
+ saveSpendLedger,
5
+ type SpendLedgerEntry,
6
+ } from "./config.js";
7
+
8
+ const LEDGER_RETENTION_DAYS = 35;
9
+
10
+ function utcDay(now: Date): string {
11
+ return now.toISOString().slice(0, 10);
12
+ }
13
+
14
+ function pruneLedger(entries: SpendLedgerEntry[], now: Date): SpendLedgerEntry[] {
15
+ const cutoff = new Date(now);
16
+ cutoff.setUTCDate(cutoff.getUTCDate() - LEDGER_RETENTION_DAYS);
17
+ return entries.filter((entry) => new Date(entry.timestamp) >= cutoff);
18
+ }
19
+
20
+ export function getDailySpend(method: string, now = new Date()): number {
21
+ const day = utcDay(now);
22
+ return getSpendLedger()
23
+ .filter((entry) => entry.method === method && entry.day === day)
24
+ .reduce((sum, entry) => sum + entry.amountUsd, 0);
25
+ }
26
+
27
+ export function canSpend(params: {
28
+ method: string;
29
+ amountUsd: number;
30
+ }): { ok: true } | { ok: false; message: string } {
31
+ const policy = getSpendPolicy(params.method);
32
+ if (!policy) return { ok: true };
33
+
34
+ if (policy.maxPerTxUsd != null && params.amountUsd > policy.maxPerTxUsd) {
35
+ return {
36
+ ok: false,
37
+ message: `Transaction blocked by spend policy: $${params.amountUsd.toFixed(2)} exceeds max_per_tx of $${policy.maxPerTxUsd.toFixed(2)} for "${params.method}".`,
38
+ };
39
+ }
40
+
41
+ if (policy.maxPerDayUsd != null) {
42
+ const spentToday = getDailySpend(params.method);
43
+ if (spentToday + params.amountUsd > policy.maxPerDayUsd) {
44
+ return {
45
+ ok: false,
46
+ message: `Transaction blocked by spend policy: daily spend would be $${(spentToday + params.amountUsd).toFixed(2)} > $${policy.maxPerDayUsd.toFixed(2)} for "${params.method}".`,
47
+ };
48
+ }
49
+ }
50
+
51
+ return { ok: true };
52
+ }
53
+
54
+ export function requiresPolicyConfirmation(method: string, amountUsd: number): boolean {
55
+ const policy = getSpendPolicy(method);
56
+ if (!policy?.requireConfirmationAboveUsd) return false;
57
+ return amountUsd >= policy.requireConfirmationAboveUsd;
58
+ }
59
+
60
+ export function recordSpend(method: string, amountUsd: number, now = new Date()): void {
61
+ const entries = pruneLedger(getSpendLedger(), now);
62
+ entries.push({
63
+ method,
64
+ amountUsd,
65
+ day: utcDay(now),
66
+ timestamp: now.toISOString(),
67
+ });
68
+ saveSpendLedger(entries);
69
+ }
package/src/core/types.ts CHANGED
@@ -6,8 +6,7 @@ export interface AgentRecord {
6
6
  id: string;
7
7
  name: string;
8
8
  description?: string;
9
- pricePer1kTokens?: string;
10
- pricingModel?: string;
9
+ pricePerRunUsd?: string;
11
10
  avgRating?: number | null;
12
11
  totalExecutions?: number;
13
12
  successRate?: number | string | null;
@@ -22,6 +21,16 @@ export interface AgentRecord {
22
21
  };
23
22
  payment?: {
24
23
  pricing?: Record<string, unknown>;
24
+ accepted_payments?: string[];
25
+ credit_packs?: {
26
+ unit_type?: string;
27
+ packs?: Array<{
28
+ key?: string;
29
+ name?: string;
30
+ included_units?: number;
31
+ price_usd?: string;
32
+ }>;
33
+ } | null;
25
34
  [key: string]: unknown;
26
35
  };
27
36
  [key: string]: unknown;
package/src/index.ts CHANGED
@@ -13,6 +13,8 @@ import { registerRateTools } from "./tools/rate.js";
13
13
  import { registerWalletTools } from "./tools/wallet.js";
14
14
  import { registerFavoriteTools } from "./tools/favorites.js";
15
15
  import { registerTipTools } from "./tools/tip.js";
16
+ import { registerPassTools } from "./tools/passes.js";
17
+ import { registerObservabilityTools } from "./tools/observability.js";
16
18
 
17
19
  // ── Resources ────────────────────────────────────────────────────
18
20
  import { registerAgentResources } from "./resources/agents.js";
@@ -40,14 +42,18 @@ export async function startMcpServer(): Promise<void> {
40
42
  "1. search_agents() or solve() — find agents for the task",
41
43
  "2. get_agent() — check required input fields before running",
42
44
  "3. run_agent() or solve() with ALL required fields",
43
- "4. If no payment method is set up, run_agent returns a QR code to connect a credit card — present it to the user",
45
+ "3a. If the agent offers discounted credit packs, use buy_agent_credit_pack() and list_agent_credit_packs() when helpful",
46
+ "4. If no payment method is set up, run_agent returns a setup page to connect a credit card — present it to the user",
44
47
  "5. Ask user to rate or tip after a successful run",
45
48
  "",
46
49
  "PAYMENT:",
47
- "- Credit/debit card is the default and easiest way to pay — scan a QR code to connect, no funding needed.",
48
- "- Crypto wallets (Tempo USDC, Base USDC) are available for advanced users.",
50
+ "- Credit/debit card is the default and easiest way to pay — open the setup page to connect, no funding needed.",
51
+ "- Crypto wallets (Tempo USDC, Base USDC, Solana USDC) are available for advanced users.",
49
52
  "- Card and crypto are SEPARATE payment methods. Card charges a credit card; crypto sends USDC on-chain.",
50
53
  "- Card is set as the default payment method when configured.",
54
+ "- run_agent() and solve() require pay_with explicitly.",
55
+ "- Use wallet_status to see the exact payment methods the user has configured before calling a paid tool.",
56
+ "- Use open_observability_dashboard() to open a secure web usage dashboard for runs/spend/rebates.",
51
57
  "- Payment is automatic once configured. Users are never charged for failed runs.",
52
58
  "- Do NOT ask the user to set up payment before they try to run an agent. Let them explore freely.",
53
59
  "- If a specific payment method fails, report the error clearly. Do NOT silently fall back to a different method.",
@@ -74,6 +80,8 @@ export async function startMcpServer(): Promise<void> {
74
80
  registerWalletTools(server);
75
81
  registerFavoriteTools(server);
76
82
  registerTipTools(server);
83
+ registerPassTools(server);
84
+ registerObservabilityTools(server);
77
85
 
78
86
  // Register resources
79
87
  registerAgentResources(server);
@@ -18,7 +18,7 @@ export function registerPrompts(server: McpServer) {
18
18
  "1. Check my wallet status with wallet_status",
19
19
  "2. If no wallet is configured, help me create one with wallet_setup",
20
20
  "3. Show me some popular agents with search_agents",
21
- "4. Briefly explain how solve, run_agent, rating, and tipping work",
21
+ "4. Briefly explain how solve, run_agent, buy_agent_credit_pack, pay_with selection, rating, and tipping work",
22
22
  ].join("\n"),
23
23
  },
24
24
  }],
@@ -86,7 +86,7 @@ export function registerPrompts(server: McpServer) {
86
86
  text: [
87
87
  `Complete this task on Agent Wonderland within $${budget || "1.00"}: "${task}"`,
88
88
  "",
89
- "Use the solve tool with the budget parameter. Show me what agent was selected and why.",
89
+ "Use the solve tool with the budget parameter and an explicit pay_with method. Show me what agent was selected and why.",
90
90
  ].join("\n"),
91
91
  },
92
92
  }],
@@ -108,6 +108,8 @@ export function registerPrompts(server: McpServer) {
108
108
  text: [
109
109
  `Run agent ${agent_id} with this input: ${input}`,
110
110
  "",
111
+ "Include an explicit pay_with method when you call run_agent.",
112
+ "",
111
113
  "After getting the result:",
112
114
  "1. Summarize the output",
113
115
  "2. Assess the quality",
@@ -9,7 +9,7 @@ export function registerAgentResources(server: McpServer) {
9
9
  const lines = agents.map(a => {
10
10
  const rating = stars(a.reputationScore);
11
11
  const jobs = compactNumber(a.totalExecutions);
12
- const price = formatPrice(a.pricePer1kTokens);
12
+ const price = formatPrice(a.pricePerRunUsd);
13
13
  return `${a.name} ${rating} ${jobs} jobs | ${price}/req — ${a.description || ""}`;
14
14
  });
15
15
  return {