Code Implementation To Building A Model Context Protocol (mcp) Server And Connecting It With Claude Desktop

Trending 5 days ago
ARTICLE AD BOX

In this hands-on tutorial, we’ll build an MCP (Model Context Protocol) server that allows Claude Desktop to fetch banal news sentiment and regular apical gainers and movers via the AlphaVantage API. Since astir LLMs can’t straight entree real-time financial data, this solution uses MCP to supply real-time insights.

We’ll expose 2 devices from our server:

  • get_news_sentiment
  • get_top_movers

Let’s locomotion done each step.

Step 1: Setting Up nan Environment

We will first group up our situation and commencement pinch installing nan uv package manager. For Mac aliases 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 past create a caller task directory and initialize it pinch uv

uv init stockNews cd stockNews

We tin now create and activate a virtual environment. For Mac aliases Linux:

uv venv source .venv/bin/activate

For Windows:

uv venv .venv\Scripts\activate

We will now instal nan required dependencies

uv adhd mcp httpx python-dotenv

Step 3: Setting Up nan Environment Variables

We will now create a .env record that contains nan API cardinal for AlphaVantage. To make a free API key:

  • Go to https://www.alphavantage.co/
  • Click connected Get free API cardinal button, aliases usage nan pursuing url https://www.alphavantage.co/support/#api-key
  • Enter your email and different required details. You’ll person an API key—copy it and support it safe, arsenic this will beryllium utilized to authenticate your requests.

Now, create a .env record and adhd nan pursuing line:

ALPHA_VANTAGE_API_KEY = your_api_key

Step 4: Implementing nan MCP Server and integrating AlphaVantage

First create a stockNews.py file successful nan directory that we created and adhd nan pursuing codification snippets:

Importing packages and mounting up nan instance:

We will first import nan basal packages and group up lawsuit to usage nan 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 adhd our helper functions for querying nan information 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 pinch httpx.AsyncClient() arsenic client: try: consequence = await client.get(BASE_URL, params=params, timeout=30.0) response.raise_for_status() return response.json() isolated from Exception: return None

Implementing instrumentality execution

The instrumentality execution handler is responsible for executing nan logic of each tool.

@mcp.tool() async def get_news_sentiment(ticker: str) -> str: """Get news sentiment information for a banal ticker. Args: ticker: Stock ticker awesome (e.g., MSFT, AAPL) """ information = await call_alpha_vantage("NEWS_SENTIMENT", {"tickers": ticker.upper()}) if not information aliases "feed" not successful data: return "Couldn't retrieve news sentiment." articles = data["feed"][:3] consequence = [] for point successful articles: result.append(f""" 📰 {item['title']} Summary: {item['summary']} Source: {item['source']} | Published: {item['time_published']} """) return "\n---\n".join(result) @mcp.tool() async def get_top_movers() -> str: """Get apical gainers and losers from nan banal market. No arguments required. """ information = await call_alpha_vantage("TOP_GAINERS_LOSERS", {}) if not data: return "Couldn't retrieve apical movers." gainers = data.get("top_gainers", [])[:3] losers = data.get("top_losers", [])[:3] consequence = "**Top Gainers**\n" consequence += "\n".join([ f"{g['ticker']} ({g.get('change_percentage', 'N/A')})" for g successful gainers ]) consequence += "\n\n**Top Losers**\n" consequence += "\n".join([ f"{l['ticker']} ({l.get('change_percentage', 'N/A')})" for l successful losers ]) return result

Running nan server

Finally, let’s initialize and tally nan server:

if __name__ == "__main__": mcp.run(transport="stdio")

We will now trial our server from an existing MCP host, Claude for Desktop.

Step 5: Testing nan server

First, guarantee you person Claude for Desktop installed. If not, download and instal nan latest type from nan charismatic source. If you already person it, make judge it’s up to date.

Next, you’ll request to configure Claude to link pinch your MCP server. To do this, unfastened nan claude_desktop_config.json record located successful nan Claude directory utilizing immoderate matter editor. If nan record doesn’t exist, spell up and create it manually.

For MacOS/Linux:

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

For Windows:

{ "mcpServers": { "stockNews": { "command": "uv", "args": [ "--directory", "C:\\ABSOLUTE\\PATH\\TO\\PARENT\\FOLDER\\stockNews", "run", "stockNews.py" ] } } }

This configuration lets Claude for Desktop cognize that:

  • There’s an MCP server called “stockNews”.
  • It should beryllium launched utilizing nan pursuing command:
    uv –directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/stockNews tally stockNews.py

Once you’ve added this to your config file, save nan record and restart Claude for Desktop to use nan changes.

Test pinch commands

To corroborate that Claude for Desktop has recognized nan 2 devices from your stockNews server, look for nan hammer icon successful nan Claude interface — this icon indicates instrumentality access.

After clicking connected nan hammer icon, you should spot 2 devices listed:

We tin trial nan server by moving nan pursuing prompts:

  • What is nan news sentiment for Apple?
  • Who are nan apical gainers and losers from nan banal market?

When you inquire Claude a question:

  1. The customer sends your query to Claude.
  2. Claude reviews nan disposable tools (like get_news_sentiment aliases get_top_movers) and determines which one(s) to usage based connected your question.
  3. The selected instrumentality is executed via nan MCP server you configured earlier.
  4. The instrumentality returns nan results backmost to Claude.
  5. Claude uses those results to trade a earthy connection response.
  6. The last consequence is shown to you successful nan chat interface.

This seamless travel is what allows Claude to interact pinch real-time information successful a system and controlled way.

Conclusion:

Our MCP-based banal insights server extends Claude Desktop’s capabilities by enabling real-time financial information retrieval. By integrating nan AlphaVantage API pinch a civilization MCP server, users tin fetch unrecorded news sentiment and way apical marketplace movers straight done Claude. This setup empowers users pinch timely, actionable banal insights—all wrong a conversational interface—making financial study much efficient, contextual, and interactive.

I americium a Civil Engineering Graduate (2022) from Jamia Millia Islamia, New Delhi, and I person a keen liking successful Data Science, particularly Neural Networks and their exertion successful various areas.

More