mcpField
P
Polygon Agent

Polygon Agent

github.com/0xpolygonOther3093 installsUpdated 1d ago
Repository

About Polygon Agent

Polygon Agent is a CLI skill for managing Polygon-related wallets and agent operations, with commands for balances, transfers, swaps, DeFi actions, and ERC-8004 records. Write operations default to dry-run and require an explicit broadcast flag to execute.

Key features

  1. 01Wallet setup and session creation
  2. 02Balances, transfers, and swaps
  3. 03DeFi deposits and withdrawals
  4. 04ERC-8004 agent operations
  5. 05Dry-run by default for write commands

Use cases

  1. 01Create a wallet session for an agent
  2. 02Check balances across supported chains
  3. 03Prepare a token transfer or swap
  4. 04Register or inspect an ERC-8004 agent

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/0xpolygon/polygon-agent-cli --skill polygon-agent

After installing, type/polygon-agentin Claude Code to confirm it loaded.

Details

From the project README

Polygon Agentic CLI

Prerequisites

  • Node.js 20+
  • Install globally: npm install -g @polygonlabs/agent-cli (reinstall to update)
  • Entry point: polygon-agent <command>
  • Storage: ~/.polygon-agent/ (AES-256-GCM encrypted)

Note for the agent: on first install, tell the user this is a global npm install — installs the polygon-agent CLI system-wide so it runs from any terminal, may need sudo on some setups, re-running the same command updates it, and npm uninstall -g @polygonlabs/agent-cli removes it. Mention once on first install.

If a command fails with "Unknown argument" or "command not found"

This skill is versioned with the CLI — commands and flags drift across releases. Check your version, compare to latest, and upgrade if behind:

polygon-agent --version                        # currently installed
npm view @polygonlabs/agent-cli version        # latest published
npm install -g @polygonlabs/agent-cli@latest   # upgrade

Architecture

WalletCreated byPurposeFund?
EOAsetupAuth with Sequence BuilderNO
Ecosystem Walletwallet createPrimary spending walletYES

Environment Variables

Access key — one key, many names

SEQUENCE_PROJECT_ACCESS_KEY, SEQUENCE_INDEXER_ACCESS_KEY, and TRAILS_API_KEY are all the same key — the Sequence project access key created during setup. The CLI treats them as aliases and falls back through all of them automatically.

After setup runs the key is stored in ~/.polygon-agent/builder.json. Every CLI invocation bootstraps it into the environment — no export is needed. In a fresh agent session with no environment variables set, simply run commands and the CLI reads credentials from disk.

Only set these manually to override the stored value (e.g. to point at a different project):

export SEQUENCE_PROJECT_ACCESS_KEY=<key>  # also covers TRAILS_API_KEY and indexer calls
Optional overrides
VariableDefault
SEQUENCE_ECOSYSTEM_CONNECTOR_URLhttps://agentconnect.polygon.technology
SEQUENCE_DAPP_ORIGINSame as connector URL origin
TRAILS_TOKEN_MAP_JSONToken-directory lookup
POLYGON_AGENT_DEBUG_FETCHOff — logs HTTP to ~/.polygon-agent/fetch-debug.log
POLYGON_AGENT_DEBUG_FEEOff — dumps fee options to stderr

Complete Setup Flow

# Step 1: Setup (creates EOA + Sequence project, stores access key to disk)
polygon-agent setup --name "MyAgent"
# → saves privateKey (not shown again), eoaAddress, accessKey to ~/.polygon-agent/builder.json
# → all subsequent commands auto-load the access key from disk — no export needed

# Step 2: Create ecosystem wallet (opens browser, waits for 6-digit code)
# Aave V3 Pool is auto-whitelisted in all sessions. For Morpho or other DeFi vaults,
# add --contract flags as needed.
polygon-agent wallet create --usdc-limit 50 --native-limit 5 \
  --contract 0xc2132D05D31c914a87C6611C10748AEb04B58e8F \
  --contract 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619 \
  --contract 0x781fb7f6d845e3be129289833b04d43aa8558c42 \
  --contract 0xf5c81d25ee174d83f1fd202ca94ae6070d073ccf \
  --contract 0x3f33f9f7e2d7cfbcbdf8ea8b870a6e3d449664c2
