@agentwonderland/mcp 0.1.14 → 0.1.16

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.
@@ -68,6 +68,10 @@ export declare function removeWallet(id: string): void;
68
68
  * Get card configuration.
69
69
  */
70
70
  export declare function getCardConfig(): CardConfig | null;
71
+ /**
72
+ * Save card configuration after setup.
73
+ */
74
+ export declare function setCardConfig(card: CardConfig | null): void;
71
75
  /**
72
76
  * Resolve a payment method string to a wallet + chain.
73
77
  * Accepts: wallet ID, chain name, or "card".
@@ -259,6 +259,12 @@ export function removeWallet(id) {
259
259
  export function getCardConfig() {
260
260
  return getConfig().card;
261
261
  }
262
+ /**
263
+ * Save card configuration after setup.
264
+ */
265
+ export function setCardConfig(card) {
266
+ saveConfig({ card });
267
+ }
262
268
  /**
263
269
  * Resolve a payment method string to a wallet + chain.
264
270
  * Accepts: wallet ID, chain name, or "card".
package/dist/tools/run.js CHANGED
@@ -1,10 +1,34 @@
1
1
  import { z } from "zod";
2
2
  import { apiGet, apiPost, apiPostWithPayment } from "../core/api-client.js";
3
3
  import { uploadLocalFiles } from "../core/file-upload.js";
4
- import { getConfiguredMethods, hasWalletConfigured } from "../core/payments.js";
4
+ import { getConfiguredMethods, hasWalletConfigured, getWalletAddress } from "../core/payments.js";
5
5
  import { requiresSpendConfirmation, getDefaultTipAmount } from "../core/config.js";
6
6
  import { formatRunResult } from "../core/formatters.js";
7
7
  import { storeFeedbackToken } from "./_token-cache.js";
8
+ const POLL_INTERVAL_MS = 3000;
9
+ const POLL_MAX_MS = 120000; // 2 minutes
10
+ async function pollJobUntilDone(jobId, agentName) {
11
+ const deadline = Date.now() + POLL_MAX_MS;
12
+ const walletAddress = await getWalletAddress();
13
+ const walletParam = walletAddress ? `?wallet=${walletAddress}` : "";
14
+ while (Date.now() < deadline) {
15
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
16
+ try {
17
+ const job = await apiGet(`/jobs/${jobId}${walletParam}`);
18
+ if (job.status === "completed") {
19
+ return { status: "completed", output: job.output };
20
+ }
21
+ if (job.status === "failed") {
22
+ return { status: "failed", output: job.output, error_code: job.error_code };
23
+ }
24
+ // Still processing — continue polling
25
+ }
26
+ catch {
27
+ // Ignore poll errors, keep trying until deadline
28
+ }
29
+ }
30
+ return { status: "failed", error_code: "POLL_TIMEOUT" };
31
+ }
8
32
  function text(t) {
9
33
  return { content: [{ type: "text", text: t }] };
10
34
  }
@@ -99,6 +123,38 @@ export function registerRunTools(server) {
99
123
  }
100
124
  const actualCost = result.cost;
101
125
  const status = result.status;
126
+ // Async agent — poll until complete
127
+ if (status === "processing") {
128
+ const pollResult = await pollJobUntilDone(jobId, agentName);
129
+ if (pollResult.status === "completed") {
130
+ const asyncFormatted = formatRunResult({
131
+ ...result,
132
+ status: "success",
133
+ output: pollResult.output,
134
+ }, { paymentMethod: method ?? getConfiguredMethods()[0] });
135
+ if (result.feedback_token) {
136
+ storeFeedbackToken(jobId, result.feedback_token, resultAgentId);
137
+ }
138
+ const asyncCostLine = actualCost != null ? `Paid $${actualCost.toFixed(actualCost < 0.01 ? 4 : 2)}.` : "";
139
+ const asyncFeedbackAsk = [
140
+ `IMPORTANT: After presenting the result above, you MUST ask the user:`,
141
+ `"${asyncCostLine} Was this result helpful? I can rate it (1-5 stars) or tip the builder for you."`,
142
+ "",
143
+ `If the user wants to rate: rate_agent({ job_id: "${jobId}", rating: <1-5>, comment: "..." })`,
144
+ `If the user wants to tip: tip_agent({ job_id: "${jobId}", agent_id: "${resultAgentId}", amount: 0.25 })`,
145
+ `To save for later: favorite_agent({ agent_id: "${resultAgentId}" })`,
146
+ ].join("\n");
147
+ return multiText(uploadSummary ? `${uploadSummary}\n\n${asyncFormatted}` : asyncFormatted, asyncFeedbackAsk);
148
+ }
149
+ // Async agent failed
150
+ const failedFormatted = formatRunResult({
151
+ ...result,
152
+ status: "failed",
153
+ output: pollResult.output,
154
+ error_code: pollResult.error_code,
155
+ }, { paymentMethod: method ?? getConfiguredMethods()[0] });
156
+ return multiText(uploadSummary ? `${uploadSummary}\n\n${failedFormatted}` : failedFormatted, "The agent execution failed. A refund has been initiated automatically.");
157
+ }
102
158
  // Auto-tip if configured and run succeeded
103
159
  const defaultTip = getDefaultTipAmount();
104
160
  let tipLine = "";
@@ -1,10 +1,33 @@
1
1
  import { z } from "zod";
2
2
  import { apiGet, apiPost, apiPostWithPayment } from "../core/api-client.js";
3
- import { hasWalletConfigured, getConfiguredMethods, getAcceptedPaymentMethods, } from "../core/payments.js";
3
+ import { hasWalletConfigured, getConfiguredMethods, getAcceptedPaymentMethods, getWalletAddress, } from "../core/payments.js";
4
4
  import { requiresSpendConfirmation, getDefaultTipAmount } from "../core/config.js";
5
5
  import { agentList, formatRunResult } from "../core/formatters.js";
6
6
  import { uploadLocalFiles } from "../core/file-upload.js";
7
7
  import { storeFeedbackToken } from "./_token-cache.js";
8
+ const POLL_INTERVAL_MS = 3000;
9
+ const POLL_MAX_MS = 120000;
10
+ async function pollSolveJob(jobId) {
11
+ const deadline = Date.now() + POLL_MAX_MS;
12
+ const walletAddress = await getWalletAddress();
13
+ const walletParam = walletAddress ? `?wallet=${walletAddress}` : "";
14
+ while (Date.now() < deadline) {
15
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
16
+ try {
17
+ const job = await apiGet(`/jobs/${jobId}${walletParam}`);
18
+ if (job.status === "completed") {
19
+ return { status: "completed", output: job.output };
20
+ }
21
+ if (job.status === "failed") {
22
+ return { status: "failed", output: job.output, error_code: job.error_code };
23
+ }
24
+ }
25
+ catch {
26
+ // Ignore poll errors, keep trying
27
+ }
28
+ }
29
+ return { status: "failed", error_code: "POLL_TIMEOUT" };
30
+ }
8
31
  function text(t) {
9
32
  return { content: [{ type: "text", text: t }] };
10
33
  }
@@ -171,9 +194,46 @@ export function registerSolveTools(server) {
171
194
  }
172
195
  const jobId = result.job_id ?? "";
173
196
  const agentId2 = result.agent_id ?? selected.id;
197
+ const status = result.status;
174
198
  if (result.feedback_token) {
175
199
  storeFeedbackToken(jobId, result.feedback_token, agentId2);
176
200
  }
201
+ // Async agent — poll until complete
202
+ if (status === "processing") {
203
+ const pollResult = await pollSolveJob(jobId);
204
+ if (pollResult.status === "completed") {
205
+ const asyncFormatted = formatRunResult({
206
+ ...result,
207
+ status: "success",
208
+ output: pollResult.output,
209
+ }, { paymentMethod: method });
210
+ const asyncOutput = [
211
+ discovery,
212
+ "",
213
+ `Running ${selected.name} — best match`,
214
+ `Estimated cost: $${estimatedCost.toFixed(4)}`,
215
+ "",
216
+ asyncFormatted,
217
+ ].join("\n");
218
+ const asyncCost = result.cost;
219
+ return multiText(asyncOutput, feedbackAsk(jobId, agentId2, asyncCost, ""));
220
+ }
221
+ // Async agent failed
222
+ const failedFormatted = formatRunResult({
223
+ ...result,
224
+ status: "failed",
225
+ output: pollResult.output,
226
+ error_code: pollResult.error_code,
227
+ }, { paymentMethod: method });
228
+ const failedOutput = [
229
+ discovery,
230
+ "",
231
+ `Running ${selected.name} — best match`,
232
+ "",
233
+ failedFormatted,
234
+ ].join("\n");
235
+ return multiText(failedOutput, "The agent execution failed. A refund has been initiated automatically.");
236
+ }
177
237
  const actualCost = result.cost;
178
238
  const tipMsg = result.feedback_token ? await autoTip(jobId, agentId2, selected.name ?? "", result.feedback_token) : "";
179
239
  const output = [
@@ -1,10 +1,15 @@
1
1
  import { z } from "zod";
2
- import { getWallets, getCardConfig, addWallet } from "../core/config.js";
2
+ import QRCode from "qrcode";
3
+ import { getWallets, getCardConfig, setCardConfig, addWallet } from "../core/config.js";
4
+ import { getApiUrl } from "../core/config.js";
3
5
  import { getWalletAddress } from "../core/payments.js";
6
+ import { apiPost, apiGet } from "../core/api-client.js";
4
7
  import { isOwsAvailable, createOwsWallet, importKeyToOws, listOwsWallets, } from "../core/ows-adapter.js";
5
8
  function text(t) {
6
9
  return { content: [{ type: "text", text: t }] };
7
10
  }
11
+ // Pending card setup — stored between the QR display call and the confirmation poll
12
+ let pendingCardSetup = null;
8
13
  export function registerWalletTools(server) {
9
14
  // ── wallet_status (extracted from check_wallet) ─────────────────
10
15
  server.tool("wallet_status", "Check payment readiness. Shows all configured wallets, their chains, addresses, and card status.", {}, async () => {
@@ -26,10 +31,10 @@ export function registerWalletTools(server) {
26
31
  return text(lines.join("\n"));
27
32
  });
28
33
  // ── wallet_setup (NEW) ──────────────────────────────────────────
29
- server.tool("wallet_setup", "Create or import a wallet for paying agents. Uses OWS (Open Wallet Standard) for encrypted key storage when available, falling back to plaintext.", {
34
+ server.tool("wallet_setup", "Set up a payment method for running agents. Options: 'create' a crypto wallet, 'import' an existing key, or 'add-card' to connect a credit/debit card via QR code. Card setup shows a scannable QR code — call again after the user enters their card to confirm.", {
30
35
  action: z
31
- .enum(["create", "import"])
32
- .describe("'create' a new wallet or 'import' an existing private key"),
36
+ .enum(["create", "import", "add-card"])
37
+ .describe("'create' a new crypto wallet, 'import' an existing private key, or 'add-card' to connect a credit/debit card"),
33
38
  name: z
34
39
  .string()
35
40
  .optional()
@@ -41,6 +46,72 @@ export function registerWalletTools(server) {
41
46
  chain: z.enum(["tempo", "base", "solana"]).optional()
42
47
  .describe("Primary chain (default: tempo). Solana support is via Stripe deposit mode."),
43
48
  }, async ({ action, name, key, chain }) => {
49
+ // ── Card setup flow ──────────────────────────────────────
50
+ if (action === "add-card") {
51
+ const existing = getCardConfig();
52
+ if (existing) {
53
+ return text(`Card already connected: ${existing.brand} ****${existing.last4}\n\nTo replace it, remove the current card first.`);
54
+ }
55
+ // Check if there's a pending setup to complete
56
+ if (pendingCardSetup) {
57
+ const pendingToken = pendingCardSetup.token;
58
+ // Poll for completion (up to 2 minutes)
59
+ const deadline = Date.now() + 120_000;
60
+ while (Date.now() < deadline) {
61
+ await new Promise((r) => setTimeout(r, 3000));
62
+ try {
63
+ const status = await apiGet(`/card/status?token=${pendingToken}`);
64
+ if (status.status === "complete" && status.consumer_token) {
65
+ setCardConfig({
66
+ consumerToken: status.consumer_token,
67
+ last4: status.card_last4 ?? "????",
68
+ brand: status.card_brand ?? "card",
69
+ });
70
+ pendingCardSetup = null;
71
+ return text(`Connected! ${status.card_brand ?? "Card"} ****${status.card_last4} is ready for payments.`);
72
+ }
73
+ }
74
+ catch {
75
+ // Keep polling
76
+ }
77
+ }
78
+ pendingCardSetup = null;
79
+ return text("Card setup timed out. Run wallet_setup({ action: \"add-card\" }) to try again.");
80
+ }
81
+ // Create new card setup session
82
+ let setupResult;
83
+ try {
84
+ setupResult = await apiPost("/card/setup", {});
85
+ }
86
+ catch {
87
+ return text("Error: Could not create card setup session. Try again later.");
88
+ }
89
+ // Store for the follow-up poll call
90
+ pendingCardSetup = { token: setupResult.token };
91
+ // Build a short link URL for a compact QR code
92
+ const apiUrl = getApiUrl();
93
+ const shortUrl = `${apiUrl}/card/link/${setupResult.token}`;
94
+ // Generate QR code
95
+ let qr;
96
+ try {
97
+ qr = await QRCode.toString(shortUrl, {
98
+ type: "utf8",
99
+ errorCorrectionLevel: "L",
100
+ margin: 2,
101
+ });
102
+ }
103
+ catch {
104
+ qr = "";
105
+ }
106
+ return text([
107
+ "Scan to connect a payment card:\n",
108
+ qr,
109
+ `Or open: ${shortUrl}`,
110
+ "",
111
+ "After entering your card, tell me and I'll confirm the connection.",
112
+ ].join("\n"));
113
+ }
114
+ // ── Crypto wallet setup ──────────────────────────────────
44
115
  if (action === "import" && !key) {
45
116
  return text("Error: 'key' parameter is required when action is 'import'.");
46
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentwonderland/mcp",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
4
4
  "type": "module",
5
5
  "description": "MCP server for the Agent Wonderland AI agent marketplace",
6
6
  "bin": {
@@ -24,6 +24,7 @@
24
24
  "dependencies": {
25
25
  "@modelcontextprotocol/sdk": "^1.12.1",
26
26
  "mppx": "^0.4.9",
27
+ "qrcode": "^1.5.4",
27
28
  "viem": "^2.47.6",
28
29
  "zod": "^3.24.0"
29
30
  },
@@ -36,6 +37,7 @@
36
37
  }
37
38
  },
38
39
  "devDependencies": {
40
+ "@types/qrcode": "^1.5.6",
39
41
  "tsx": "^4.0.0",
40
42
  "typescript": "^5.7.0"
41
43
  },
@@ -346,6 +346,13 @@ export function getCardConfig(): CardConfig | null {
346
346
  return getConfig().card;
347
347
  }
348
348
 
349
+ /**
350
+ * Save card configuration after setup.
351
+ */
352
+ export function setCardConfig(card: CardConfig | null): void {
353
+ saveConfig({ card });
354
+ }
355
+
349
356
  /**
350
357
  * Resolve a payment method string to a wallet + chain.
351
358
  * Accepts: wallet ID, chain name, or "card".
package/src/tools/run.ts CHANGED
@@ -2,11 +2,46 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
3
  import { apiGet, apiPost, apiPostWithPayment } from "../core/api-client.js";
4
4
  import { uploadLocalFiles } from "../core/file-upload.js";
5
- import { getConfiguredMethods, hasWalletConfigured } from "../core/payments.js";
5
+ import { getConfiguredMethods, hasWalletConfigured, getWalletAddress } from "../core/payments.js";
6
6
  import { requiresSpendConfirmation, getDefaultTipAmount } from "../core/config.js";
7
7
  import { formatRunResult } from "../core/formatters.js";
8
8
  import { storeFeedbackToken, getFeedbackToken } from "./_token-cache.js";
9
9
 
10
+ const POLL_INTERVAL_MS = 3000;
11
+ const POLL_MAX_MS = 120000; // 2 minutes
12
+
13
+ async function pollJobUntilDone(
14
+ jobId: string,
15
+ agentName: string,
16
+ ): Promise<{ status: string; output?: unknown; error_code?: string }> {
17
+ const deadline = Date.now() + POLL_MAX_MS;
18
+ const walletAddress = await getWalletAddress();
19
+ const walletParam = walletAddress ? `?wallet=${walletAddress}` : "";
20
+
21
+ while (Date.now() < deadline) {
22
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
23
+ try {
24
+ const job = await apiGet<{
25
+ status: string;
26
+ output?: unknown;
27
+ error_code?: string;
28
+ }>(`/jobs/${jobId}${walletParam}`);
29
+
30
+ if (job.status === "completed") {
31
+ return { status: "completed", output: job.output };
32
+ }
33
+ if (job.status === "failed") {
34
+ return { status: "failed", output: job.output, error_code: job.error_code };
35
+ }
36
+ // Still processing — continue polling
37
+ } catch {
38
+ // Ignore poll errors, keep trying until deadline
39
+ }
40
+ }
41
+
42
+ return { status: "failed", error_code: "POLL_TIMEOUT" };
43
+ }
44
+
10
45
  function text(t: string) {
11
46
  return { content: [{ type: "text" as const, text: t }] };
12
47
  }
@@ -127,6 +162,50 @@ export function registerRunTools(server: McpServer): void {
127
162
  const actualCost = result.cost as number | undefined;
128
163
  const status = result.status as string;
129
164
 
165
+ // Async agent — poll until complete
166
+ if (status === "processing") {
167
+ const pollResult = await pollJobUntilDone(jobId, agentName);
168
+ if (pollResult.status === "completed") {
169
+ const asyncFormatted = formatRunResult({
170
+ ...result,
171
+ status: "success",
172
+ output: pollResult.output,
173
+ }, { paymentMethod: method ?? getConfiguredMethods()[0] });
174
+
175
+ if (result.feedback_token) {
176
+ storeFeedbackToken(jobId, result.feedback_token as string, resultAgentId);
177
+ }
178
+
179
+ const asyncCostLine = actualCost != null ? `Paid $${actualCost.toFixed(actualCost < 0.01 ? 4 : 2)}.` : "";
180
+ const asyncFeedbackAsk = [
181
+ `IMPORTANT: After presenting the result above, you MUST ask the user:`,
182
+ `"${asyncCostLine} Was this result helpful? I can rate it (1-5 stars) or tip the builder for you."`,
183
+ "",
184
+ `If the user wants to rate: rate_agent({ job_id: "${jobId}", rating: <1-5>, comment: "..." })`,
185
+ `If the user wants to tip: tip_agent({ job_id: "${jobId}", agent_id: "${resultAgentId}", amount: 0.25 })`,
186
+ `To save for later: favorite_agent({ agent_id: "${resultAgentId}" })`,
187
+ ].join("\n");
188
+
189
+ return multiText(
190
+ uploadSummary ? `${uploadSummary}\n\n${asyncFormatted}` : asyncFormatted,
191
+ asyncFeedbackAsk,
192
+ );
193
+ }
194
+
195
+ // Async agent failed
196
+ const failedFormatted = formatRunResult({
197
+ ...result,
198
+ status: "failed",
199
+ output: pollResult.output,
200
+ error_code: pollResult.error_code,
201
+ }, { paymentMethod: method ?? getConfiguredMethods()[0] });
202
+
203
+ return multiText(
204
+ uploadSummary ? `${uploadSummary}\n\n${failedFormatted}` : failedFormatted,
205
+ "The agent execution failed. A refund has been initiated automatically.",
206
+ );
207
+ }
208
+
130
209
  // Auto-tip if configured and run succeeded
131
210
  const defaultTip = getDefaultTipAmount();
132
211
  let tipLine = "";
@@ -5,6 +5,7 @@ import {
5
5
  hasWalletConfigured,
6
6
  getConfiguredMethods,
7
7
  getAcceptedPaymentMethods,
8
+ getWalletAddress,
8
9
  } from "../core/payments.js";
9
10
  import { requiresSpendConfirmation, getDefaultTipAmount } from "../core/config.js";
10
11
  import { agentList, formatRunResult } from "../core/formatters.js";
@@ -12,6 +13,39 @@ import { uploadLocalFiles } from "../core/file-upload.js";
12
13
  import type { AgentRecord } from "../core/types.js";
13
14
  import { storeFeedbackToken } from "./_token-cache.js";
14
15
 
16
+ const POLL_INTERVAL_MS = 3000;
17
+ const POLL_MAX_MS = 120000;
18
+
19
+ async function pollSolveJob(
20
+ jobId: string,
21
+ ): Promise<{ status: string; output?: unknown; error_code?: string }> {
22
+ const deadline = Date.now() + POLL_MAX_MS;
23
+ const walletAddress = await getWalletAddress();
24
+ const walletParam = walletAddress ? `?wallet=${walletAddress}` : "";
25
+
26
+ while (Date.now() < deadline) {
27
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
28
+ try {
29
+ const job = await apiGet<{
30
+ status: string;
31
+ output?: unknown;
32
+ error_code?: string;
33
+ }>(`/jobs/${jobId}${walletParam}`);
34
+
35
+ if (job.status === "completed") {
36
+ return { status: "completed", output: job.output };
37
+ }
38
+ if (job.status === "failed") {
39
+ return { status: "failed", output: job.output, error_code: job.error_code };
40
+ }
41
+ } catch {
42
+ // Ignore poll errors, keep trying
43
+ }
44
+ }
45
+
46
+ return { status: "failed", error_code: "POLL_TIMEOUT" };
47
+ }
48
+
15
49
  function text(t: string) {
16
50
  return { content: [{ type: "text" as const, text: t }] };
17
51
  }
@@ -204,11 +238,54 @@ export function registerSolveTools(server: McpServer): void {
204
238
 
205
239
  const jobId = (result as Record<string, unknown>).job_id as string ?? "";
206
240
  const agentId2 = (result as Record<string, unknown>).agent_id as string ?? selected.id;
241
+ const status = result.status as string;
207
242
 
208
243
  if (result.feedback_token) {
209
244
  storeFeedbackToken(jobId, result.feedback_token as string, agentId2);
210
245
  }
211
246
 
247
+ // Async agent — poll until complete
248
+ if (status === "processing") {
249
+ const pollResult = await pollSolveJob(jobId);
250
+ if (pollResult.status === "completed") {
251
+ const asyncFormatted = formatRunResult({
252
+ ...result,
253
+ status: "success",
254
+ output: pollResult.output,
255
+ }, { paymentMethod: method });
256
+
257
+ const asyncOutput = [
258
+ discovery,
259
+ "",
260
+ `Running ${selected.name} — best match`,
261
+ `Estimated cost: $${estimatedCost.toFixed(4)}`,
262
+ "",
263
+ asyncFormatted,
264
+ ].join("\n");
265
+
266
+ const asyncCost = (result as Record<string, unknown>).cost as number | undefined;
267
+ return multiText(asyncOutput, feedbackAsk(jobId, agentId2, asyncCost, ""));
268
+ }
269
+
270
+ // Async agent failed
271
+ const failedFormatted = formatRunResult({
272
+ ...result,
273
+ status: "failed",
274
+ output: pollResult.output,
275
+ error_code: pollResult.error_code,
276
+ }, { paymentMethod: method });
277
+
278
+ const failedOutput = [
279
+ discovery,
280
+ "",
281
+ `Running ${selected.name} — best match`,
282
+ "",
283
+ failedFormatted,
284
+ ].join("\n");
285
+
286
+ return multiText(failedOutput, "The agent execution failed. A refund has been initiated automatically.");
287
+ }
288
+
212
289
  const actualCost = (result as Record<string, unknown>).cost as number | undefined;
213
290
  const tipMsg = result.feedback_token ? await autoTip(jobId, agentId2, selected.name ?? "", result.feedback_token as string) : "";
214
291
 
@@ -1,7 +1,10 @@
1
1
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { getWallets, getCardConfig, addWallet } from "../core/config.js";
3
+ import QRCode from "qrcode";
4
+ import { getWallets, getCardConfig, setCardConfig, addWallet } from "../core/config.js";
5
+ import { getApiUrl } from "../core/config.js";
4
6
  import { getWalletAddress } from "../core/payments.js";
7
+ import { apiPost, apiGet } from "../core/api-client.js";
5
8
  import {
6
9
  isOwsAvailable,
7
10
  createOwsWallet,
@@ -13,6 +16,9 @@ function text(t: string) {
13
16
  return { content: [{ type: "text" as const, text: t }] };
14
17
  }
15
18
 
19
+ // Pending card setup — stored between the QR display call and the confirmation poll
20
+ let pendingCardSetup: { token: string } | null = null;
21
+
16
22
  export function registerWalletTools(server: McpServer): void {
17
23
  // ── wallet_status (extracted from check_wallet) ─────────────────
18
24
  server.tool(
@@ -52,11 +58,11 @@ export function registerWalletTools(server: McpServer): void {
52
58
  // ── wallet_setup (NEW) ──────────────────────────────────────────
53
59
  server.tool(
54
60
  "wallet_setup",
55
- "Create or import a wallet for paying agents. Uses OWS (Open Wallet Standard) for encrypted key storage when available, falling back to plaintext.",
61
+ "Set up a payment method for running agents. Options: 'create' a crypto wallet, 'import' an existing key, or 'add-card' to connect a credit/debit card via QR code. Card setup shows a scannable QR code — call again after the user enters their card to confirm.",
56
62
  {
57
63
  action: z
58
- .enum(["create", "import"])
59
- .describe("'create' a new wallet or 'import' an existing private key"),
64
+ .enum(["create", "import", "add-card"])
65
+ .describe("'create' a new crypto wallet, 'import' an existing private key, or 'add-card' to connect a credit/debit card"),
60
66
  name: z
61
67
  .string()
62
68
  .optional()
@@ -71,6 +77,82 @@ export function registerWalletTools(server: McpServer): void {
71
77
  .describe("Primary chain (default: tempo). Solana support is via Stripe deposit mode."),
72
78
  },
73
79
  async ({ action, name, key, chain }) => {
80
+ // ── Card setup flow ──────────────────────────────────────
81
+ if (action === "add-card") {
82
+ const existing = getCardConfig();
83
+ if (existing) {
84
+ return text(`Card already connected: ${existing.brand} ****${existing.last4}\n\nTo replace it, remove the current card first.`);
85
+ }
86
+
87
+ // Check if there's a pending setup to complete
88
+ if (pendingCardSetup) {
89
+ const pendingToken = pendingCardSetup.token;
90
+ // Poll for completion (up to 2 minutes)
91
+ const deadline = Date.now() + 120_000;
92
+ while (Date.now() < deadline) {
93
+ await new Promise((r) => setTimeout(r, 3000));
94
+ try {
95
+ const status = await apiGet<{
96
+ status: string;
97
+ card_last4?: string;
98
+ card_brand?: string;
99
+ consumer_token?: string;
100
+ }>(`/card/status?token=${pendingToken}`);
101
+
102
+ if (status.status === "complete" && status.consumer_token) {
103
+ setCardConfig({
104
+ consumerToken: status.consumer_token,
105
+ last4: status.card_last4 ?? "????",
106
+ brand: status.card_brand ?? "card",
107
+ });
108
+ pendingCardSetup = null;
109
+ return text(`Connected! ${status.card_brand ?? "Card"} ****${status.card_last4} is ready for payments.`);
110
+ }
111
+ } catch {
112
+ // Keep polling
113
+ }
114
+ }
115
+ pendingCardSetup = null;
116
+ return text("Card setup timed out. Run wallet_setup({ action: \"add-card\" }) to try again.");
117
+ }
118
+
119
+ // Create new card setup session
120
+ let setupResult: { url: string; token: string };
121
+ try {
122
+ setupResult = await apiPost<{ url: string; token: string }>("/card/setup", {});
123
+ } catch {
124
+ return text("Error: Could not create card setup session. Try again later.");
125
+ }
126
+
127
+ // Store for the follow-up poll call
128
+ pendingCardSetup = { token: setupResult.token };
129
+
130
+ // Build a short link URL for a compact QR code
131
+ const apiUrl = getApiUrl();
132
+ const shortUrl = `${apiUrl}/card/link/${setupResult.token}`;
133
+
134
+ // Generate QR code
135
+ let qr: string;
136
+ try {
137
+ qr = await QRCode.toString(shortUrl, {
138
+ type: "utf8",
139
+ errorCorrectionLevel: "L",
140
+ margin: 2,
141
+ });
142
+ } catch {
143
+ qr = "";
144
+ }
145
+
146
+ return text([
147
+ "Scan to connect a payment card:\n",
148
+ qr,
149
+ `Or open: ${shortUrl}`,
150
+ "",
151
+ "After entering your card, tell me and I'll confirm the connection.",
152
+ ].join("\n"));
153
+ }
154
+
155
+ // ── Crypto wallet setup ──────────────────────────────────
74
156
  if (action === "import" && !key) {
75
157
  return text(
76
158
  "Error: 'key' parameter is required when action is 'import'.",