paint-brush
Building an AI Trading Agent Using Anthropic’s MCP - Part IIby@zbruceli
206 reads New Story

Building an AI Trading Agent Using Anthropic’s MCP - Part II

by Bruce Li11mMarch 8th, 2025
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Part II of the series: use MCP and Solana AgentKit to build an AI Agent that can trade USD and EUR stablecoins.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coins Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Building an AI Trading Agent Using Anthropic’s MCP - Part II
Bruce Li HackerNoon profile picture

An AI Agent with a Web 3 wallet is a pig that can fly

Series Recap

This is the second installment of a mini-series of tutorials, where we utilize Anthropic’s Model Context Protocol (MCP) as the foundation to build an AI agent that can trade foreign currencies based on real-time market intelligence.


In Part 1 “MCP primer and how to build your first MCP server”, we focused on collecting market intelligence from custom-built MCP servers for forex price and social media posts. That was more of a “READ” function and needs to be expanded into a “WRITE” function. Therefore, in Part 2, we will be connecting to MCP servers that can carry out real trades for our forex trader.

AI Agents With Wallets: The Powerful Convergence of AI and Web3

The phrase "An AI agent with a wallet is a powerful thing" has become increasingly prominent at Web3 gatherings like the recent ETHDenver 2025. This simple statement encapsulates a transformative concept at the intersection of artificial intelligence and blockchain technology. Let's explore why this combination is generating so much excitement and what it means for the future of digital interactions.

What Are AI Agents With Wallets?

AI agents with wallets are autonomous software systems powered by artificial intelligence that can directly interact with blockchains through cryptocurrency wallets. Unlike traditional AI assistants that merely provide information, these agents can take financial actions independently - sending transactions, interacting with smart contracts, and managing digital assets.


The key innovation is combining:

  • Autonomous AI: Systems that can perceive, learn, reason, and act
  • Blockchain Integration: Direct access to decentralized financial systems
  • Programmable Money: The ability to execute financial transactions without human intervention

Why This Combination Is Powerful

The power of AI agents with crypto wallets stems from several capabilities:


  1. Autonomous Financial Actions: Agents can directly interact with blockchains to execute trades, provide liquidity, participate in governance, or manage investments without constant human supervision.
  2. 24/7 Operation: Unlike humans, AI agents can monitor markets and take action continuously without fatigue.
  3. Complex Decision Making: Advanced models can analyze vast amounts of on-chain and off-chain data to make sophisticated decisions about market trends, investment opportunities, and risk management.
  4. Programmable Economics: Creating systems where AI agents can participate in economic activities opens new possibilities for resource allocation and value creation.
  5. Reduced Intermediaries: By giving AI agents direct financial capabilities, many processes that traditionally required human middlemen can be automated.

Current Applications

AI agents with wallets are already finding use in several domains:


  1. DeFi Automation: Managing yield farming, liquidity provision, and optimal trading strategies across decentralized exchanges.
  2. Portfolio Management: Automatically rebalancing crypto holdings based on market conditions and risk parameters.
  3. NFT Creation and Trading: Generating digital art and making strategic decisions about NFT purchases and sales.
  4. DAO Governance: Analyzing proposals and voting based on predefined parameters or community sentiment.
  5. Content Creation: AI agents like Truth Terminal have emerged as content creators who can directly receive cryptocurrency payments.

MCP’s Role

Model Context Protocol (MCP) has emerged as a pivotal infrastructure layer at the intersection of AI agents and Web3, particularly for agents equipped with cryptocurrency wallets. Released by Anthropic in November 2024, MCP provides a standardized framework that enables AI agents to interact seamlessly with diverse data sources including blockchain networks, smart contracts, and decentralized applications.


For wallet-enabled AI agents, MCP serves as the crucial communication bridge that allows them to maintain contextual awareness when processing on-chain data, interpreting transaction histories, and making financial decisions autonomously. This protocol eliminates the need for custom integrations with each blockchain or DeFi platform, significantly reducing development complexity while ensuring AI agents can securely access the real-time blockchain data essential for executing transactions and managing digital assets.

Potential Tools Needed in Part II

Enough theory, now, let’s jump into coding action and experiments.


From Part I of the series, we have all the tools to form real-time intelligence on foreign exchanged related signals, we need action tools that can actually trade the foreign currencies. We could use traditional forex tools, but you probably need both a license to trade and a lot of money to cover the fees. So, we resort to stablecoins and decentralized exchanges for both convenience and the lowest fees.

Wallet Prerequisites

As a first step, you need to have a Solana wallet and its private key. In addition, you need to pre-fund the wallet with a small amount of SOL (e.g. 0.25 SOL).