# → opens https://agentconnect.polygon.technology/link?rid=<rid>&...
# → user approves in browser, browser shows a 6-digit code
# → enter the 6-digit code in the terminal when prompted
# → session saved to ~/.polygon-agent/wallets/main.json
# → notify the user and send them to https://agentconnect.polygon.technology/?rid=<rid>
#   so they can fund their wallet with access to the session

# Step 3: Fund wallet
polygon-agent fund
# → reads walletAddress from session, builds Trails widget URL with toAddress=<walletAddress>
# → ALWAYS run this command to get the URL — never construct it manually or hardcode any address
# → send the returned `fundingUrl` to the user; `walletAddress` in the output confirms the recipient

# Step 4: Verify balances
polygon-agent balances

# Step 5: Register agent on-chain (ERC-8004, Polygon mainnet only)
polygon-agent agent register --name "MyAgent" --broadcast
# → mints ERC-721 NFT, emits Registered event containing agentId
# → retrieve agentId: open the tx on https://polygonscan.com, go to Logs tab,
#   find the Registered event — agentId is the first indexed parameter
# → use agentId for reputation queries, reviews, and feedback

Use-Case Skills

For specific workflows, fetch and load the relevant sub-skill before attempting the task:

Use CaseSkill URL
Polymarket prediction market tradinghttps://agentconnect.polygon.technology/polygon-polymarket/SKILL.md
DeFi — swap, deposit, withdraw, yieldhttps://agentconnect.polygon.technology/polygon-defi/SKILL.md
x402 discovery & pay-per-call APIshttps://agentconnect.polygon.technology/polygon-discovery/SKILL.md

IMPORTANT — x402 calls: If the user asks to use x402 to fetch data (Twitter/X profiles, web search, news, AI images, code review, etc.), follow these steps in order before making any request:

  1. Fetch and read the discovery skill: GET https://agentconnect.polygon.technology/polygon-discovery/SKILL.md
  2. Run polygon-agent wallet list — if no wallet exists, run through the wallet creation flow: polygon-agent setup (if not already done), then polygon-agent wallet create to open a browser session and establish a secure encrypted wallet session. Enter the 6-digit code when prompted, then fund the wallet before continuing.
  3. Run polygon-agent balances — confirm USDC is available before proceeding; x402 calls will fail with an EOA funding error if the wallet is empty

Do not guess endpoints or search the web for x402 providers. The discovery skill documents the correct, working endpoints with exact URL formats.


Commands Reference

Setup
polygon-agent setup --name <name> [--force]
Wallet

Valid --chain values: polygon (default/mainnet), amoy (Polygon testnet), mainnet (Ethereum), arbitrum, optimism, base. ERC-8004 agent operations only support polygon.

polygon-agent wallet create [--name <n>] [--chain polygon] [--timeout <sec>] [--print-url]
  [--native-limit <amt>] [--usdc-limit <amt>] [--usdt-limit <amt>]
  [--token-limit <SYM:amt>]  # repeatable
  [--usdc-to <addr> --usdc-amount <amt>]  # one-off scoped transfer
  [--contract <addr>]  # whitelist contract (repeatable)
