feat: add agent-payment-x402 skill for autonomous agent payments#893
Conversation
Adds a skill for x402 payment execution with MCP integration: - Per-task and per-session spending controls - Non-custodial wallet management (ERC-4337) - Pairs with mcp-server-patterns and cost-aware-llm-pipeline skills - Production reference: merged into NVIDIA NeMo Agent Toolkit (PR affaan-m#17) - npm package: agentwallet-sdk
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a new skill specification document "Agent Payment Execution (x402)" describing MCP Changes
Sequence Diagram(s)sequenceDiagram
participant Orchestrator
participant Agent
participant MCP_Server as MCP (agentpay)
participant SmartAccount as ERC-4337
participant Blockchain
Orchestrator->>MCP_Server: set_policy(SpendingPolicy)
Orchestrator-->>Agent: delegate_with_policy
Agent->>MCP_Server: check_spending / get_balance
MCP_Server->>SmartAccount: query_balance
SmartAccount->>Blockchain: fetch_state
Blockchain-->>SmartAccount: state
SmartAccount-->>MCP_Server: balance_info
MCP_Server-->>Agent: balance_result
Agent->>MCP_Server: send_payment(tx_request)
MCP_Server->>SmartAccount: sign_and_send(tx_request)
SmartAccount->>Blockchain: submit_transaction
Blockchain-->>SmartAccount: tx_receipt
SmartAccount-->>MCP_Server: tx_receipt
MCP_Server-->>Agent: tx_result
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@skills/agent-payment-x402/SKILL.md`:
- Around line 15-69: Rename or move the existing "Core Concepts" and "MCP
Integration" sections under a new "## How It Works" heading (i.e., replace the
"Core Concepts" and "MCP Integration" headings with "How It Works" and keep
their content intact), and rename the "## Example: Pay-Per-API-Call Agent"
heading to "## Examples" (ensuring the example content remains unchanged);
ensure the new headings "How It Works" and "Examples" are present exactly as
written to satisfy skill-format compliance while preserving sections like the
x402 Protocol, Spending Controls, Non-Custodial Wallets, MCP Integration JSON
block, Available Tools table, and the TypeScript pay-per-API-call example.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f39cfcc2-bad5-466b-816f-dc249d6dfe9c
📒 Files selected for processing (1)
skills/agent-payment-x402/SKILL.md
There was a problem hiding this comment.
3 issues found across 1 file
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:39">
P2: Documentation recommends unpinned `npx` execution for a payment-signing package, creating supply-chain and reproducibility risk.</violation>
<violation number="2" location="skills/agent-payment-x402/SKILL.md:52">
P1: Security model contradiction: `set_policy` is listed as an agent-available tool, which can let the spender mutate its own limits unless explicitly restricted.</violation>
<violation number="3" location="skills/agent-payment-x402/SKILL.md:82">
P2: User-facing documentation links to an unvetted external GitHub repository/PR, conflicting with repository review policy on external repo links.</violation>
</file>
Since this is your first cubic review, here's how it works:
- cubic automatically reviews your code and comments on bugs and improvements
- Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
- Add one-off context when rerunning by tagging
@cubic-dev-aiwith guidance or docs links (includingllms.txt) - Ask questions if you need clarification on any suggestion
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
Greptile SummaryThis PR adds a new Two issues remain:
Confidence Score: 3/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant Orchestrator
participant AgentpayMCP as AgentPay MCP Server<br/>(agentwallet-sdk)
participant Agent
participant ExternalService as External Service
Orchestrator->>AgentpayMCP: connect(StdioClientTransport)
Orchestrator->>AgentpayMCP: callTool("set_policy", {per_task_budget, per_session_budget, allowlist})
AgentpayMCP-->>Orchestrator: policyResult (check isError)
Orchestrator->>Agent: delegate task (within policy bounds)
Agent->>AgentpayMCP: callTool("check_spending")
AgentpayMCP-->>Agent: {remaining: number}
alt remaining >= apiCost
Agent->>ExternalService: HTTP request
ExternalService-->>Agent: 402 Payment Required
Agent->>AgentpayMCP: callTool("send_payment", {recipient, amount})
AgentpayMCP-->>Agent: payment signed & broadcast
Agent->>ExternalService: retry request with payment proof
ExternalService-->>Agent: 200 OK + response
Agent->>AgentpayMCP: callTool("list_transactions") [audit]
else budget exceeded
Agent--xAgent: throw Error("Budget exceeded — action blocked")
end
Reviews (10): Last reviewed commit: "Update skills/agent-payment-x402/SKILL.m..." | Re-trigger Greptile |
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:74">
P2: Payment guard example swallows exception context in catch, reducing observability/auditability for spending-check failures.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:71">
P1: MCP client example calls `callTool` before showing any transport/session connection, making the snippet likely non-runnable and misleading for users.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
|
thanks for the pr. triaged and queued for maintainer review. |
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:96">
P1: Validate that `check_spending` returned a numeric `remaining` value before comparing budgets; otherwise malformed responses can bypass the guardrail and allow paid actions to proceed.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
There was a problem hiding this comment.
1 issue found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:99">
P1: Budget enforcement can be bypassed because numeric validation allows non-finite values (`NaN`/`Infinity`) and does not validate `apiCost`.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
There was a problem hiding this comment.
2 issues found across 1 file (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="skills/agent-payment-x402/SKILL.md">
<violation number="1" location="skills/agent-payment-x402/SKILL.md:74">
P2: The example forwards the entire parent `process.env` to a high‑privilege third‑party subprocess, which unnecessarily exposes unrelated secrets to that dependency. Prefer whitelisting only required env vars (e.g., the wallet key and PATH).</violation>
<violation number="2" location="skills/agent-payment-x402/SKILL.md:115">
P3: Handle `result.isError` before parsing `result.content` as JSON. Without this guard, tool-execution failures are incorrectly reported as unexpected format errors, which obscures the real payment-service failure.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
79fa3fe to
5bfbcd7
Compare
Security model: - Remove set_policy from agent-callable tools table; document as orchestrator-only to prevent self-privilege escalation - Pin agentwallet-sdk@6.0.0 in MCP config with pre-install guidance (npx without -y hangs in non-interactive MCP startup) - Whitelist only required env vars (PATH, NODE_ENV, WALLET_PRIVATE_KEY) instead of forwarding entire process.env to subprocess Code example (complete rewrite): - Add StdioClientTransport import and client.connect() for runnable code - Wrap in async main() for CJS/ESM compatibility (top-level await) - Verify set_policy result via isError before delegating - Five distinct fail-closed error paths in preToolCheck: 1. Invalid apiCost input (NaN/Infinity bypass prevention) 2. Transport/connectivity failure 3. Tool-level error (isError: true, e.g., auth failure) 4. Unexpected response format (missing/non-finite remaining) 5. Budget exceeded (clear amounts in message) - Use Number.isFinite() for both apiCost and remaining validation Documentation: - Rename headings per CONTRIBUTING.md format - Replace broken mcp-server-patterns cross-ref with security-review - Add 'Pin your dependencies' to Best Practices - Add security note about supply-chain risk
5bfbcd7 to
e57ad5c
Compare
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
| ```json | ||
| { | ||
| "mcpServers": { | ||
| "agentpay": { | ||
| "command": "npx", | ||
| "args": ["agentwallet-sdk@6.0.0"] | ||
| } | ||
| } | ||
| } | ||
| ``` |
There was a problem hiding this comment.
mcpServers JSON config missing env field for wallet credentials
The mcpServers JSON block is the primary entry point for Claude Code users who don't write their own orchestrator. It does not include an env field, so there is no guidance on how to pass the wallet private key to the subprocess. When Claude Code spawns the MCP server from this config, the subprocess environment depends entirely on what Claude Code happens to inherit — the key may or may not be present, with no controlled injection.
The TypeScript orchestrator example correctly handles this (with an explicit env object in the transport), but that path requires writing a custom orchestrator. A reader who copies only this JSON block has no idea how to supply credentials, which is a significant omission for a tool that manages private keys and authorises financial transactions.
The mcpServers format supports an env field (just as the TypeScript StdioClientTransport does). The block should include one, with a placeholder referencing the appropriate environment variable and a note to set that variable in the shell before starting Claude Code — mirroring the same guidance already present in the TypeScript example.
| env: { | ||
| PATH: process.env.PATH ?? "", | ||
| NODE_ENV: process.env.NODE_ENV ?? "production", | ||
| WALLET_PRIVATE_KEY: walletKey, | ||
| }, |
There was a problem hiding this comment.
Empty
PATH fallback will silently prevent npx from executing
process.env.PATH ?? "" falls back to an empty string when PATH is not set in the environment. Because env is passed directly to StdioClientTransport, Node.js's child_process.spawn uses it as the complete replacement environment — it does not merge with the parent process's existing environment. An empty PATH means no executables can be resolved, including npx itself. The subprocess will fail immediately with a "command not found" style error, which is completely unrelated to payment logic and very hard to diagnose.
Since the code already validates that the wallet key is present before reaching this point, a consistent pattern would be to apply the same eager validation to PATH:
const envPath = process.env.PATH;
if (!envPath) {
throw new Error("PATH is not set — cannot spawn npx");
}
const transport = new StdioClientTransport({
command: "npx",
args: ["agentwallet-sdk@6.0.0"],
env: {
PATH: envPath,
NODE_ENV: process.env.NODE_ENV ?? "production",
// wallet key forwarded here
},
});There was a problem hiding this comment.
Review from @ankitSrivastavaITH
Reviewed the latest commit (95a1435). The skill is well-structured and the author has addressed most bot feedback across 3 iterations. The code example is now substantially better (proper MCP client setup, fail-closed paths, env whitelisting). A few issues remain:
Remaining Issues
1. [P2] mcpServers JSON config missing env for wallet credentials
The JSON config block (the primary copy-paste entry point for most users) doesn't show how to pass WALLET_PRIVATE_KEY. The TypeScript example does it correctly with env whitelisting, but someone who only copies the JSON block will get a server that starts without credentials.
{
"mcpServers": {
"agentpay": {
"command": "npx",
"args": ["agentwallet-sdk@6.0.0"],
"env": {
"WALLET_PRIVATE_KEY": "${WALLET_PRIVATE_KEY}"
}
}
}
}2. [P2] npx without -y hangs in non-interactive MCP startup
The security note correctly warns against unpinned versions, and the prerequisites section suggests npm install -g first. But the mcpServers JSON still uses npx without -y — if the package isn't globally installed, Claude Code's MCP server startup will hang waiting for a confirmation prompt. Either:
- Add
-yback (since version is pinned, supply-chain risk is mitigated), or - Change command to the globally installed binary path
3. [P2] PATH fallback to empty string breaks npx execution
In the TypeScript example at line 88:
PATH: process.env.PATH ?? "",If PATH is unset, the empty string means npx can't be found. Should throw or use a sensible default.
4. [P1] agentwallet-sdk package verification
This skill recommends running a third-party npm package (agentwallet-sdk) that handles private keys. For a security-sensitive skill in ECC:
- The npm package has only ~250 weekly downloads
- The author of this PR appears to be affiliated with the package (
up2itnow0822/ "AI Agent Economy") - This should be disclosed in the PR description
Not a blocker, but the maintainer should be aware this is effectively a promotion of the author's own package.
5. [Nitpick] Line count
At 178 lines, this is within the 500-line CONTRIBUTING.md limit but relatively long for a skill that's primarily documentation for one specific SDK. The code example alone is ~65 lines.
What's Good
- Fail-closed design is well-documented and the code example demonstrates 5 distinct error paths
- Env var whitelisting in the transport setup is a good security pattern
set_policyis correctly kept out of agent-callable tools- Spending controls section is clear and actionable
- Production references add credibility
Issues 1-3 are worth fixing before merge. Issue 4 is for the maintainer's awareness.
…x402-skill feat: add agent-payment-x402 skill for autonomous agent payments
…x402-skill feat: add agent-payment-x402 skill for autonomous agent payments
What
Adds
agent-payment-x402— a skill that enables AI agents to make autonomous payments with built-in spending controls via the x402 HTTP payment protocol and MCP tools.Why
The skills directory covers coding, testing, deploying, researching, and security — but not payment execution. As agents compose more skills per session, some will need to purchase API calls, settle with other agents, or provision paid resources. This skill fills that gap.
What's included
mcpServersconfig withnpx agentwallet-sdkPairs with existing skills
mcp-server-patterns— for building/configuring MCP serverscost-aware-llm-pipeline— for controlling LLM costs (this extends cost control to external payments)security-review— payment tools are high-privilege, same scrutiny as shell accessProduction references
agentwallet-sdkFollows the CONTRIBUTING.md skill template format (YAML frontmatter + structured sections).
Summary by cubic
Adds
agent-payment-x402, a skill for autonomous payments via the x402 protocol with strict guardrails. Integrates MCP tools so agents can pay APIs/services within budgets using non-custodial wallets; policy is orchestrator-controlled andagentwallet-sdk@6.0.0is pinned.New Features
get_balance,send_payment,check_spending,list_transactions.Bug Fixes
set_policyis orchestrator-only; removed from agent-callable tools table.agentwallet-sdk@6.0.0with pre-install guidance to avoidnpxprompt hangs; whitelist only required env vars (PATH,NODE_ENV,WALLET_PRIVATE_KEY); added supply-chain risk note.WALLET_PRIVATE_KEY, importStdioClientTransport, callClient.connect(), wrap inasync main, verifyset_policyviaisError, useNumber.isFinite, and add five fail-closed paths (invalidapiCost, transport failure, tool error, unexpected format, budget exceeded).mcp-server-patternscross-ref withsecurity-review, and added “Pin your dependencies” best practice.Written for commit 95a1435. Summary will update on new commits.
Summary by CodeRabbit