Your resource for web content, online publishing
and the distribution of digital products.
«  
  »
S M T W T F S
 
 
 
 
 
 
1
 
2
 
3
 
4
 
5
 
6
 
7
 
8
 
9
 
10
 
11
 
12
 
13
 
14
 
15
 
16
 
17
 
18
 
19
 
20
 
21
 
22
 
23
 
24
 
25
 
26
 
27
 
28
 
29
 
30
 
31
 
 
 
 
 
 

This AI Agent Can Trade Forex Using Tweets and Real-Time Market Data—Here’s How You Can Build One

DATE POSTED:March 5, 2025
Series Introduction

In this mini-series of tutorial, we will utilze 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. It will be divided into 3 installments:

\

  • Part 1: MCP primer and how to build your first MCP server
  • Part 2: Connecting to MCP servers for trading actions
  • Part 3: Putting everything together for an autonomous trading agent

\ Through a practical step-by step and hands-on exercise, we can understand more deeply why MCP is critically important to build both powerful and flexible AI Agents that can handle any open-ended requests, by leveraging all the MCP tools and resources at its disposal.

Target Use Case - forex trading Trading
  • forex between USD and EUR
  • Monitor social media posts regarding economic relationship between US and Europe that might impact the exchange rate, for example, tariff, trade deals, and etc.
  • Start with an initial investment, and check return rate after several days
Potential Tools needed
  • Anthropic’s Model Context Protocol (MCP) as the foundation of our tech stack
  • Read latest forex exchange rate info
  • Read latest social media posts, esp from Truth Social (Truth Social API)
  • All other existing tools for web search, macro news, web 3 news, and more
What is MCP - a primer

Anthropic’s Model Context Protocol (MCP) is an open standard designed to streamline the integration of AI systems with diverse data sources and tools. By providing a universal framework, MCP addresses the complexities of connecting large language models (LLMs) to various external systems, enhancing their functionality and performance.

Why MCP? What Are the Benefits?

\ When building an AI Agents, we can use a simple pattern that enable the LLM to interact with data sources, tools (API calls), plus short-term and long-term memories for context. MCP enables a standardized and lightweight approach to achieve this interoperability without resorting more heavy-handed agentic frameworks.

\

  • Reduced Integration Complexity: MCP aims to solve the "N×M integration issue" where connecting numerous AI applications with diverse tools and data sources requires custom code for each integration. By providing a unified protocol, MCP eliminates the need for redundant custom code, saving developer time and resources.
  • Enhanced Performance: By enabling direct, standardized connections to data sources, MCP allows AI systems to retrieve relevant information more efficiently, leading to faster and more accurate responses.
  • Standardization and Interoperability: MCP’s universal framework facilitates seamless interaction between different AI models and data repositories, promoting a more cohesive and integrated AI ecosystem. You don’t have to use Antheopic’s Claude LLM.
How Does MCP Work?

\ MCP operates on a client-server architecture:

  • MCP Servers: These are lightweight programs that expose specific capabilities or data sources through the standardized MCP framework. They can connect to local data sources, such as files and databases, or remote services available through API.
  • MCP Clients: AI applications or tools act as clients that connect to MCP servers to access the exposed data or functionalities. This setup allows AI systems to utilize external information seamlessly.

\ Developers can implement MCP servers using SDKs in languages like Python and TypeScript. These servers define resources (data) and tools (functions) that AI models can access, enabling functionalities such as querying databases or interacting with APIs. Below are some examples of the MCP capabilities ranging from tools, resources to prompts.

\

\ There are ready-to-use MCP Clients today, such as Anthropics’ own Claude Desktop, Cursor, and LibreChat. You can also build your own client with the SDKs.

What Is the Current Status of MCP Support in the Industry?

Since its introduction in November 2024, MCP has seen growing adoption:

  • Early Adopters: Companies like Block and Apollo have integrated MCP into their systems. Additionally, development tool providers such as Zed, Replit, Codeium, and Sourcegraph are working with MCP to enhance their platforms, enabling AI agents to retrieve relevant information and produce more functional code with fewer attempts.
  • Server Builders: 1,100+ and counting. An open-source repository of pre-built MCP servers is available, offering integrations for common platforms like Google Drive, Slack, and GitHub.
  • Open-Source Community: MCP is open-source, encouraging contributions from developers worldwide. This openness fosters innovation and accelerates the development of new integrations and tools within the MCP ecosystem.