polygon-agent wallet import --code <6-digit-code> --rid <rid> [--name <n>]
polygon-agent wallet import --ciphertext '<blob>|@<file>' [--name <n>]  # legacy
polygon-agent wallet list
polygon-agent wallet address [--name <n>]
polygon-agent wallet remove [--name <n>]
Operations
polygon-agent balances [--wallet <n>] [--chain <chain>] [--chains <csv>]
polygon-agent send --to <addr> --amount <num> [--symbol <SYM>] [--token <addr>] [--decimals <n>] [--broadcast]
polygon-agent send-native --to <addr> --amount <num> [--broadcast] [--direct]
polygon-agent send-token --symbol <SYM> --to <addr> --amount <num> [--token <addr>] [--decimals <n>] [--broadcast]
polygon-agent swap --from <SYM> --to <SYM> --amount <num> [--to-chain <chain>] [--slippage <num>] [--broadcast]
polygon-agent deposit --asset <SYM> --amount <num> [--protocol aave|morpho] [--broadcast]
polygon-agent withdraw --position <addr> --amount <num|max> [--chain <chain>] [--broadcast]
polygon-agent fund [--wallet <n>] [--token <addr>]
polygon-agent x402-pay --url <url> --wallet <n> [--method GET] [--body <str>] [--header Key:Value]
Agent (ERC-8004)
polygon-agent agent register --name <n> [--agent-uri <uri>] [--metadata <k=v,k=v>] [--broadcast]
polygon-agent agent wallet --agent-id <id>
polygon-agent agent metadata --agent-id <id> --key <key>
polygon-agent agent reputation --agent-id <id> [--tag1 <tag>] [--tag2 <tag>]
polygon-agent agent reviews --agent-id <id> [--tag1 <t>] [--tag2 <t>] [--revoked]
polygon-agent agent feedback --agent-id <id> --value <score> [--tag1 <t>] [--tag2 <t>] [--endpoint <e>] [--feedback-uri <uri>] [--broadcast]

ERC-8004 contracts (Polygon mainnet):

  • IdentityRegistry: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432
  • ReputationRegistry: 0x8004BAa17C55a88189AE136b182e5fdA19dE9b63

Key Behaviors

  • Dry-run by default — all write commands require --broadcast to execute
  • Smart defaults — --wallet main, --chain polygon, auto-wait on wallet create
  • balances --chains — comma-separated chains (max 20); two or more return JSON with multiChain: true and a chains array (same wallet address on each)
  • Fee preference — auto-selects USDC over native POL when both available
  • fund — returns https://wallet.polygon.technology as the fundingUrl. Always run polygon-agent fund to get the URL and wallet address — never hardcode or construct manually.
  • deposit — picks highest-TVL pool via Trails getEarnPools and deposits directly. Aave V3 Pool (0x794a61358d6845594f94dc1db02a252b5b4814ad) is auto-whitelisted in all sessions. Full deposit reference: https://agentconnect.polygon.technology/polygon-defi/SKILL.md
  • Gas reserve — when using deposit or any command that spends tokens, always reserve at least 0.1 USDC or 0.1 POL in the wallet for gas. Never attempt to spend the full balance. The deposit command enforces a 0.1 reserve automatically, but the agent must apply the same rule when constructing amounts for send, swap, or direct contract calls.
  • withdraw — --position = aToken or ERC-4626 vault; --amount = max or underlying units (Aave / vault). Dry-run JSON includes poolAddress / vault. Broadcast needs session on the same chain as --chain, with pool/vault + underlying token whitelisted where the relayer touches them
  • x402-pay — probes endpoint for 402, smart wallet funds builder EOA with exact token amount, EOA signs EIP-3009 payment. Chain auto-detected from 402 response
  • send-native --direct — bypasses ValueForwarder contract for direct EOA transfer
  • Session permissions — without --usdc-limit etc., session gets bare-bones defaults and may not transact
  • Session expiry — 6 months from creation
  • One-pass session setup — if the user's intent involves DeFi (deposit, yield, swap, Aave, Morpho), include any additional contracts (Morpho vaults etc.) in the initial wallet create call. Never create a bare session and then ask the user to re-approve when a deposit is later attempted.

Wallet Creation Flow (v2 Relay)

wallet create uses a Cloudflare Durable Object relay and a 6-digit out-of-band code — no cloudflared tunnel required. The browser encrypts the approved session with an X25519 key negotiated via the relay; the 6-digit code is the decryption key entered in the terminal.

