Certainly! Here’s a rewriten version of the content you provided:
—
In this hands-on tutorial, we’ll create an MCP (Model Context Protocol) server designed to help Claude Desktop retrieve stock news sentiment and track daily top gainers and movers using the AlphaVantage API. Given that most LLMs lack the direct capability to access real-time financial data, our solution leverages MCP to offer live insights.
We’ll implement two primary tools in our server:
- get_news_sentiment
- get_top_movers
Let’s go through the setup step by step.
Step 1: Setting Up the Environment
We’ll begin by configuring our environment, starting with the installation of the uv package manager. Instructions for Mac or Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh
Instructions for Windows (PowerShell):
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
Next, create a new project directory and initialize it with uv:
uv init stockNews
cd stockNews
Create and activate a virtual environment. For Mac or Linux:
uv venv
source .venv/bin/activate
For Windows:
uv venv
.venvScriptsactivate
Now, install the necessary dependencies:
uv add mcp httpx python-dotenv
Step 3: Configuring Environment Variables
Create a .env file to store the AlphaVantage API key. To obtain a free API key:
Add this line to your .env file:
ALPHA_VANTAGE_API_KEY=your_api_key
Step 4: Developing the MCP Server and Integrating AlphaVantage
Create a stockNews.py file in your project directory and include the following code snippets:
To import necessary packages and set up the instance for API interaction:
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
Add helper functions for querying AlphaVantage data:
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
Define the tool execution handlers for the required logic:
@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"""
馃摪 {item['title']}
Summary: {item['summary']}
Source: {item['source']} | Published: