@agentwonderland/mcp 0.1.53 → 0.1.55

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.
@@ -1,6 +1,6 @@
1
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { MCP_PACKAGE_VERSION } from "../version.js";
3
- const { mockGetApiUrl, mockGetApiKey, mockGetPaymentFetch, mockEnsureConsumerPrincipalForMethod, mockEnsureBaseRebatePrincipal, mockGetConsumerPrincipalForMethod, mockGetBaseRebatePrincipal, mockPaymentFetch, } = vi.hoisted(() => ({
3
+ const { mockGetApiUrl, mockGetApiKey, mockGetPaymentFetch, mockEnsureConsumerPrincipalForMethod, mockEnsureBaseRebatePrincipal, mockGetConsumerPrincipalForMethod, mockGetBaseRebatePrincipal, mockPaymentFetch, mockPayMppWithApprovedLinkSpendRequest, } = vi.hoisted(() => ({
4
4
  mockGetApiUrl: vi.fn(),
5
5
  mockGetApiKey: vi.fn(),
6
6
  mockGetPaymentFetch: vi.fn(),
@@ -9,6 +9,7 @@ const { mockGetApiUrl, mockGetApiKey, mockGetPaymentFetch, mockEnsureConsumerPri
9
9
  mockGetConsumerPrincipalForMethod: vi.fn(),
10
10
  mockGetBaseRebatePrincipal: vi.fn(),
11
11
  mockPaymentFetch: vi.fn(),
12
+ mockPayMppWithApprovedLinkSpendRequest: vi.fn(),
12
13
  }));
13
14
  vi.mock("../config.js", () => ({
14
15
  getApiUrl: () => mockGetApiUrl(),
@@ -25,6 +26,9 @@ vi.mock("../principal.js", () => ({
25
26
  getConsumerPrincipalForMethod: (...args) => mockGetConsumerPrincipalForMethod(...args),
26
27
  getBaseRebatePrincipal: (...args) => mockGetBaseRebatePrincipal(...args),
27
28
  }));
29
+ vi.mock("../link-cli.js", () => ({
30
+ payMppWithApprovedLinkSpendRequest: (...args) => mockPayMppWithApprovedLinkSpendRequest(...args),
31
+ }));
28
32
  describe("api-client headers", () => {
29
33
  beforeEach(() => {
30
34
  vi.clearAllMocks();
@@ -39,6 +43,7 @@ describe("api-client headers", () => {
39
43
  status: 200,
40
44
  headers: { "content-type": "application/json" },
41
45
  }));
46
+ mockPayMppWithApprovedLinkSpendRequest.mockResolvedValue({ ok: true });
42
47
  });
43
48
  it("includes the Base rebate principal alongside the method-specific consumer principal", async () => {
44
49
  const { apiPostWithPayment } = await import("../api-client.js");
@@ -56,4 +61,63 @@ describe("api-client headers", () => {
56
61
  }),
57
62
  }));
58
63
  });
64
+ it("labels playbook API calls with MCP surface, version, tool, and action headers", async () => {
65
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true }), {
66
+ status: 200,
67
+ headers: { "content-type": "application/json" },
68
+ }));
69
+ vi.stubGlobal("fetch", fetchMock);
70
+ const { apiGet, apiPost } = await import("../api-client.js");
71
+ await apiGet("/playbooks?limit=1");
72
+ await apiGet("/playbooks/competitor-ads");
73
+ await apiGet("/playbooks/competitor-ads/versions");
74
+ await apiGet("/playbooks/competitor-ads/versions/1");
75
+ await apiPost("/playbooks/competitor-ads/favorite", {});
76
+ await apiPost("/playbooks/competitor-ads/feedback", { rating: 5 });
77
+ await apiPost("/playbook-quotes", { slug: "competitor-ads", budget: 5 });
78
+ await apiPost("/playbook-runs", { slug: "competitor-ads", budget: 5 });
79
+ await apiGet("/playbook-runs/run-1");
80
+ await apiPost("/playbook-runs/run-1/steps/ads", { status: "running" });
81
+ const calls = fetchMock.mock.calls.map(([url, init]) => ({
82
+ url: String(url).replace("https://api.agentwonderland.test", ""),
83
+ headers: init.headers,
84
+ }));
85
+ for (const call of calls) {
86
+ expect(call.headers).toMatchObject({
87
+ "Content-Type": "application/json",
88
+ Accept: "application/json",
89
+ "X-AW-Surface": "mcp",
90
+ "X-AW-MCP-Version": MCP_PACKAGE_VERSION,
91
+ });
92
+ }
93
+ expect(calls[0]).toMatchObject({ url: "/playbooks?limit=1", headers: { "X-AW-MCP-Tool": "search_playbooks", "X-AW-MCP-Action": "search" } });
94
+ expect(calls[1]).toMatchObject({ url: "/playbooks/competitor-ads", headers: { "X-AW-MCP-Tool": "get_playbook", "X-AW-MCP-Action": "view" } });
95
+ expect(calls[2]).toMatchObject({ url: "/playbooks/competitor-ads/versions", headers: { "X-AW-MCP-Tool": "get_playbook", "X-AW-MCP-Action": "view" } });
96
+ expect(calls[3]).toMatchObject({ url: "/playbooks/competitor-ads/versions/1", headers: { "X-AW-MCP-Tool": "get_playbook", "X-AW-MCP-Action": "view" } });
97
+ expect(calls[4]).toMatchObject({ url: "/playbooks/competitor-ads/favorite", headers: { "X-AW-MCP-Tool": "favorite_playbook", "X-AW-MCP-Action": "favorite" } });
98
+ expect(calls[5]).toMatchObject({ url: "/playbooks/competitor-ads/feedback", headers: { "X-AW-MCP-Tool": "rate_playbook", "X-AW-MCP-Action": "feedback" } });
99
+ expect(calls[6]).toMatchObject({ url: "/playbook-quotes", headers: { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": "quote" } });
100
+ expect(calls[7]).toMatchObject({ url: "/playbook-runs", headers: { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": "execute" } });
101
+ expect(calls[8]).toMatchObject({ url: "/playbook-runs/run-1", headers: { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": "poll" } });
102
+ expect(calls[9]).toMatchObject({ url: "/playbook-runs/run-1/steps/ads", headers: { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": "execute" } });
103
+ });
104
+ it("uses Link MPP pay with run-agent headers for an approved spend request", async () => {
105
+ const { apiPostWithApprovedLinkSpendRequest } = await import("../api-client.js");
106
+ await apiPostWithApprovedLinkSpendRequest("/agents/agent-1/run", { input: { text: "hello" } }, "lsrq_test_123");
107
+ expect(mockPayMppWithApprovedLinkSpendRequest).toHaveBeenCalledWith(expect.objectContaining({
108
+ url: "https://api.agentwonderland.test/agents/agent-1/run",
109
+ method: "POST",
110
+ body: { input: { text: "hello" } },
111
+ spendRequestId: "lsrq_test_123",
112
+ headers: expect.objectContaining({
113
+ "Content-Type": "application/json",
114
+ Accept: "application/json",
115
+ "X-AW-Surface": "mcp",
116
+ "X-AW-MCP-Version": MCP_PACKAGE_VERSION,
117
+ "X-AW-MCP-Tool": "run_agent",
118
+ "X-AW-MCP-Action": "execute",
119
+ }),
120
+ }));
121
+ expect(mockEnsureConsumerPrincipalForMethod).toHaveBeenCalledWith("link");
122
+ });
59
123
  });
@@ -99,4 +99,99 @@ describe("Link CLI spend requests", () => {
99
99
  expect(execCalls[0]?.args).toEqual(expect.arrayContaining(["spend-request", "retrieve", "lsrq_test_123"]));
100
100
  expect(state.pendingWrites).toEqual([null]);
101
101
  });
102
+ it("reuses an approved spend request id for playbook MPP payments", async () => {
103
+ const expiresAt = Math.floor(Date.now() / 1000) + 300;
104
+ state.pending = {
105
+ id: "lsrq_test_123",
106
+ approvalUrl: "https://link.example/approve/lsrq_test_123",
107
+ amount: "500",
108
+ currency: "usd",
109
+ context: "Agent Wonderland playbook test context that is long enough for Link",
110
+ expiresAt,
111
+ networkId: "profile_test",
112
+ paymentMethodId: "csmrpd_test_123",
113
+ createdAt: new Date().toISOString(),
114
+ };
115
+ outputs.push({ id: "lsrq_test_123", status: "approved" });
116
+ const { ensureApprovedLinkSpendRequest } = await import("../link-cli.js");
117
+ await expect(ensureApprovedLinkSpendRequest({
118
+ amount: "500",
119
+ currency: "usd",
120
+ context: "Agent Wonderland playbook test context that is long enough for Link",
121
+ expiresAt,
122
+ networkId: "profile_test",
123
+ paymentMethodId: "csmrpd_test_123",
124
+ })).resolves.toBe("lsrq_test_123");
125
+ expect(execCalls).toHaveLength(1);
126
+ expect(execCalls[0]?.args).toEqual(expect.arrayContaining(["spend-request", "retrieve", "lsrq_test_123"]));
127
+ expect(state.pendingWrites).toEqual([]);
128
+ });
129
+ it("pauses when the reusable Link spend request is still pending approval", async () => {
130
+ const expiresAt = Math.floor(Date.now() / 1000) + 300;
131
+ state.pending = {
132
+ id: "lsrq_test_123",
133
+ approvalUrl: "https://link.example/approve/lsrq_test_123",
134
+ amount: "500",
135
+ currency: "usd",
136
+ context: "Agent Wonderland playbook test context that is long enough for Link",
137
+ expiresAt,
138
+ networkId: "profile_test",
139
+ paymentMethodId: "csmrpd_test_123",
140
+ createdAt: new Date().toISOString(),
141
+ };
142
+ outputs.push({ id: "lsrq_test_123", status: "pending_approval" });
143
+ const { ensureApprovedLinkSpendRequest, LinkApprovalRequiredError } = await import("../link-cli.js");
144
+ await expect(ensureApprovedLinkSpendRequest({
145
+ amount: "500",
146
+ currency: "usd",
147
+ context: "Agent Wonderland playbook test context that is long enough for Link",
148
+ expiresAt,
149
+ networkId: "profile_test",
150
+ paymentMethodId: "csmrpd_test_123",
151
+ })).rejects.toBeInstanceOf(LinkApprovalRequiredError);
152
+ expect(execCalls).toHaveLength(1);
153
+ expect(state.pendingWrites).toEqual([]);
154
+ });
155
+ it("runs Link MPP pay with an approved spend request and returns the response body", async () => {
156
+ outputs.push({
157
+ response: {
158
+ body: {
159
+ status: "success",
160
+ job_id: "job_123",
161
+ },
162
+ },
163
+ });
164
+ const { payMppWithApprovedLinkSpendRequest } = await import("../link-cli.js");
165
+ await expect(payMppWithApprovedLinkSpendRequest({
166
+ url: "https://api.agentwonderland.test/agents/agent-1/run",
167
+ method: "POST",
168
+ headers: {
169
+ Accept: "application/json",
170
+ "Content-Type": "application/json",
171
+ },
172
+ body: { input: { text: "hello" } },
173
+ spendRequestId: "lsrq_test_123",
174
+ })).resolves.toEqual({
175
+ status: "success",
176
+ job_id: "job_123",
177
+ });
178
+ expect(execCalls[0]?.args).toEqual(expect.arrayContaining([
179
+ "mpp",
180
+ "pay",
181
+ "https://api.agentwonderland.test/agents/agent-1/run",
182
+ "--spend-request-id",
183
+ "lsrq_test_123",
184
+ "--method",
185
+ "POST",
186
+ "--data",
187
+ JSON.stringify({ input: { text: "hello" } }),
188
+ ]));
189
+ expect(execCalls[0]?.args).toContain("Accept: application/json");
190
+ });
191
+ it("decodes the MPP network id from a payment challenge", async () => {
192
+ outputs.push({ accepts: [{ network_id: "profile_test" }] });
193
+ const { decodeMppNetworkId } = await import("../link-cli.js");
194
+ await expect(decodeMppNetworkId("Payment challenge")).resolves.toBe("profile_test");
195
+ expect(execCalls[0]?.args).toEqual(expect.arrayContaining(["mpp", "decode", "--challenge", "Payment challenge"]));
196
+ });
102
197
  });
@@ -1,7 +1,8 @@
1
1
  export declare class ApiError extends Error {
2
2
  readonly status: number;
3
3
  readonly body?: unknown | undefined;
4
- constructor(status: number, message: string, body?: unknown | undefined);
4
+ readonly headers?: Headers | undefined;
5
+ constructor(status: number, message: string, body?: unknown | undefined, headers?: Headers | undefined);
5
6
  }
6
7
  interface RequestOptions {
7
8
  ensureConsumerPrincipal?: boolean;
@@ -16,5 +17,6 @@ export declare function apiPost<T>(path: string, body: unknown, options?: Reques
16
17
  * Pass `payWith` to specify a method, or omit for auto-detection.
17
18
  */
18
19
  export declare function apiPostWithPayment<T>(path: string, body: unknown, payWith?: string, options?: RequestOptions): Promise<T>;
20
+ export declare function apiPostWithApprovedLinkSpendRequest<T>(path: string, body: unknown, spendRequestId: string, options?: RequestOptions): Promise<T>;
19
21
  export declare function apiPut<T>(path: string, body: unknown, options?: RequestOptions): Promise<T>;
20
22
  export {};
@@ -2,14 +2,17 @@ import { getApiUrl, getApiKey } from "./config.js";
2
2
  import { getPaymentFetch } from "./payments.js";
3
3
  import { getBaseRebatePrincipal, ensureBaseRebatePrincipal, ensureConsumerPrincipalForMethod, getConsumerPrincipalForMethod, } from "./principal.js";
4
4
  import { MCP_PACKAGE_VERSION } from "./version.js";
5
+ import { payMppWithApprovedLinkSpendRequest } from "./link-cli.js";
5
6
  // ── Error class ────────────────────────────────────────────────────
6
7
  export class ApiError extends Error {
7
8
  status;
8
9
  body;
9
- constructor(status, message, body) {
10
+ headers;
11
+ constructor(status, message, body, headers) {
10
12
  super(message);
11
13
  this.status = status;
12
14
  this.body = body;
15
+ this.headers = headers;
13
16
  this.name = "ApiError";
14
17
  }
15
18
  }
@@ -23,6 +26,24 @@ function inferToolHeaders(path, method) {
23
26
  if (path.startsWith("/agents?") || path === "/agents" || path === "/agents/search") {
24
27
  return { "X-AW-MCP-Tool": "search_agents", "X-AW-MCP-Action": "search" };
25
28
  }
29
+ if (path.startsWith("/playbooks?") || path === "/playbooks") {
30
+ return { "X-AW-MCP-Tool": "search_playbooks", "X-AW-MCP-Action": "search" };
31
+ }
32
+ if (/^\/playbooks\/[^/]+(?:\/versions(?:\/[^/]+)?)?$/.test(path)) {
33
+ return { "X-AW-MCP-Tool": "get_playbook", "X-AW-MCP-Action": "view" };
34
+ }
35
+ if (/^\/playbooks\/[^/]+\/favorite$/.test(path)) {
36
+ return { "X-AW-MCP-Tool": "favorite_playbook", "X-AW-MCP-Action": "favorite" };
37
+ }
38
+ if (/^\/playbooks\/[^/]+\/feedback$/.test(path)) {
39
+ return { "X-AW-MCP-Tool": "rate_playbook", "X-AW-MCP-Action": "feedback" };
40
+ }
41
+ if (path === "/playbook-quotes") {
42
+ return { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": "quote" };
43
+ }
44
+ if (path === "/playbook-runs" || path.startsWith("/playbook-runs/")) {
45
+ return { "X-AW-MCP-Tool": "run_playbook", "X-AW-MCP-Action": method === "GET" ? "poll" : "execute" };
46
+ }
26
47
  if (/^\/agents\/[^/]+$/.test(path)) {
27
48
  return { "X-AW-MCP-Tool": "get_agent", "X-AW-MCP-Action": "view" };
28
49
  }
@@ -78,7 +99,7 @@ async function handleResponse(response) {
78
99
  : typeof body === "string"
79
100
  ? body
80
101
  : `Request failed with status ${response.status}`;
81
- throw new ApiError(response.status, message, body);
102
+ throw new ApiError(response.status, message, body, response.headers);
82
103
  }
83
104
  return body;
84
105
  }
@@ -145,6 +166,22 @@ export async function apiPostWithPayment(path, body, payWith, options) {
145
166
  const result = await handleResponse(response);
146
167
  return attachResponseMetadata(result, response);
147
168
  }
169
+ export async function apiPostWithApprovedLinkSpendRequest(path, body, spendRequestId, options) {
170
+ const url = `${getApiUrl()}${path}`;
171
+ const headers = await buildHeaders(path, "POST", {
172
+ ensureConsumerPrincipal: true,
173
+ principalMethod: "link",
174
+ ...options,
175
+ });
176
+ const result = await payMppWithApprovedLinkSpendRequest({
177
+ url,
178
+ method: "POST",
179
+ headers,
180
+ body,
181
+ spendRequestId,
182
+ });
183
+ return result;
184
+ }
148
185
  export async function apiPut(path, body, options) {
149
186
  const url = `${getApiUrl()}${path}`;
150
187
  const response = await fetch(url, {
@@ -3,6 +3,14 @@ export declare class LinkApprovalRequiredError extends Error {
3
3
  readonly approvalUrl?: string | undefined;
4
4
  constructor(spendRequestId: string, approvalUrl?: string | undefined);
5
5
  }
6
+ export interface ApprovedLinkSpendRequestParams {
7
+ amount: string;
8
+ currency: string;
9
+ context: string;
10
+ expiresAt: number;
11
+ networkId: string;
12
+ paymentMethodId: string;
13
+ }
6
14
  export interface LinkCliAuthStatus {
7
15
  authenticated: boolean;
8
16
  credentialsPath?: string;
@@ -30,3 +38,12 @@ export declare function createLinkSharedPaymentToken(params: {
30
38
  networkId: string;
31
39
  paymentMethodId: string;
32
40
  }): Promise<string>;
41
+ export declare function ensureApprovedLinkSpendRequest(params: ApprovedLinkSpendRequestParams): Promise<string>;
42
+ export declare function payMppWithApprovedLinkSpendRequest(params: {
43
+ url: string;
44
+ method: string;
45
+ headers: Record<string, string>;
46
+ body?: unknown;
47
+ spendRequestId: string;
48
+ }): Promise<unknown>;
49
+ export declare function decodeMppNetworkId(challenge: string): Promise<string>;
@@ -108,6 +108,16 @@ function extractSpendRequestApproval(output) {
108
108
  }
109
109
  return null;
110
110
  }
111
+ function extractSpendRequestStatus(output) {
112
+ const record = Array.isArray(output) ? asRecord(output[0]) : asRecord(output);
113
+ if (!record)
114
+ return {};
115
+ return {
116
+ id: typeof record.id === "string" ? record.id : undefined,
117
+ approvalUrl: typeof record.approval_url === "string" ? record.approval_url : undefined,
118
+ status: typeof record.status === "string" ? record.status : undefined,
119
+ };
120
+ }
111
121
  function isMatchingPendingSpendRequest(pending, params) {
112
122
  if (!pending)
113
123
  return false;
@@ -128,6 +138,12 @@ function isMatchingPendingSpendRequest(pending, params) {
128
138
  function isProjectedSpendCapError(message) {
129
139
  return /projected daily spend|projected spend|exceeds limit/i.test(message);
130
140
  }
141
+ function isApprovedSpendRequestStatus(status) {
142
+ return /approved|active|ready/i.test(status ?? "");
143
+ }
144
+ function isPendingSpendRequestStatus(status) {
145
+ return /pending/i.test(status ?? "");
146
+ }
131
147
  function recordLinkCooldown(reason) {
132
148
  const now = new Date();
133
149
  setLinkCooldown({
@@ -317,6 +333,155 @@ export async function createLinkSharedPaymentToken(params) {
317
333
  throw new Error("Link spend request completed without a shared payment token in the CLI response.");
318
334
  }
319
335
  }
336
+ export async function ensureApprovedLinkSpendRequest(params) {
337
+ const existing = getPendingLinkSpendRequest();
338
+ if (isMatchingPendingSpendRequest(existing, params)) {
339
+ const retrieved = await runLinkCli([
340
+ "spend-request",
341
+ "retrieve",
342
+ existing.id,
343
+ ], 30_000);
344
+ const status = extractSpendRequestStatus(retrieved);
345
+ if (isApprovedSpendRequestStatus(status.status)) {
346
+ return existing.id;
347
+ }
348
+ if (isPendingSpendRequestStatus(status.status)) {
349
+ throw new LinkApprovalRequiredError(existing.id, existing.approvalUrl ?? status.approvalUrl);
350
+ }
351
+ setPendingLinkSpendRequest(null);
352
+ }
353
+ const args = [
354
+ "spend-request",
355
+ "create",
356
+ "--credential-type",
357
+ "shared_payment_token",
358
+ "--network-id",
359
+ params.networkId,
360
+ "--amount",
361
+ params.amount,
362
+ "--currency",
363
+ params.currency,
364
+ "--payment-method-id",
365
+ params.paymentMethodId,
366
+ "--context",
367
+ params.context,
368
+ "--request-approval",
369
+ ];
370
+ if (process.env.AGENTWONDERLAND_LINK_TEST_MODE === "1") {
371
+ args.push("--test");
372
+ }
373
+ let output;
374
+ try {
375
+ output = await runLinkCli(args);
376
+ }
377
+ catch (err) {
378
+ const message = err instanceof Error ? err.message : String(err);
379
+ if (isProjectedSpendCapError(message)) {
380
+ recordLinkCooldown(message);
381
+ throw new Error([
382
+ "Link is temporarily blocked by Stripe's projected-spend cap.",
383
+ "Reauthing Link or switching cards in the same Link account will not fix this.",
384
+ "Use USDC for now, wait for the rolling Link window to clear, or ask Stripe to raise/clear the merchant projected-spend cap.",
385
+ "",
386
+ message,
387
+ ].join("\n"));
388
+ }
389
+ throw err;
390
+ }
391
+ const status = extractSpendRequestStatus(output);
392
+ const id = status.id ?? extractSpendRequestApproval(output)?.id;
393
+ if (id && isApprovedSpendRequestStatus(status.status)) {
394
+ setPendingLinkSpendRequest({
395
+ id,
396
+ approvalUrl: status.approvalUrl,
397
+ amount: params.amount,
398
+ currency: params.currency,
399
+ context: params.context,
400
+ expiresAt: params.expiresAt,
401
+ networkId: params.networkId,
402
+ paymentMethodId: params.paymentMethodId,
403
+ createdAt: new Date().toISOString(),
404
+ });
405
+ return id;
406
+ }
407
+ const approval = extractSpendRequestApproval(output);
408
+ if (approval?.id && isPendingSpendRequestStatus(approval.status)) {
409
+ setPendingLinkSpendRequest({
410
+ id: approval.id,
411
+ approvalUrl: approval.approvalUrl,
412
+ amount: params.amount,
413
+ currency: params.currency,
414
+ context: params.context,
415
+ expiresAt: params.expiresAt,
416
+ networkId: params.networkId,
417
+ paymentMethodId: params.paymentMethodId,
418
+ createdAt: new Date().toISOString(),
419
+ });
420
+ if (approval.approvalUrl) {
421
+ console.error(`Link approval required: ${approval.approvalUrl}`);
422
+ }
423
+ throw new LinkApprovalRequiredError(approval.id, approval.approvalUrl);
424
+ }
425
+ throw new Error("Link spend request did not return an approved or pending approval state.");
426
+ }
427
+ function extractMppPayBody(output) {
428
+ if (typeof output === "string") {
429
+ try {
430
+ return JSON.parse(output);
431
+ }
432
+ catch {
433
+ return output;
434
+ }
435
+ }
436
+ if (Array.isArray(output)) {
437
+ return output.length === 1 ? extractMppPayBody(output[0]) : output;
438
+ }
439
+ const record = asRecord(output);
440
+ if (!record)
441
+ return output;
442
+ for (const key of ["body", "json", "data", "response_body"]) {
443
+ const value = record[key];
444
+ if (value !== undefined)
445
+ return extractMppPayBody(value);
446
+ }
447
+ const response = asRecord(record.response);
448
+ if (response)
449
+ return extractMppPayBody(response.body ?? response.json ?? response.data ?? response);
450
+ return output;
451
+ }
452
+ export async function payMppWithApprovedLinkSpendRequest(params) {
453
+ const args = [
454
+ "mpp",
455
+ "pay",
456
+ params.url,
457
+ "--spend-request-id",
458
+ params.spendRequestId,
459
+ "--method",
460
+ params.method,
461
+ ];
462
+ for (const [name, value] of Object.entries(params.headers)) {
463
+ args.push("--header", `${name}: ${value}`);
464
+ }
465
+ if (params.body !== undefined) {
466
+ args.push("--data", typeof params.body === "string" ? params.body : JSON.stringify(params.body));
467
+ }
468
+ const output = await runLinkCli(args);
469
+ return extractMppPayBody(output);
470
+ }
471
+ export async function decodeMppNetworkId(challenge) {
472
+ const output = await runLinkCli(["mpp", "decode", "--challenge", challenge], 30_000);
473
+ const found = walk(output, (value, key) => {
474
+ if (typeof value !== "string")
475
+ return null;
476
+ if (key && /network[_-]?id/i.test(key))
477
+ return value;
478
+ return null;
479
+ });
480
+ if (!found) {
481
+ throw new Error("Could not decode Link MPP network_id from payment challenge.");
482
+ }
483
+ return found;
484
+ }
320
485
  async function retrieveSharedPaymentToken(spendRequestId, approvalUrl) {
321
486
  const retrieved = await runLinkCli([
322
487
  "spend-request",
@@ -1 +1 @@
1
- export declare const MCP_PACKAGE_VERSION = "0.1.51";
1
+ export declare const MCP_PACKAGE_VERSION = "0.1.55";
@@ -1 +1 @@
1
- export const MCP_PACKAGE_VERSION = "0.1.51";
1
+ export const MCP_PACKAGE_VERSION = "0.1.55";
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ import { registerRebateTools } from "./tools/rebates.js";
16
16
  import { registerUploadTools } from "./tools/upload.js";
17
17
  import { registerProbeTools } from "./tools/probe.js";
18
18
  import { registerProviderTools } from "./tools/providers.js";
19
+ import { registerPlaybookTools } from "./tools/playbooks.js";
19
20
  // ── Resources ────────────────────────────────────────────────────
20
21
  import { registerAgentResources } from "./resources/agents.js";
21
22
  import { registerWalletResources } from "./resources/wallet.js";
@@ -41,16 +42,17 @@ export async function startMcpServer() {
41
42
  "WORKFLOW:",
42
43
  "1. solve(intent, input, budget) — one call: find best agent + pay + run. Use when the task is clear.",
43
44
  " OR: search_agents() → get_agent() to inspect schema → run_agent() with required fields.",
45
+ " For multi-agent workflows, use search_playbooks() → get_playbook() → run_playbook().",
44
46
  "2. If the agent returns status 'processing', poll with get_job(). Async runs resolve automatically.",
45
- "3. After a successful run, rate_agent() and optionally tip_agent() if the result was useful.",
47
+ "3. After a successful agent run, rate_agent() and optionally tip_agent() if the result was useful.",
48
+ " Playbooks return one run-level receipt; do not ask users to rate or tip individual child-agent steps.",
46
49
  "4. Use list_jobs() to recover state across sessions (it checks every configured wallet).",
47
50
  "",
48
51
  "PAYMENT:",
49
- "- Supported payment methods: Link card/bank via @stripe/link-cli, Tempo USDC, Base USDC, and Solana USDC.",
50
- "- Link payments may ask the user to approve a spend request in Link before the first charge.",
52
+ "- Supported launch payment methods: Tempo USDC, Base USDC, and Solana USDC.",
51
53
  "- Tempo and Base share one EVM wallet key. Solana uses a separate ed25519 key. One OWS wallet can manage both.",
52
54
  "- If pay_with is omitted, the MCP auto-selects a compatible configured rail. Pass pay_with explicitly",
53
- " (tempo | base | solana | link | wallet-id) for deterministic behavior.",
55
+ " (tempo | base | solana | wallet-id) for deterministic behavior.",
54
56
  "- Payment is automatic: on a 402 challenge the MCP signs on-chain, submits, then retries. Failed runs are refunded.",
55
57
  "- If a specific rail fails, surface the real reason — do NOT silently retry with a different method.",
56
58
  "- Headless/automation: set wallet_set_policy() to cap max_per_tx and max_per_day so a runaway loop can't drain funds.",
@@ -66,7 +68,7 @@ export async function startMcpServer() {
66
68
  "WALLET HYGIENE:",
67
69
  "- wallet_status shows per-chain USDC balance and the active network (mainnet vs testnet).",
68
70
  "- rebate_status shows accrued, pending, paid, and blocked consumer rebates plus recent payout transactions.",
69
- "- To set up payments: wallet_setup({ action: \"start\" }). Link card/bank is recommended for most users.",
71
+ "- To set up payments: wallet_setup({ action: \"start\" }). Use Tempo, Base, or Solana USDC for launch runs.",
70
72
  "- To create or import a crypto wallet directly: wallet_setup({ action: \"create\" }) or { action: \"import\", key }.",
71
73
  "- NEVER delete or rotate keys programmatically. Direct users to edit ~/.agentwonderland/config.json or ~/.ows/ manually.",
72
74
  ].join("\n"),
@@ -86,6 +88,7 @@ export async function startMcpServer() {
86
88
  registerUploadTools(server);
87
89
  registerProbeTools(server);
88
90
  registerProviderTools(server);
91
+ registerPlaybookTools(server);
89
92
  // Register resources
90
93
  registerAgentResources(server);
91
94
  registerWalletResources(server);
@@ -0,0 +1 @@
1
+ export {};