mpp32-mcp-server 1.2.4 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,83 @@ All notable changes to `mpp32-mcp-server` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.3.1] - 2026-05-15
8
+
9
+ ### Fixed
10
+
11
+ * **Diagnostics tool referenced non-existent `query_intelligence`.** The
12
+ `get_mpp32_diagnostics` "Ready to pay" message told users to try
13
+ `query_intelligence`, which was never a tool name. Now correctly says
14
+ `get_solana_token_intelligence`.
15
+
16
+ * **`protocol` filter missing from `list_mpp32_services`.** The tool
17
+ description and the backend both support filtering by payment protocol
18
+ (x402, tempo, acp, ap2, agtp), but the parameter was never wired
19
+ through. Added `protocol` as an optional enum parameter and forwarded
20
+ it to the backend query string.
21
+
22
+ * **`server.json` version stuck at 1.2.2.** The MCP registry manifest
23
+ was never bumped past 1.2.2, causing the official registry listing to
24
+ advertise the wrong version. Updated to 1.3.1 with all new env vars.
25
+
26
+ * **`server.json` missing `MPP32_PREFERRED_NETWORK` and `MPP32_TIMEOUT_MS`
27
+ environment variables.** Both were supported since 1.2.3 and 1.1.2
28
+ respectively but never declared in the registry manifest.
29
+
30
+ ### Added
31
+
32
+ * **README now documents all M32-gated tools.** `get_m32_whale_tracker`,
33
+ `compare_tokens_m32`, and `scan_portfolio_m32` were live in the server
34
+ but missing from the README's tools section.
35
+
36
+ * **README now documents `MPP32_SOLANA_RPC_URL` and `MPP32_TIMEOUT_MS`**
37
+ in the configuration table.
38
+
39
+ ## [1.3.0] - 2026-05-14
40
+
41
+ ### Added
42
+
43
+ * **Economic Circuit Breakers — infrastructure-level spending guardrails.**
44
+ The first MCP payment server with built-in budget enforcement. No more
45
+ runaway agent bills.
46
+
47
+ - **`manage_agent_budget` tool** — new MCP tool to view, set, or reset
48
+ spending limits directly from Claude, Cursor, or any MCP client.
49
+ Supports three actions:
50
+ - `get`: View current budget status (remaining balance, hourly velocity,
51
+ circuit breaker state, per-service spending breakdown).
52
+ - `set`: Configure `budgetLimitUsd` (total session cap), `velocityLimitUsd`
53
+ (hourly max), and `alertThresholdPercent` (warning threshold).
54
+ - `reset`: Manually clear a tripped circuit breaker so the session can
55
+ resume spending.
56
+
57
+ - **Per-session budget limits** — set a maximum total spend in USD when
58
+ creating a session or at any time via the new `manage_agent_budget` tool.
59
+ When the limit is reached, the circuit breaker trips and all paid calls
60
+ are blocked until manually reset or the budget is increased.
61
+
62
+ - **Velocity (hourly) limits** — cap how fast an agent can spend. Prevents
63
+ infinite-loop scenarios where an agent drains a wallet in minutes.
64
+
65
+ - **Automatic circuit breaker** — trips instantly when budget or velocity
66
+ limits are exceeded. Sticky by design: agents cannot auto-resume spending.
67
+ Requires explicit reset via the MCP tool or API.
68
+
69
+ - **Budget status in every response** — all `call_mpp32_endpoint` and
70
+ `get_solana_token_intelligence` responses now include remaining budget,
71
+ utilization percentage, and circuit breaker state when limits are
72
+ configured.
73
+
74
+ - **Circuit breaker error handling** — when a circuit breaker is tripped,
75
+ the MCP server returns a clear, actionable message explaining what
76
+ happened and how to resume (via `manage_agent_budget`).
77
+
78
+ ### Changed
79
+
80
+ * **`formatExecuteSuccess` now includes budget status.** When budget limits
81
+ are configured, successful responses include a one-line budget summary
82
+ (remaining balance and utilization %).
83
+
7
84
  ## [1.2.4] - 2026-05-11
8
85
 
9
86
  ### Fixed
package/README.md CHANGED
@@ -35,6 +35,7 @@ MPP32 replaces all of that with one MCP server. Your agent asks for a service by
35
35
  * Run real time Solana token intelligence with alpha scoring, rug risk, whale flow, and 24 hour pump probability.
