How to Build an MCP Server for AI
Let’s dive into creating a Model Context Protocol (MCP) server. We’ll build one that grabs stock prices and, since Claude can’t generate images on its own, we’ll use Truepix AI to add that superpower. By the end, you’ll have a simple MCP server that connects your AI to real-world tools — think stock tickers and image creation — all in a few steps.
What’s MCP in Simple Terms? The USB-C for AI
MCP is like a universal plug for AI. Imagine the frustration of incompatible chargers before USB-C came along. MCP solves a similar problem for AI, creating a standard way for AI Clients (like Claude, Cursor or others) to connect to a wide range of tools and data sources. Think of it as a standardized port that allows your AI to effortlessly access things like real-time stock prices, your email inbox, or even complex APIs, all without complicated, one-off setups.
Imagine giving your AI a Swiss Army knife. With MCP, it gains a set of tools: it can fetch information, generate images, interact with services, and even automate tasks, all while keeping your data access secure within your own infrastructure. It’s about making AI agents truly capable and versatile.
Quick Summary: MCP links AI to services, simplifies integrations, and keeps data safe.
What We’re Building
- A server to:
- Get live stock prices (e.g., Apple’s “AAPL” ticker).
- Create images from text using Truepix AI.
- Then, we’ll hook it up to Claude for Desktop so your AI can use these tools.
Step 1: Set Up Your Tools
We’ll use uv to manage our Python project. Here’s how to get started:
MacOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | shWindows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Next, set up your project:
uv init server
cd server
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
uv add "mcp[cli]" httpx aiohttp yfinance asyncio
touch server.py # Windows: New-Item server.pyThis installs everything we need, including MCP and libraries for stocks and APIs.
Step 2: Write the MCP Server
Create a file called server.py and add this code. It defines two tools — one for stock prices, one for images.
server.py
import yfinance as yf
from mcp.server.fastmcp import FastMCP
import asyncio
import aiohttp
mcp = FastMCP("stock_prices")
@mcp.tool()
async def get_stock_price(ticker: str) -> str:
"""
Fetches the current stock price for a ticker (e.g., AAPL).
"""
try:
stock = yf.Ticker(ticker)
info = stock.info
price = info.get('currentPrice') or info.get('regularMarketPrice')
if not price:
return f"No price found for {ticker}"
return f"${price:.2f}"
except Exception as e:
return f"Error: {str(e)}"
@mcp.tool()
async def generate_t2i_image(prompt: str) -> str:
"""
Generates an image from a text prompt using Truepix AI.
"""
api_url = "https://api.truepix.ai" # Coming SOON
headers = {"Authorization": "Bearer YOUR_API_KEY"}
payload = {"prompt": prompt}
try:
async with aiohttp.ClientSession() as session:
# Start image generation
async with session.post(api_url, json=payload, headers=headers) as response:
if response.status != 200:
return f"Error: Status {response.status}"
data = await response.json()
task_id = data.get("task_id")
if not task_id:
return "Error: No task ID"
# Check progress every 10 seconds
while True:
poll_url = f"https://api.truepix.ai" # Coming SOON
async with session.get(poll_url, headers=headers) as poll_response:
if poll_response.status != 200:
return f"Error: Status {poll_response.status}"
result = await poll_response.json()
if result.get("status") == "success":
return result.get("result_url", "Error: No URL")
await asyncio.sleep(10)
except Exception as e:
return f"Error: {str(e)}"
if __name__ == "__main__":
mcp.run(transport='stdio')Note: This code fetches stock prices via Yahoo Finance
Step 3: Connect to Claude for Desktop
Claude for Desktop lets your AI use this server. Here’s how:
- Install Claude for Desktop: Grab it here.
- Edit Config: To modify Claude’s configuration, you need to edit the claude_desktop_config.json file. Follow these steps:
> Open Claude Desktop.
> Navigate to Settings.
> Go to the Developer section.
> Select Edit Config — this will open the claude_desktop_config.json file. in your preferred code editor for editing. - Add Your Server:
{
"mcpServers": {
"server": {
"command": "/full/path/to/uv", # **Replace this** with the full path to your 'uv' executable
"args": [
"--directory",
"/full/path/to/server",# **Replace this** with the full absolute path to your 'server' project directory
"run",
"server.py"
]
}
}
}Finding the uv Path: To find the full path to your uv executable, open your terminal and run which uv on macOS/Linux, or where uv on Windows. Copy the output and replace /full/path/to/uv in the JSON configuration with this path.
Setting the Project Path: Replace /full/path/to/server with the absolute path to the server directory where you created server.py. Using absolute paths is crucial to ensure Claude Desktop can find and run your MCP server correctly, regardless of where Claude Desktop is started from.
- Restart Claude Desktop: After saving the configuration file, close and restart Claude Desktop for the changes to take effect.
Once configured and restarted, Claude Desktop should now be aware of your MCP server and the tools it provides. You can now interact with Claude and ask it to perform actions using these tools! Try prompts like:
- “What is the current stock price of AAPL?”
Result
If everything is set up correctly, you should see a hammer icon in the interface, indicating that tools are available for use.
Tool use for Generating an image :
More Article on MCP:
> MCP SERVER WITH AGENTS
> MCP:STDIO VS SSE
How It All Fits Together
- Claude (MCP Client/Host): Claude acts as the intelligent brain, equipped with an MCP client. It wants to extend its capabilities by using external tools.
- Your MCP Server (server.py): This is the tool provider (the MCP server). It exposes specific functionalities — like fetching stock prices and generating images — via the MCP protocol.
- MCP Protocol: This is the standardized language and set of rules that allows Claude (via its MCP client) to communicate with your MCP server. It’s the “bridge” enabling smooth interaction.
Your Client sends a request (e.g., “Get AAPL price”), the Server processes it, and sends back “$174.50”. Simple and fast.
Full Documentation: https://modelcontextprotocol.io/quickstart/server
Frequently Asked Questions (FAQs) About MCP
- What exactly is the Model Context Protocol (MCP)?
MCP is an open standard that defines how AI models can interact with external tools, resources, and prompts in a consistent and secure manner. It’s designed to simplify the process of giving AI agents access to real-world data and capabilities, making them more useful and versatile. Think of it as creating a standardized “API for AI agents.” - Is MCP specific to Claude, or does it work with other AI models?
MCP is designed as an open protocol, meaning it’s not tied to any specific AI model or provider. While this tutorial uses Claude Desktop as an example host, the goal of MCP is to be compatible with various AI models and platforms. The benefit of a standard like MCP is that it fosters interoperability across the AI ecosystem. Any AI model or platform that implements the MCP client can potentially connect to any MCP server, regardless of the AI provider. - What kinds of things can I build with MCP Servers?
The possibilities are virtually limitless! If an action can be automated or data can be accessed programmatically, it can likely be exposed as an MCP tool. Examples include: - Data Retrieval: Connect to databases, spreadsheets, CRM systems, or any data source to provide AI with information.
- Application Integration: Allow AI to interact with apps like email clients, calendars, task managers, social media, e-commerce platforms.
- Smart Home Control: Enable AI to control smart devices, adjust lighting, temperature, security systems.
- Content Generation & Manipulation: Use APIs to generate text, images, audio, video, or manipulate existing digital content.
- Workflow Automation: Build complex workflows where AI orchestrates actions across multiple tools and services.
About Truepix AI
Truepix AI is a content generation platform where you not only create stunning images and videos but also retain ownership of your creations. Truepix AI an excellent platform for integrating content generation capabilities into AI projects like this, offering both power and control over your creative assets.