MCP’s Relevance to Crypto/Web3

MCP allows AI agents to interact seamlessly with diverse systems: databases, file systems, APIs, and blockchain-based platforms, via a universal protocol. In the context of cryptocurrency and Web3, this is significant because these ecosystems rely heavily on decentralized data, smart contracts, and real-time interactions. MCP’s ability to bridge LLMs with blockchain data or Web3 tools (e.g., wallets, decentralized apps, or DAOs) could streamline automation, enhance decision-making, and enable AI agents to perform tasks like executing transactions or querying on-chain data.

\ One good example is Solana Agent Kit by SendAI

\

  • Details: On February 19, 2025, a post on X from @sendaifun announced the Solana Agent Kit, which integrates MCP with over 100 Solana Actions.
  • Significance: Solana’s ecosystem, known for its speed and low-cost transactions, benefits from AI agents accessing on-chain actions (e.g., token swaps, NFT minting) via MCP. SendAI’s implementation suggests MCP could become a tool for building AI-driven Web3 applications on Solana.
For more information about MCP

The most up-to-date MCP tutorial today is “Building Agents with Model Context Protocol - Full Workshop” with Mahesh Murag of Anthropic, during the recent AI Engieer Summit.

https://youtu.be/kQmXtrmQ5Zg?embedable=true

Build your first MCP server for forex rates

Now enough theory and let’s get our hands dirty. We will start with a simple task: fetch latest exchange rate via API from openexchangerates.org.

\ In order to build a MCP server for this purpose, we will use Anthropic’s quickstart repository (Python version) as a starting point. Please download the code, compile, and make sure everything runs correctly before proceeding to the next step.

https://github.com/modelcontextprotocol/quickstart-resources?embedable=true

\ And the documentation is here https://modelcontextprotocol.io/quickstart/server

\ Now you can copy paste the following code to a new file called trader.py in the same directory. You will need to register for an API key from openexchangerates.org.

\

from typing import Any import httpx from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("trader") # Constants for forex API tool APP_ID = "YOUR_APP_ID" base_url = "https://openexchangerates.org/api/latest.json" @mcp.tool() async def get_forex_rate(currencies: list[str]) -> str: """Get current forex rates for USD to other major currencies. Args: currencies: List of currency codes to get rates for (e.g. ['EUR', 'GBP', 'JPY']) """ params = { "app_id": APP_ID, "symbols": ",".join(currencies), "prettyprint": "false", "show_alternative": "false" } headers = { "accept": "application/json" } async with httpx.AsyncClient() as client: try: response = await client.get(base_url, params=params, headers=headers) response.raise_for_status() data = response.json() # Format the response result = ["Current USD Exchange Rates:"] for currency, rate in data["rates"].items(): result.append(f"USD to {currency}: {rate:.4f}") return "\n".join(result) except Exception as e: return f"Error fetching forex rates: {str(e)}" if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio')

\

MCP client - Claude Desktop

Next you need to config MCP server for Claude Desktop by adding the following to the following file on MacOS: ~/Library/Application Support/Claude/claudedesktopconfig.json

\