Creating a Solana wallet with Phantom is straightforward and user-friendly.

  • First, visit phantom.com or download the Phantom app from your device's app store.
  • Click "Create New Wallet," and follow the setup wizard.
  • Phantom will generate a 12-word recovery phrase, which you must write down and store securely offline—this is crucial as it's your only backup if your device is lost or damaged.
  • After confirming your recovery phrase, create a strong password to protect your wallet.


To export your private key

  • open Phantom, go to Settings (gear icon), select "Security and Privacy," then "Export Private Key."
  • You'll need to enter your password to view the key.
  • Never share this with anyone, as it grants complete access to your funds.


Funding your Phantom wallet with 0.25 SOL requires first acquiring SOL from a cryptocurrency exchange like Coinbase or Binance. Alternatively, you can receive SOL directly from another person by sharing your wallet address with them. The transfer typically completes within seconds, and you can verify the transaction by checking your wallet balance or viewing your transaction history in the Phantom app.


Remember that maintaining a small SOL balance is necessary for paying transaction fees on the Solana network.

Install Solana AgentKit for MCP

AgentKit installation

First, get the source code:

git clone https://github.com/sendaifun/solana-agent-kit.git


Install AgentKit

npm install solana-agent-kit


cd examples/agent-kit-mcp-server


pnpm install

Code the MCP Server for Trading

Modify the index.ts file to add some actions for our needs. The example code has the first two actions “get_asset” and “deploy_token”. We added five more to enable trading as well as query wallet balance and token balance.


import { ACTIONS, SolanaAgentKit , startMcpServer  } from "solana-agent-kit";
import * as dotenv from "dotenv";
import { get_wallet_address } from "solana-agent-kit/dist/tools/index.js";

dotenv.config();

const agent = new SolanaAgentKit(
    process.env.SOLANA_PRIVATE_KEY!,
    process.env.RPC_URL!,
    {
        OPENAI_API_KEY: process.env.OPENAI_API_KEY || "",
    },
);

// Add your required actions here
const mcp_actions = {
    GET_ASSET: ACTIONS.GET_ASSET_ACTION,
    DEPLOY_TOKEN: ACTIONS.DEPLOY_TOKEN_ACTION,
    TRADE: ACTIONS.TRADE_ACTION,
    BALANCE: ACTIONS.BALANCE_ACTION,
    GET_INFO: ACTIONS.GET_INFO_ACTION,
    WALLET: ACTIONS.WALLET_ADDRESS_ACTION,
    TOKEN_BALANCES: ACTIONS.TOKEN_BALANCES_ACTION,
    
}

startMcpServer(mcp_actions, agent, { name: "solana-agent", version: "0.0.1" });


For a complete list of actions available from the Solana AgentKit, you can check this file. Currently, there are over 110 actions available.

https://github.com/sendaifun/solana-agent-kit/blob/main/src/actions/index.ts


Build the MCP Server

Since it is a TypeScript project, you need to build it.

pnpm run build


And it will create the Node.JS file below, which we will call from the MCP server:

build/index.js


MCP Client Configuration

Claude Desktop is the MCP client that we will use again in this tutorial. Please follow the instructions to modify the configuration file, for example in Mac OS.


~/Library/Application\ Support/Claude/claude_desktop_config.json


{
	"mcpServers": {
		"trader": {
			"command": "uv",
			"args": [
				"--directory",
				"/ABSOLUTE_PATH_TO_FOLDER/",
				"run",
				"trader.py"
			]
		},
		"search1api": {
			"command": "npx",
			"args": [
				"-y",
				"search1api-mcp"
			],
			"env": {
				"SEARCH1API_KEY": "YOUR_SEARCH1API_KEY"
			}
		},
		"agent-kit": {
			"command": "node",
			"env": {
				"RPC_URL": "https://api.mainnet-beta.solana.com",
				"SOLANA_PRIVATE_KEY": "YOUR_KEY"
			},
			"args": [
				"/ABSOLUTE_PATH_TO_FOLDER/build/index.js"
			]
		}
	}
}


As you can see, the last MCP server is the one for AgentKit. The RPC_URL is pointing to the official public API to Solana Mainnet, while the SOLANA_PRIVATE_KEY should be your wallet private key you exported earlier.

Test Solana AgentKit for MCP

Get Claude Desktop ready

After re-launching the Claude Desktop client, you should be able to see that now you have 14 tools at your disposal. 7 of them are from the two MCP servers from the last tutorial, while 7 more are from the new AgentKit server.



Check the Wallet Balance of SOL