36
36
  * Track every call, every dollar settled, and every protocol used from a dashboard at mpp32.org.
37
37
  * Get an automatic 20 percent or 40 percent discount on native services for holding M32 once your wallet is verified.
38
+ * Access M32-gated exclusive APIs: Whale Tracker (1M M32), Token Comparison (2.5M M32), and Portfolio Scanner (5M M32) — free for holders, unavailable to non-holders.
38
39
 
39
40
  ## Install
40
41
 
@@ -98,6 +99,8 @@ Tip: call the `get_mpp32_diagnostics` tool from inside Claude. It probes the API
98
99
  | `MPP32_SOLANA_PRIVATE_KEY` | Paid x402 calls on Solana | Base58 encoded Solana secret key. Used to sign USDC payments locally. Never leaves your machine. |
99
100
  | `MPP32_PRIVATE_KEY` | Paid x402 calls on Base | 0x prefixed EVM private key. Used to sign USDC payments on Base when a provider only accepts EVM. |
100
101
  | `MPP32_PREFERRED_NETWORK` | Optional override | When both keys are configured and the challenge advertises multiple networks, force one. Accepts `solana`, `base`, `evm`, or a full CAIP-2 string. |
102
+ | `MPP32_SOLANA_RPC_URL` | Optional | Override the Solana RPC endpoint used to fetch recent blockhashes when building x402 transactions. Defaults to `https://api.mainnet-beta.solana.com`. Set this if you hit public rate limits. |
103
+ | `MPP32_TIMEOUT_MS` | Optional | Request timeout in milliseconds for all outbound API calls. Range 1000 to 300000. Defaults to 30000 (30 seconds). |
101
104
  | `MPP32_API_URL` | Custom deployments | Override the API base URL. Defaults to `https://mpp32.org`. |
102
105
 
103
106
  Private keys stay on your machine. They sign payments locally and never travel to MPP32 servers. Provide either or both for paid calls. If both are present and a challenge advertises both networks, EVM is preferred unless `MPP32_PREFERRED_NETWORK` is set; if only one key is configured, that network wins automatically.
@@ -148,7 +151,55 @@ Real time analysis of any Solana token. Pulls live data from DexScreener, Jupite
148
151
  { "token": "BONK" }
149
152
  ```
150
153
 
151
- M32 holders will get tiered discounts (20 percent at 250k, 40 percent at 1M) once SIWS wallet signature verification ships. The discount path is gated off in production until then so it cannot be claimed by spoofing a wallet header.
154
+ M32 holders get tiered discounts (20 percent at 250k, 40 percent at 1M) once SIWS wallet signature verification ships. The discount path is gated off in production until then so it cannot be claimed by spoofing a wallet header. M32 holders also get exclusive access to three token-gated APIs: Whale Tracker (1M M32), Token Comparison (2.5M M32), and Portfolio Scanner (5M M32) — these are live now and require passing your wallet address via the `X-Wallet-Address` header.
155
+
156
+ ### `get_m32_whale_tracker`
157
+
158
+ M32-gated whale analysis for any Solana token. Returns top 20 holders, concentration risk, holder distribution, and buy/sell pressure. Requires the caller to hold 1,000,000+ M32 tokens (balance verified on-chain). Free for qualifying holders.
159
+
160
+ ```json
161
+ { "token": "<mint-address>", "walletAddress": "<your-solana-wallet>" }
162
+ ```
163
+
164
+ ### `compare_tokens_m32`
165
+
166
+ M32-gated head-to-head intelligence comparison of two Solana tokens. Returns side-by-side alpha scores, rug risk, whale activity, volume, liquidity, and a winner verdict. Requires 2,500,000+ M32 tokens.
167
+
168
+ ```json
169
+ { "tokenA": "<mint-A>", "tokenB": "<mint-B>", "walletAddress": "<your-solana-wallet>" }
170
+ ```
171
+
172
+ ### `scan_portfolio_m32`
173
+
174
+ M32-gated full wallet portfolio scan. Discovers all SPL tokens in a wallet, runs intelligence on top holdings, and returns per-token analysis with aggregate risk metrics. Requires 5,000,000+ M32 tokens.
175
+
176
+ ```json
177
+ { "wallet": "<wallet-to-scan>", "walletAddress": "<your-solana-wallet>" }
178
+ ```
179
+
180
+ ### `manage_agent_budget`
181
+
182
+ View, set, or reset the economic circuit breaker for your agent session. Prevents runaway spending with infrastructure-level budget enforcement.
183
+
184
+ ```json
185
+ { "action": "get" }
186
+ ```
187
+
188
+ ```json
189
+ { "action": "set", "budgetLimitUsd": 10.0, "velocityLimitUsd": 1.0, "alertThresholdPercent": 80 }
190
+ ```
191
+
192
+ ```json
193
+ { "action": "reset" }
194
+ ```
195
+
196
+ Three actions:
197
+
198
+ * **get** returns current budget status: remaining balance, hourly velocity, circuit breaker state, and per-service spending breakdown.
199
+ * **set** configures `budgetLimitUsd` (max total session spend), `velocityLimitUsd` (max spend per hour), and `alertThresholdPercent` (warn at this percentage of budget used). All three are optional and can be set independently.
200
+ * **reset** clears a tripped circuit breaker so the session can resume spending. Circuit breakers trip automatically when limits are exceeded and stay tripped until manually reset.
201
+
202
+ Budget limits can also be set at session creation time via the agent console at mpp32.org/agent-console or by passing `budgetLimitUsd`, `velocityLimitUsd`, and `alertThresholdPercent` to `POST /api/agent/sessions`.
152
203
 
153
204
  ## How discovery works
154
205
 
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
  import { z } from "zod";
5
5
  import { signX402Payment } from "./x402-signers.js";
6
- const SERVER_VERSION = "1.2.4";
6
+ const SERVER_VERSION = "1.3.1";
7
7
  // ── Env loading: trim and sanitize aggressively ─────────────────────────────
8
8
  // Copy-paste from Claude Desktop / Cursor / Windsurf JSON config UIs frequently
9
9
  // adds trailing \n, \r, NBSP, BOM, or wraps the value in literal quotes. Any
@@ -252,7 +252,7 @@ server.tool("get_mpp32_diagnostics", "Report what the mpp32-mcp-server detected
252
252
  `- x402 (USDC on Solana) payment: ${SOLANA_PRIVATE_KEY ? "yes" : "no — set MPP32_SOLANA_PRIVATE_KEY"}`,
253
253
  `- x402 (USDC on Base/EVM) payment: ${PRIVATE_KEY ? "yes" : "no — set MPP32_PRIVATE_KEY"}`,
254
254
  ``,
255
- `**Ready to pay end-to-end:** ${readyToPay ? "YES — try `query_intelligence` with token=\"M32\" to confirm." : "NO — see the missing items above."}`,
255
+ `**Ready to pay end-to-end:** ${readyToPay ? "YES — try `get_solana_token_intelligence` with token=\"M32\" to confirm." : "NO — see the missing items above."}`,
256
256
  ``,
257
257
  `**If a variable shows NOT SET but you set it in claude_desktop_config.json:**`,
258
258
  `1. Confirm the file path Claude Desktop actually reads:`,
@@ -308,6 +308,10 @@ server.tool("list_mpp32_services", "Browse the MPP32 federated catalog of 4,500+
308
308
  .enum(["native", "x402-bazaar", "mcp-registry", "curated", "free"])
309
309
  .optional()
310
310
  .describe("Filter by catalog source. 'native' = callable end-to-end; 'curated'/'free' = often callable; 'x402-bazaar'/'mcp-registry' = mostly listing-only."),
311
+ protocol: z
312
+ .enum(["x402", "tempo", "acp", "ap2", "agtp"])
313
+ .optional()
314
+ .describe("Filter by payment protocol (e.g. 'x402' for USDC-settled services)."),
311
315
  limit: z
312
316
  .number()
313
317
  .int()
@@ -315,7 +319,7 @@ server.tool("list_mpp32_services", "Browse the MPP32 federated catalog of 4,500+
315
319
  .max(500)
316
320
  .optional()
317
321
  .describe("Max results (default 100, max 500)."),
318
- }, async ({ category, q, source, limit }) => {
322
+ }, async ({ category, q, source, protocol, limit }) => {
319
323
  try {
320
324
  const url = new URL("/api/agent/services", API_URL);
321
325
  if (category)
@@ -324,6 +328,8 @@ server.tool("list_mpp32_services", "Browse the MPP32 federated catalog of 4,500+
324
328
  url.searchParams.set("q", q);
325
329
  if (source)
326
330
  url.searchParams.set("source", source);
331
+ if (protocol)
332
+ url.searchParams.set("protocol", protocol);
327
333
  url.searchParams.set("limit", String(limit ?? 100));
328
334
  const res = await fetchWithTimeout(url.toString(), { headers: buildHeaders() });
329
335
  if (!res.ok) {
@@ -460,6 +466,221 @@ server.tool("get_solana_token_intelligence", "Get real-time Solana token intelli
460
466
  // Legacy path — direct call to /api/intelligence with manual 402 handling.
461
467
  return await legacyIntelligenceCall(token, walletAddress);
462
468
  });
469
+ // ── Tool 4: M32-gated Whale Tracker ───────────────────────────────────────
470
+ server.tool("get_m32_whale_tracker", "M32-gated whale analysis for any Solana token. Returns top 20 holders, concentration risk, holder distribution, and buy/sell pressure. Requires the caller to hold 1,000,000+ M32 tokens (balance verified on-chain via X-Wallet-Address header). Free for qualifying holders — no payment required. Returns 403 if the wallet holds insufficient M32.", {
471
+ token: z
472
+ .string()
473
+ .describe("Solana token mint address to analyze for whale activity."),
474
+ walletAddress: z
475
+ .string()
476
+ .describe("Your Solana wallet address. M32 balance is checked on-chain to verify you hold 1M+ M32."),
477
+ }, async ({ token, walletAddress }) => {
478
+ try {
479
+ const res = await fetchWithTimeout(`${API_URL}/api/m32/whale-tracker`, {
480
+ method: "POST",
481
+ headers: buildHeaders({
482
+ "Content-Type": "application/json",
483
+ "X-Wallet-Address": safeHeaderValue("walletAddress", walletAddress),
484
+ }),
485
+ body: JSON.stringify({ token }),
486
+ });
487
+ const text = await res.text();
488
+ let formatted;
489
+ try {
490
+ formatted = JSON.stringify(JSON.parse(text), null, 2);
491
+ }
492
+ catch {
493
+ formatted = text;
494
+ }
495
+ if (res.status === 403) {
496
+ return { content: [{ type: "text", text: `**Access denied.** Whale Tracker requires holding 1,000,000+ M32 tokens. Your wallet does not meet the threshold.\n\nBuy M32: https://raydium.io/swap/?inputMint=sol&outputMint=6hKtz8FV7cAQMrbjcBZeTQAcrYep3WCM83164JpJpump` }] };
497
+ }
498
+ return { content: [{ type: "text", text: `**Whale Tracker** — \`${token}\`\n\n\`\`\`json\n${formatted}\n\`\`\`` }] };
499
+ }
500
+ catch (err) {
501
+ return { content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
502
+ }
503
+ });
504
+ // ── Tool 5: M32-gated Token Comparison ────────────────────────────────────
505
+ server.tool("compare_tokens_m32", "M32-gated head-to-head intelligence comparison of two Solana tokens. Returns side-by-side alpha scores, rug risk, whale activity, volume, liquidity, market data, and a winner verdict. Requires the caller to hold 2,500,000+ M32 tokens (balance verified on-chain via X-Wallet-Address header). Free for qualifying holders. Returns 403 if insufficient M32.", {
506
+ tokenA: z
507
+ .string()
508
+ .describe("First Solana token mint address."),
509
+ tokenB: z
510
+ .string()
511
+ .describe("Second Solana token mint address."),
512
+ walletAddress: z
513
+ .string()
514
+ .describe("Your Solana wallet address. M32 balance is checked on-chain to verify you hold 2.5M+ M32."),
515
+ }, async ({ tokenA, tokenB, walletAddress }) => {
516
+ try {
517
+ const res = await fetchWithTimeout(`${API_URL}/api/m32/compare`, {
518
+ method: "POST",
519
+ headers: buildHeaders({
520
+ "Content-Type": "application/json",
521
+ "X-Wallet-Address": safeHeaderValue("walletAddress", walletAddress),
522
+ }),
523
+ body: JSON.stringify({ tokenA, tokenB }),
524
+ });
525
+ const text = await res.text();
526
+ let formatted;
527
+ try {
528
+ formatted = JSON.stringify(JSON.parse(text), null, 2);
529
+ }
530
+ catch {
531
+ formatted = text;
532
+ }
533
+ if (res.status === 403) {
534
+ return { content: [{ type: "text", text: `**Access denied.** Token Comparison requires holding 2,500,000+ M32 tokens. Your wallet does not meet the threshold.\n\nBuy M32: https://raydium.io/swap/?inputMint=sol&outputMint=6hKtz8FV7cAQMrbjcBZeTQAcrYep3WCM83164JpJpump` }] };
535
+ }
536
+ return { content: [{ type: "text", text: `**Token Comparison** — \`${tokenA}\` vs \`${tokenB}\`\n\n\`\`\`json\n${formatted}\n\`\`\`` }] };
537
+ }
538
+ catch (err) {
539
+ return { content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
540
+ }
541
+ });
542
+ // ── Tool 6: M32-gated Portfolio Scanner ───────────────────────────────────
543
+ server.tool("scan_portfolio_m32", "M32-gated full wallet portfolio scan. Discovers all SPL tokens in a Solana wallet, runs intelligence on top holdings, and returns per-token analysis with aggregate portfolio risk metrics. Requires the caller to hold 5,000,000+ M32 tokens (balance verified on-chain via X-Wallet-Address header). Free for qualifying holders. Returns 403 if insufficient M32.", {
544
+ wallet: z
545
+ .string()
546
+ .describe("Solana wallet address to scan for token holdings."),
547
+ walletAddress: z
548
+ .string()
549
+ .describe("Your Solana wallet address. M32 balance is checked on-chain to verify you hold 5M+ M32."),
550
+ }, async ({ wallet, walletAddress }) => {
551
+ try {
552
+ const res = await fetchWithTimeout(`${API_URL}/api/m32/portfolio`, {
553
+ method: "POST",
554
+ headers: buildHeaders({
555
+ "Content-Type": "application/json",
556
+ "X-Wallet-Address": safeHeaderValue("walletAddress", walletAddress),
557
+ }),
558
+ body: JSON.stringify({ wallet }),
559
+ });
560
+ const text = await res.text();
561
+ let formatted;
562
+ try {
563
+ formatted = JSON.stringify(JSON.parse(text), null, 2);
564
+ }
565
+ catch {
566
+ formatted = text;
567
+ }
568
+ if (res.status === 403) {
569
+ return { content: [{ type: "text", text: `**Access denied.** Portfolio Scanner requires holding 5,000,000+ M32 tokens. Your wallet does not meet the threshold.\n\nBuy M32: https://raydium.io/swap/?inputMint=sol&outputMint=6hKtz8FV7cAQMrbjcBZeTQAcrYep3WCM83164JpJpump` }] };
570
+ }
571
+ return { content: [{ type: "text", text: `**Portfolio Scanner** — wallet \`${wallet}\`\n\n\`\`\`json\n${formatted}\n\`\`\`` }] };
572
+ }
573
+ catch (err) {
574
+ return { content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
575
+ }
576
+ });
577
+ // ── Tool 8: manage_agent_budget ────────────────────────────────────────────
578
+ server.tool("manage_agent_budget", "View, set, or reset the spending circuit breaker for your MPP32 agent session. Use 'get' to check current budget status (remaining budget, hourly velocity, circuit breaker state). Use 'set' to configure spending limits (budget cap in USD, hourly velocity limit, alert threshold percentage). Use 'reset' to manually reset a tripped circuit breaker so the session can resume spending. Circuit breakers trip automatically when budget or velocity limits are exceeded, preventing runaway agent spending.", {
579
+ action: z.enum(["get", "set", "reset"]).describe("Action: 'get' = view budget status, 'set' = update limits, 'reset' = clear tripped circuit breaker"),
580
+ budgetLimitUsd: z.number().positive().max(1_000_000).optional().describe("Maximum total session spend in USD. Only used with action='set'."),
581
+ velocityLimitUsd: z.number().positive().max(1_000_000).optional().describe("Maximum spend per hour in USD. Only used with action='set'."),
582
+ alertThresholdPercent: z.number().int().min(1).max(100).optional().describe("Budget percentage at which to warn (e.g. 80 = warn at 80% spent). Only used with action='set'."),
583
+ }, async ({ action, budgetLimitUsd, velocityLimitUsd, alertThresholdPercent }) => {
584
+ if (!AGENT_KEY) {
585
+ return {
586
+ content: [{ type: "text", text: "**MPP32_AGENT_KEY not configured.** Set it in your MCP config to manage budgets." }],
587
+ };
588
+ }
589
+ try {
590
+ if (action === "get") {
591
+ const res = await fetchWithTimeout(new URL("/api/agent/spending", API_URL).toString(), { headers: buildHeaders() });
592
+ if (!res.ok) {
593
+ const err = await res.json().catch(() => null);
594
+ return { content: [{ type: "text", text: `Error fetching budget: ${err?.error?.message ?? res.statusText}` }] };
595
+ }
596
+ const data = (await res.json()).data;
597
+ const lines = [
598
+ `**MPP32 Session Budget Status**`,
599
+ ``,
600
+ ];
601
+ if (data.budgetLimitUsd != null) {
602
+ lines.push(`Budget: $${data.totalSpentUsd.toFixed(4)} spent of $${data.budgetLimitUsd.toFixed(4)} ($${data.remainingBudgetUsd.toFixed(4)} remaining, ${data.budgetUtilizationPercent}% used)`);
603
+ }
604
+ else {
605
+ lines.push(`Budget: unlimited (no cap set)`);
606
+ lines.push(`Total spent: $${data.totalSpentUsd.toFixed(4)} across ${data.totalSettledCalls} settled calls`);
607
+ }
608
+ if (data.velocityLimitUsd != null) {
609
+ lines.push(`Velocity: $${data.hourlySpendUsd.toFixed(4)}/hr of $${data.velocityLimitUsd.toFixed(4)}/hr limit (${data.hourlySettledCalls} calls this hour)`);
610
+ }
611
+ if (data.circuitBreakerTripped) {
612
+ lines.push(``);
613
+ lines.push(`**CIRCUIT BREAKER TRIPPED** — ${data.circuitBreakerReason}`);
614
+ lines.push(`Tripped at: ${data.circuitBreakerTrippedAt}`);
615
+ lines.push(`Use action="reset" to resume spending.`);
616
+ }
617
+ if (data.byService?.length) {
618
+ lines.push(``);
619
+ lines.push(`**Spending by service:**`);
620
+ for (const s of data.byService) {
621
+ lines.push(`- ${s.service}: $${s.totalSpentUsd.toFixed(4)} (${s.count} calls)`);
622
+ }
623
+ }
624
+ return { content: [{ type: "text", text: lines.join("\n") }] };
625
+ }
626
+ if (action === "set") {
627
+ const payload = {};
628
+ if (budgetLimitUsd !== undefined)
629
+ payload.budgetLimitUsd = budgetLimitUsd;
630
+ if (velocityLimitUsd !== undefined)
631
+ payload.velocityLimitUsd = velocityLimitUsd;
632
+ if (alertThresholdPercent !== undefined)
633
+ payload.alertThresholdPercent = alertThresholdPercent;
634
+ if (Object.keys(payload).length === 0) {
635
+ return { content: [{ type: "text", text: "Provide at least one of: budgetLimitUsd, velocityLimitUsd, alertThresholdPercent." }] };
636
+ }
637
+ const res = await fetchWithTimeout(new URL("/api/agent/budget", API_URL).toString(), {
638
+ method: "PATCH",
639
+ headers: buildHeaders({ "Content-Type": "application/json" }),
640
+ body: JSON.stringify(payload),
641
+ });
642
+ if (!res.ok) {
643
+ const err = await res.json().catch(() => null);
644
+ return { content: [{ type: "text", text: `Error updating budget: ${err?.error?.message ?? res.statusText}` }] };
645
+ }
646
+ const data = (await res.json()).data;
647
+ const lines = [
648
+ `**Budget updated successfully.**`,
649
+ ``,
650
+ data.budgetLimitUsd != null ? `Budget limit: $${data.budgetLimitUsd.toFixed(4)}` : `Budget limit: unlimited`,
651
+ data.velocityLimitUsd != null ? `Velocity limit: $${data.velocityLimitUsd.toFixed(4)}/hr` : `Velocity limit: unlimited`,
652
+ `Total spent: $${data.totalSpentUsd.toFixed(4)}`,
653
+ data.remainingBudgetUsd != null ? `Remaining: $${data.remainingBudgetUsd.toFixed(4)}` : ``,
654
+ data.circuitBreakerTripped ? `\n**Note:** Circuit breaker is still tripped. Use action="reset" to resume.` : ``,
655
+ ].filter(Boolean);
656
+ return { content: [{ type: "text", text: lines.join("\n") }] };
657
+ }
658
+ if (action === "reset") {
659
+ const res = await fetchWithTimeout(new URL("/api/agent/circuit-breaker/reset", API_URL).toString(), {
660
+ method: "POST",
661
+ headers: buildHeaders({ "Content-Type": "application/json" }),
662
+ });
663
+ if (!res.ok) {
664
+ const err = await res.json().catch(() => null);
665
+ return { content: [{ type: "text", text: `Error resetting circuit breaker: ${err?.error?.message ?? res.statusText}` }] };
666
+ }
667
+ const data = (await res.json()).data;
668
+ const lines = [
669
+ data.previousReason
670
+ ? `**Circuit breaker reset.** Previous reason: ${data.previousReason}.`
671
+ : `**Circuit breaker was not tripped.** No action needed.`,
672
+ ``,
673
+ data.budgetLimitUsd != null ? `Budget: $${data.totalSpentUsd.toFixed(4)} / $${data.budgetLimitUsd.toFixed(4)} ($${data.remainingBudgetUsd.toFixed(4)} remaining)` : ``,
674
+ `Session can resume spending.`,
675
+ ].filter(Boolean);
676
+ return { content: [{ type: "text", text: lines.join("\n") }] };
677
+ }
678
+ return { content: [{ type: "text", text: "Unknown action. Use 'get', 'set', or 'reset'." }] };
679
+ }
680
+ catch (err) {
681
+ return { content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }] };
682
+ }
683
+ });
463
684
  // ── Core: agent/execute path with 402 sign-and-retry ────────────────────────