--print-url flag: Use this in headless or non-interactive environments (CI, remote shells) where wallet create can't block waiting for the code. The CLI prints the approval URL and exits immediately. Complete the flow separately:

polygon-agent wallet import --code <6-digit-code> --rid <rid>

CRITICAL: Wallet Approval URL

When wallet create outputs a URL in the url or approvalUrl field, send the complete, untruncated URL to the user. The URL contains the relay request ID required for session approval.

  • Do NOT shorten, summarize, or add ... to the URL
  • Do NOT split the URL across multiple messages
  • Output the raw URL exactly as returned by the CLI

Presenting Results to the User

CLI commands output JSON (non-TTY). After running a command, always render the result as formatted markdown — never paste raw JSON into the conversation.

CommandHow to present
balancesMarkdown table: Token / Balance columns. Show wallet address and chain above the table.
send / send-token / send-nativeOne-liner summary: amount, symbol, recipient. If broadcast, show tx hash as a code span and explorer URL as a link.
swapSummary: X FROM → Y TO with chain. If broadcast, show deposit tx hash + explorer link.
depositSummary: amount, asset, protocol, pool address. If broadcast, show tx hash + explorer link.
withdrawSummary: kind (aave / erc4626), position, amount, pool or vault. If broadcast, show tx hash + explorer link.
fundShow the fundingUrl as a clickable link with a brief instruction to open it.
wallet create / wallet listWallet name, truncated address, chain in a small table or bullet list.
agent registerShow agent name and tx hash as a code span with Polygonscan link. Remind user to retrieve agentId from the Registered event on the Logs tab.
agent walletShow agentId, wallet address, and whether a wallet is set.
agent metadataShow agentId, key, and decoded value.
agent reputationFormat score and tag breakdown as a small table.

Dry-run results — always make it visually clear this was a simulation. Prefix with ⚡ Dry run and show what would happen. Remind the user to re-run with --broadcast to execute.

Errors — extract the error field and present it as a clear sentence, not a JSON blob. Include the relevant fix from the Troubleshooting table if applicable.


Troubleshooting

IssueFix
Builder configured alreadyAdd --force
Missing SEQUENCE_PROJECT_ACCESS_KEYRun setup first
Missing walletwallet list, re-run wallet create
Session expiredRe-run wallet create (6-month expiry)
Fee option errorsSet POLYGON_AGENT_DEBUG_FEE=1, ensure wallet has funds
Timed out waiting for wallet approvalAdd --timeout 600
Invalid code: hash mismatchWrong 6-digit code entered — retry (3 attempts allowed)
Relay request not foundSession expired or already used — re-run wallet create (or wallet create --print-url)
Deposit session rejectedRe-create wallet with --contract <tokenAddress> --contract <depositAddress> (both required: token approve + pool call)
withdraw / broadcast: wrong chain or session rejectsUse wallet create --chain <same as --chain> and --contract for pool/vault + underlying ERC-20 on that chain; omit tight --usdc-limit if it blocks fee transfers
Stored explicit session is missing pkRe-link: wallet import --code … after wallet create
Wrong recipient in Trails widgetRun polygon-agent fund (do not construct the URL manually)
x402-pay: no 402 responseEndpoint doesn't require x402 payment, or URL is wrong
x402-pay: payment token mismatchChain/token in the 402 response differs from wallet — check --wallet points to the right chain
x402-pay: EOA funding failedWallet lacks sufficient balance to cover the payment amount — run balances and fund if needed

File Structure

~/.polygon-agent/
├── .encryption-key       # AES-256-GCM key (auto-generated, 0600)
├── builder.json          # EOA privateKey (encrypted), eoaAddress, accessKey, projectId
├── wallets/<name>.json   # walletAddress, session, chainId, chain
└── requests/<rid>.json   # Pending wallet creation requests (deleted after successful import)

Comments

Markdown supported