The first thing you will do is check your SOL wallet balance. Sometimes, you need to give the full wallet address. You should be able to see 0.25 SOL in your agent wallet.


Optional: Issue a Meme Coin

This is just for fun: deploy a new token on Solana named Manusv2 with an initial supply of 1000000000. This is, of course, unrelated to the forex trading.



It is extremely easy to deploy a new token on the Solana network, which is very convenient. But it also means there will be gazillions of tokens with similar or same names. Therefore, it is always important to check the token’s Contract Address (CA) to make sure it is the right token that you want to trade.

Trade Foreign Currency (Stablecoins)

Now, we get to the meat of the trading actions. First, let’s trade 0.05 SOL for USDC on the Solana network. USDC is well known, and you do not need to specify the Contract Address. But it is always good practice to double-check.


Next, let’s trade 0.05 SOL for EURC. This time, we do specify the Contract Addrss for EURC (HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr) since it is a lesser-known stablecoin.



Wow, that looks so easy! We did not write a single line of code to use API to interact with a Decentralized Exchange to carry out the trade. We just typed in a few words in our favorite desktop chat app: Claude.


Let that sink in a bit, and appreciate the power of MCP.

Check the Wallet Balance of All Tokens

Sometimes, there are multiple MCP tools or actions that can handle similar tasks. The Claude Desktop client is smart enough to try a few of them, and eventually get the correct results.


You can see it in the example below where I ask for the wallet balance of all tokens. Initially, Claude used BALANCRE_ACTION, which only retired the SOL balance but without the USDC & EURC balance. Once Claude tried TOKEN_BALANCE_ACTIO, we got a list of all the tokens in the wallet. This shows the flexibility and robustness of the MCP protocol.


Combo Test: Forex Trading AI Assistant

The prompt is still important for MCP.

Just a quick memory refresh about MCP. The three categories of important assets for MCP are: tools, resources, and prompts. We touched upon Tools in the tutorials, and now it is time to talk a bit about prompts.


MCP clients like Claude Desktop are smart enough to carry out most tasks based on very simple instructions from humans. However, a good prompt is often necessary for more complex tasks. It can still be quite concise, but consider adding the following elements:

  • What is the objective and main ask
  • What tools and resources do you want MCP to search and execute
  • What thinking/planning process you would like to recommend
  • What final output should look like


Now, let’s get on with the combo test for an AI forex trading assistant.

Step 1: Analysis and Plan

[Prompt]: You are my assistant for forex trading. Research recent macro economic news, truth social posts by Trump, and everything else that might impact the forex exchange rate between USD and EUR. Evaluate my current wallet balance. Give me actionable plan: for example, buy or sell USD, buy or sell EUR.



Step 2: Execution

[Prompt]: yes proceed with USDC to EURC conversion



Step 3: Verification

check all token balances in my wallet



It is always good practice to double-check by using the Solana Explorer:

https://explorer.solana.com



Practical Assessment of MCP

We talked a lot about MCP’s strengths in the first episode. For example, MCP is Standard and Simple, and it has excellent momentum and is widely supported by both Web 2 and Web 3 developer communities.


However, MCP still faces significant usability challenges that limit its accessibility, particularly for non-technical users.

  • Server integration with Claude Desktop remains cumbersome, requiring developers to navigate command-line operations, manage dependencies, and configure ports - creating a substantial barrier to entry.


  • Additionally, the requirement to manually specify which MCP servers to use for each interaction creates unnecessary friction in the user experience. The lack of a streamlined discovery and selection mechanism means users must edit configuration files and restart applications just to add new data sources.


While these limitations are acknowledged on MCP's development roadmap, addressing them will be crucial for the protocol to realize its full potential as a universal standard for contextual AI assistance beyond the developer community. And we have also seen interesting approaches by the open-source community to address these shortcomings.

Summary

In this episode, we focused on actions for AI Agents. We started with the unique importance of AI Agents with Web 3 wallets, and MCP’s role in this emerging vision. Then we went about the practical steps of setting up the Solana AgentKit MCP server, where all our forex trading-related actions were added. We traded some USD and EUR stablecoins. In the final combo test, we use AI Agent as our trading assistant who not only can do smart analysis based on real-time signals but also carry out the actual trades.


The next and last part of this mini-series will be most exciting: the agent will be autonomous! It will run 24x7. It will wake up periodically, check the latest news and social posts, check his current portfolio position, and make short-medium term action plans against his long-term strategy. If it needs to re-balance the portfolio, it will execute the trades. And hopefully, it will evaluate his own performance and make some adjustments if needed. Are you excited? :-)