{ "mcpServers": { "trader": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/FOLDER/", "run", "trader.py" ] } } }

\ You can also find where this config file is by going to Claude Desktop -> Settings -> Developer -> Edit Config

\

\ After saving the config file, relauch Claude Desktop. If there is no error, you should be able to see MCP tools are now available to you.

\

\ And then you can just ask “tell me today’s exchange rate between EUR and USD”, and allow the tool in the pop-up box, and you will invoke the tool and get results.

\

Bonus MCP server for Truth Social

Now let’s add one more tool to our trader MCP server: get the latest posts on Truth Social. For this task we are going to use the truthbrush API, which requires you to register for a Truth Social account. You either export your username and password to the environment, or keep them in .env file in the same directory.

\

TRUTHSOCIAL_USERNAME=YOUR_NAME TRUTHSOCIAL_PASSWORD=YOUR_PASSWORD

\ Add the following tool to trader.py

\

@mcp.tool() async def truth_posts(handle: str = "realDonaldTrump", days: int = 1) -> str: """Fetch recent posts from a Truth Social handle. Args: handle: Truth Social handle (e.g. realDonaldTrump) days: Number of days of posts to fetch """ from truthbrush.api import Api import datetime try: api = Api() created_after = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days) posts = [] for page in api.pull_statuses( username=handle, created_after=created_after, replies=False, pinned=False ): posts.append(f""" Timestamp: {page['created_at']} Content: {page['content']} """) if not posts: return f"No posts found for @{handle} in the last {days} day(s)" return "\n---\n".join(posts) except Exception as e: return f"Error fetching Truth Social posts: {str(e)}"

\ \ Once you relaunch the Claude Desktop, you will find that now you have two MCP tools at your disposal. And you can now ask for any recent post by specifying the handle and how many days of posts to retrieve.

\ Note: from my experience, you have to run this API from local machine where you were authenticated to Truth Social. Running this code on a remote server won’t work due to Truth Social’s security measures.

Remote MCP servers - search1api

Not only you can run MCP server locally, but also you can connect to remote MCP servers. Some data and service providers prefer to run their own MCP servers, in order to provide a uniform and reliable services to different AI agents and applications.

\ For our exercise, we will use search1api which is officially integrated with MCP. This MCP server provides 5 actions:

  • Web search functionality
  • News search functionality
  • Web page content extraction
  • Website sitemap extraction
  • Deep thinking and complex problem solving with DeepSeek R1

\ You need to register on search1api to get a free API key first. Multiple MCP servers in Claude Desktop Since we already run a local MCP server, we can add the new remote server to the config file since Claude deskptop support multiple MCP servers. I don’t know how many servers you can add, but you can try.

\ Config MCP server for Claude Desktop (MacOS)

~/Library/Application Support/Claude/claudedesktopconfig.json

\ \

{ "mcpServers": { "trader": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/", "run", "trader.py" ] }, "search1api": { "command": "npx", "args": ["-y", "search1api-mcp"], "env": { "SEARCH1API_KEY": “YOU_SEARCH1API_KEY" } } } }

\ Now relaunch Claude Desktop, and you will find you have 7 actions from 2 MCP servers at your disposal!

A combo exercise

Now we have built our own MCP server with two actions (forex rate, Truth Social posts), as well as connected to a remote MCP server for more actions (web search, news, crawl, reason), how can we leverage all of them for our forex trading task?

\ We can actually enter this simple prompt into the Claude Desktop client (pre-configured with above MCP servers):

\ [Prompt]: You are a forex trader, and you want to form your eur/usd strategy by looking at all the current information including macro news, social media posts, and exchange rates to form a recommended action for the next 7 days.

\

\ You can see the MCP client (Claude Desktop) automatically search for and call the relevant MCP tools at its disposal. We did not program a single line of code in order to facilitate the entire sequence of evens, which is entirely orchestrated by MCP client itself with the help of LLM (Claude Sonnet 3.7 in this example). This really shows the powerand flexibility of MCP in handling open-ended tasks.

Summary

In this tutorial, we covered a lot of ground. We investigated our use case: foreign exchange trading; as well as the potential tools to use. We had an overview of the MCP protocol, and why it matters in AI Agent development in the context of web 3. Finally we give a step-by-step guide to build your first two MCP servers (forex exchange rate, Truth social posts), and connect to a remote MCP server (search1api). We showed you how to launch your MCP server with the Claude Desktop client with the correct configurations. Finally, we ran a combo test to showcase MCP’s power to utilize all kinds of tools to fulfill its task.

\ If you have successfully completed the coding exercise, you are well prepared for our next two installments. So stay tuned for the upcoming episodes!

\

  • Part 2: Connecting to MCP servers for trading actions on chain
  • Part 3: Putting everything together for an autonomous trading agent
Technical References MCP references:

https://modelcontextprotocol.io/quickstart/server

https://github.com/modelcontextprotocol/quickstart-resources

Forex API

https://docs.openexchangerates.org/reference/api-introduction

Truth Social API

https://github.com/stanfordio/truthbrush

Search1API

https://github.com/fatwang2/search1api-mcp