464
685
  async function callViaAgentExecute(service, method, body, query, path) {
465
686
  try {
@@ -637,6 +858,10 @@ function formatExecuteSuccess(resp, protoOverride) {
637
858
  else if (meta?.paymentMethod === "unsettled") {
638
859
  lines.push(`Service responded but no payment was verified. This should not happen for paid services.`);
639
860
  }
861
+ if (meta?.budget && meta.budget.budgetLimitUsd != null) {
862
+ const b = meta.budget;
863
+ lines.push(`Budget: $${b.remainingBudgetUsd.toFixed(4)} remaining (${b.budgetUtilizationPercent}% of $${b.budgetLimitUsd.toFixed(4)} used)`);
864
+ }
640
865
  lines.push("");
641
866
  lines.push("```json");
642
867
  lines.push(formatted);
@@ -645,6 +870,25 @@ function formatExecuteSuccess(resp, protoOverride) {
645
870
  }
646
871
  function formatExecuteHardError(status, body) {
647
872
  const code = body?.error?.code;
873
+ if (code === "MPP32_CIRCUIT_BREAKER_TRIPPED" || (status === 429 && body?.error?.budgetStatus)) {
874
+ const bs = body?.error?.budgetStatus;
875
+ return {
876
+ content: [
877
+ {
878
+ type: "text",
879
+ text: [
880
+ `**Circuit breaker tripped** — spending limit reached.`,
881
+ ``,
882
+ body?.error?.message ?? "Session budget exhausted.",
883
+ bs?.budgetLimitUsd != null ? `Budget: $${bs.totalSpentUsd?.toFixed(4) ?? "?"} / $${bs.budgetLimitUsd.toFixed(4)}` : "",
884
+ bs?.velocityLimitUsd != null ? `Velocity: $${bs.hourlySpendUsd?.toFixed(4) ?? "?"}/hr of $${bs.velocityLimitUsd.toFixed(4)}/hr limit` : "",
885
+ ``,
886
+ `To resume: use \`manage_agent_budget\` with action="reset", or increase the budget with action="set".`,
887
+ ].filter(Boolean).join("\n"),
888
+ },
889
+ ],
890
+ };
891
+ }
648
892
  if (code === "NOT_HTTP_CALLABLE") {
649
893
  return {
650
894
  content: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mpp32-mcp-server",
3
- "version": "1.2.4",
3
+ "version": "1.3.1",
4
4
  "mcpName": "io.github.MPP32/mpp32-mcp-server",
5
5
  "description": "Payment layer for AI agents. One MCP, five protocols, thousands of paid APIs your agent can call.",
6
6
  "type": "module",