Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop
In this hands-on tutorial, we’ll build an MCP (Model Context Protocol) server that allows Claude Desktop to fetch stock news sentiment and daily top gainers and movers via the AlphaVantage API. Since most LLMs can’t directly access real-time financial data, this solution uses MCP to provide real-time insights. We’ll expose two tools from our server: […] The post Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop appeared first on MarkTechPost.

In this hands-on tutorial, we’ll build an MCP (Model Context Protocol) server that allows Claude Desktop to fetch stock news sentiment and daily top gainers and movers via the AlphaVantage API. Since most LLMs can’t directly access real-time financial data, this solution uses MCP to provide real-time insights.
We’ll expose two tools from our server:
- get_news_sentiment
- get_top_movers
Let’s walk through each step.
Step 1: Setting Up the Environment
We will first set up our environment and start with installing the uv package manager. For Mac or Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh
For Windows (PowerShell):
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
We will then create a new project directory and initialize it with uv
uv init stockNews
cd stockNews
We can now create and activate a virtual environment. For Mac or Linux:
uv venv
source .venv/bin/activate
For Windows:
uv venv
.venv\Scripts\activate
We will now install the required dependencies
uv add mcp httpx python-dotenv
Step 3: Setting Up the Environment Variables
We will now create a .env file that contains the API key for AlphaVantage. To generate a free API key:
- Go to https://www.alphavantage.co/
- Click on Get free API key button, or use the following url https://www.alphavantage.co/support/#api-key
- Enter your email and other required details. You’ll receive an API key—copy it and keep it safe, as this will be used to authenticate your requests.
Now, create a .env file and add the following line:
ALPHA_VANTAGE_API_KEY = your_api_key
Step 4: Implementing the MCP Server and integrating AlphaVantage
First create a stockNews.py file in the directory that we created and add the following code snippets:
Importing packages and setting up the instance:
We will first import the necessary packages and set up instance to use the API
from typing import Any
import os
import httpx
from mcp.server.fastmcp import FastMCP
from dotenv import load_dotenv
# Load .env variables
load_dotenv()
API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")
# Initialize FastMCP server
mcp = FastMCP("alpha-finance")
# Constants
BASE_URL = "https://www.alphavantage.co/query"
Helper functions
Next, let’s add our helper functions for querying the data from AlphaVantage.
async def call_alpha_vantage(endpoint: str, params: dict[str, Any]) -> dict[str, Any] | None:
"""Generic async caller to Alpha Vantage."""
params["apikey"] = API_KEY
params["function"] = endpoint
async with httpx.AsyncClient() as client:
try:
response = await client.get(BASE_URL, params=params, timeout=30.0)
response.raise_for_status()
return response.json()
except Exception:
return None
Implementing tool execution
The tool execution handler is responsible for executing the logic of each tool.
@mcp.tool()
async def get_news_sentiment(ticker: str) -> str:
"""Get news sentiment data for a stock ticker.
Args:
ticker: Stock ticker symbol (e.g., MSFT, AAPL)
"""
data = await call_alpha_vantage("NEWS_SENTIMENT", {"tickers": ticker.upper()})
if not data or "feed" not in data:
return "Couldn't retrieve news sentiment."
articles = data["feed"][:3]
result = []
for item in articles:
result.append(f"""
read more