Build an AI agent that swaps on six chains with Cleave and Chainstack
A hands-on tutorial: an AI agent plans a swap with Cleave's MCP server, a local wallet signs it, and Chainstack RPC sends it and reads the receipt.

An AI agent can find a swap route, but the route still needs to become a transaction: the wallet must approve the right spender, sign the calls, submit them to the right chain, and check what arrived. This tutorial connects those steps with Cleave's MCP server and Chainstack RPC.
Cleave plans the swap, splitting the trade across several liquidity pools so the price moves less, and returns unsigned calls. Your wallet signs them locally, and Chainstack provides the RPC connection for checking state, estimating gas, submitting signed transactions, and reading receipts. We'll walk through a 5 USDC to WETH swap on Base, then show how the same pattern extends to Cleave's other supported networks.
How the agent, wallet, and RPC fit together
The agent uses the Model Context Protocol (MCP) to call Cleave's tools. Cleave resolves tokens, finds a route, and returns the transaction calls in signing order. A separate executor checks the plan and asks for confirmation before using the wallet. That executor connects to Chainstack with ethers.js.
The flow is: user request, Cleave MCP, unsigned swap plan, plan checks and wallet approval, local signing, Chainstack RPC, transaction receipt, Cleave tracking.
The private key stays in the signing process. Neither the model nor the MCP server needs it.
1. Set up your RPC endpoints
Create a Chainstack account, create a project, and deploy a Base mainnet node. Open Access and credentials and copy its HTTPS endpoint. You can find the network options on the Base RPC page and connection examples in the Base tooling guide.
For a six-chain setup, provision endpoints for Ethereum, Arbitrum, Optimism, Polygon, and BNB Smart Chain alongside Base. Keep each endpoint mapped to its own mainnet chain ID: Ethereum 1, Arbitrum 42161, Optimism 10, Polygon 137, BNB Smart Chain 56, and Base 8453.
Start with Node.js 22, a dedicated wallet holding 5 USDC on Base, and enough Base ETH to cover the approval and swap transactions. Store the endpoint and wallet credentials in a local .env file, and exclude that file from version control.
CHAINSTACK_BASE_RPC=YOUR_CHAINSTACK_BASE_MAINNET_HTTPS_ENDPOINT
WALLET_ADDRESS=YOUR_WALLET_ADDRESS
WALLET_PRIVATE_KEY=YOUR_LOCAL_SIGNING_KEYCreate a project directory and install the libraries used below. The examples use the MCP TypeScript SDK's v1 client API, Cleave's core plan checks, and ethers.js v6.
mkdir cleave-chainstack-agent
cd cleave-chainstack-agent
npm init -y
npm install @modelcontextprotocol/sdk@1 zod @cleave-protocol/ai-sdk@0.2.2 ethers@62. Give your agent Cleave's swap tools
In an MCP-compatible agent client, add the remote server with your wallet pinned to the connection. A USD cap and listed-token setting narrow the plans the connection can return.
{"mcpServers":{"cleave":{"url":"https://api.cleave.fi/mcp/0xYourWalletAddress?maxUsd=10&listedOnly=1"}}}Replace 0xYourWalletAddress with your wallet's address. Cleave exposes four tools: cleave_find_token for resolving tokens, cleave_plan_swap for generating unsigned calls, cleave_track_swap for checking progress, and cleave_get_gas for gas top-ups. This walkthrough uses planning and tracking; the wallet already has native gas.
Give the agent a precise request:
Plan a swap of 5 USDC to WETH on Base, chain ID 8453, for my pinned wallet. Use that wallet as the recipient and 50 basis points maximum slippage. Resolve any ambiguous token before planning. Show the outcome, minimum received, fees, warnings, expiry, and calls in signing order. Stop after planning.The agent translates that request into a cleave_plan_swap call. For a reproducible handoff to the signing process, the next script makes the same MCP call directly and saves its structured result.
3. Request and screen the unsigned plan
Save the following as plan.mjs. It pins the wallet, calls Cleave over Streamable HTTP, and passes the result through screenPlanSwap before writing plan.json.
import { writeFile } from 'node:fs/promises';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { screenPlanSwap } from '@cleave-protocol/ai-sdk/core';
import { getAddress } from 'ethers';
const wallet = getAddress(process.env.WALLET_ADDRESS);
const request = {
fromChainId: 8453,
toChainId: 8453,
sellToken: 'USDC',
buyToken: 'WETH',
amount: '5',
wallet,
recipient: wallet,
maxSlippageBps: 50
};
const url = new URL('https://api.cleave.fi/mcp/' + wallet);
url.searchParams.set('maxUsd', '10');
url.searchParams.set('listedOnly', '1');
const client = new Client({ name: 'cleave-chainstack', version: '1.0.0' });
try {
await client.connect(new StreamableHTTPClientTransport(url));
const result = await client.callTool({
name: 'cleave_plan_swap',
arguments: request
});
if (result.isError || !result.structuredContent) {
throw new Error('No structured plan returned. Inspect the tool response.');
}
const plan = screenPlanSwap(request, result.structuredContent);
if (plan.error || plan.blocked || !plan.calls?.length) {
throw new Error(JSON.stringify(plan));
}
await writeFile('plan.json', JSON.stringify({ request, plan }, null, 2));
console.log(JSON.stringify(plan, null, 2));
} finally {
await client.close();
}Run it from the project directory:
node --env-file=.env plan.mjsThe request uses decimal token units, so amount: '5' means 5 USDC. maxSlippageBps: 50 sets a 0.5% slippage limit. The output contains calls for the wallet to sign, plus route details, fees, notices, a requestId, and validUntil in Unix seconds.
Cleave's core plan screening checks the calls against the request and its pinned contract allowlist. It checks the source chain and wallet, allowed targets and functions, approvals, and supported amount and recipient rules. Use the screened result for the handoff.
4. Review, sign, and send through Chainstack
Review the sell amount, recipient, minimum received, approvals, fees, and notices together. The network gas cost is separate from the costs in the plan. A blocked plan stops execution; warnings and requiresConfirmation belong in the review before signing.
Save this as execute.mjs. It accepts only the intended 5 USDC to WETH Base request, screens the saved plan again, verifies the RPC network and wallet, and requests an explicit SEND confirmation. It signs locally and submits each call through the Chainstack endpoint, waiting for a successful receipt before continuing.
import { readFile, appendFile, open } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
import { JsonRpcProvider, Wallet, getAddress, keccak256 } from 'ethers';
import { screenPlanSwap } from '@cleave-protocol/ai-sdk/core';
const saved = JSON.parse(await readFile('plan.json', 'utf8'));
const request = saved.request;
if (request.fromChainId !== 8453 || request.toChainId !== 8453 ||
request.sellToken !== 'USDC' || request.buyToken !== 'WETH' ||
request.amount !== '5' || request.maxSlippageBps !== 50 ||
getAddress(request.wallet) !== getAddress(process.env.WALLET_ADDRESS) ||
getAddress(request.recipient) !== getAddress(request.wallet)) {
throw new Error('The saved request differs from the intended Base swap.');
}
const plan = screenPlanSwap(request, saved.plan);
if (plan.error || plan.blocked || !plan.calls?.length ||
plan.notices?.some(n => n.level === 'block')) {
throw new Error('The plan cannot be executed.');
}
function checkExpiry() {
if (!Number.isFinite(plan.validUntil) ||
Date.now() / 1000 >= plan.validUntil - 15) {
throw new Error('Plan is expiring. Track any sent calls before replanning.');
}
}
checkExpiry();
const provider = new JsonRpcProvider(process.env.CHAINSTACK_BASE_RPC);
const network = await provider.getNetwork();
if (network.chainId !== 8453n) throw new Error('Expected Base mainnet.');
const wallet = new Wallet(process.env.WALLET_PRIVATE_KEY, provider);
if (getAddress(wallet.address) !== getAddress(request.wallet)) {
throw new Error('The signing wallet differs from the planning wallet.');
}
console.log(JSON.stringify({
request,
outcome: plan.route?.outcomeKind,
receive: plan.receive,
fees: plan.fees,
pullsAtMost: plan.pullsAtMost,
notices: plan.notices,
requiresConfirmation: plan.requiresConfirmation,
validUntil: plan.validUntil,
calls: plan.calls
}, null, 2));
const prompt = createInterface({ input: stdin, output: stdout });
let approved;
try {
approved = await prompt.question('Review the plan. Type SEND to submit: ');
} finally {
prompt.close();
}
if (approved !== 'SEND') throw new Error('Cancelled.');
const id = createHash('sha256')
.update(JSON.stringify({ request, plan })).digest('hex');
const lock = await open('execution-' + id + '.lock', 'wx');
await lock.close();
let swapHash;
for (const call of plan.calls) {
checkExpiry();
const tx = {
chainId: 8453,
to: getAddress(call.to),
data: call.data,
value: BigInt(call.value)
};
if (call.gas) tx.gasLimit = BigInt(call.gas);
else {
const fees = await provider.getFeeData();
const tip = fees.maxPriorityFeePerGas && fees.maxPriorityFeePerGas > 0n
? fees.maxPriorityFeePerGas : 1n;
tx.maxPriorityFeePerGas = tip;
tx.maxFeePerGas = (fees.maxFeePerGas ?? fees.gasPrice ?? tip) + tip;
tx.gasLimit = await provider.estimateGas({ ...tx, from: wallet.address });
}
const populated = await wallet.populateTransaction(tx);
const raw = await wallet.signTransaction(populated);
const hash = keccak256(raw);
await appendFile('execution.jsonl', JSON.stringify({
requestId: plan.requestId, chainId: 8453, txHash: hash
}) + '\n');
console.log('Transaction:', hash);
const sent = await provider.broadcastTransaction(raw);
const receipt = await sent.wait(1);
if (!receipt || receipt.status !== 1) throw new Error('Transaction failed.');
swapHash = hash;
}
console.log('Track the final swap:', JSON.stringify({
chainId: 8453, txHash: swapHash, requestId: plan.requestId
}));Run the executor while the plan is still valid:
node --env-file=.env execute.mjsThe executor uses Cleave's recommended gas limit when one is present. Otherwise, it estimates the call with a positive priority fee. Approvals run before the swap, so the swap's gas estimate sees the allowance created by the preceding transaction.
ethers.js populates the transaction, the local wallet signs it, and provider.broadcastTransaction submits the signed bytes through Chainstack. This uses eth_sendRawTransaction. The transaction hash is recorded before submission so you can investigate an interrupted request without immediately sending another swap.
The execution lock prevents the same saved plan from running twice. If execution stops after a transaction was prepared or sent, inspect execution.jsonl and check its hash onchain before planning another attempt. A mined source transaction and a completed cross-chain delivery are different checkpoints.
5. Track what arrived
Use the final swap hash, the source chain ID, and the plan's requestId with cleave_track_swap. In your agent client, ask:
Track the swap on Base, chain ID 8453, using transaction hash YOUR_FINAL_SWAP_HASH and requestId YOUR_REQUEST_ID. Report the current status and what arrived. Do not create another swap.For an application backend, Cleave exposes the same tracking operation through its Agent REST API:
curl https://api.cleave.fi/agent/v1/track_swap \
-H 'Content-Type: application/json' \
-d '{"chainId":8453,"txHash":"YOUR_FINAL_SWAP_HASH","requestId":"YOUR_REQUEST_ID"}'Read status together with arrived, matchesPlan, next, and pollAfterSec. For a pending or in-flight operation, wait and check again at the suggested interval. For cross-chain routes, keep tracking until the result explains whether tokens arrived, remain in flight, or entered a refund path.
6. Extend the flow across six chains
For another same-chain swap, change the planner's source and destination chain IDs, resolve the tokens on that network, and connect the executor to the matching Chainstack endpoint. Update the executor's intended-request checks at the same time. Token symbols and addresses are network-specific; use cleave_find_token to resolve the intended asset before requesting the plan.
For a cross-chain swap, set fromChainId to the network holding the sell token and toChainId to the receiving network. Cleave returns the source-chain calls in signing order. Submit those calls through the source-chain Chainstack endpoint, then use Cleave tracking to follow the destination outcome. Use a destination RPC endpoint for independent balance and receipt checks.
Cross-chain plans also describe the route's outcome kind. A route may return the requested token, a named fallback token, or enter a later refund path. Show those possible outcomes in the same review as the recipient and minimum amount, and use tracking to establish what actually happened.
Build from a complete transaction flow
You now have a path from an agent's swap request to a screened plan, wallet approval, signed submission, and delivery tracking. Cleave handles route planning, the wallet controls signing, and Chainstack connects the execution process to each network.
Start with the Base example, then add the endpoints and token rules your application needs. The same separation works for portfolio assistants, treasury tools, and trading interfaces that need to turn an intent into an observable onchain result.