MarkTechPost@AI 04月14日 00:55
Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文详细介绍了如何构建一个MCP(Model Context Protocol)服务器,该服务器允许Claude Desktop通过AlphaVantage API获取股票新闻情绪、当日涨幅榜和跌幅榜等实时金融数据。文章首先阐述了MCP在扩展LLM(大型语言模型)功能方面的作用,特别是解决LLM无法直接访问实时数据的问题。随后,文章提供了详细的步骤,包括环境设置、依赖安装、API密钥配置、MCP服务器的实现(包括工具函数的编写)以及与Claude Desktop的集成。最后,通过测试验证了服务器的有效性,使Claude Desktop能够通过MCP服务器获取实时股票信息,从而增强了其在金融分析方面的应用能力。

💡 **环境搭建:** 首先,通过安装uv包管理器来设置开发环境,并创建和激活虚拟环境,然后安装所需的依赖项,包括mcp、httpx和python-dotenv。

🔑 **API密钥配置:** 为了从AlphaVantage获取数据,需要注册一个API密钥。文章指导用户获取API密钥,并将其存储在.env文件中,以确保安全。

💻 **MCP服务器实现:** 核心部分是编写MCP服务器代码,包括导入必要的库、定义调用AlphaVantage API的辅助函数,以及实现两个核心工具:get_news_sentiment(获取股票新闻情绪)和get_top_movers(获取当日涨幅榜和跌幅榜)。

🛠️ **与Claude Desktop集成:** 为了让Claude Desktop能够使用MCP服务器,需要在Claude Desktop的配置文件中进行配置,指定MCP服务器的名称、启动命令和参数。配置完成后,重启Claude Desktop,即可通过界面中的工具图标访问MCP服务器提供的工具。

✅ **测试与验证:** 通过在Claude Desktop中输入特定问题,如“Apple的新闻情绪如何?”和“股市的涨幅榜和跌幅榜是什么?”,来测试MCP服务器的功能。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:

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 stockNewscd stockNews

We can now create and activate a virtual environment. For Mac or Linux:

uv venvsource .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:

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 Anyimport osimport httpxfrom mcp.server.fastmcp import FastMCPfrom dotenv import load_dotenv# Load .env variablesload_dotenv()API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")# Initialize FastMCP servermcp = FastMCP("alpha-finance")# ConstantsBASE_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""" {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 top gainers and losers from the stock market.    No arguments required.    """    data = await call_alpha_vantage("TOP_GAINERS_LOSERS", {})    if not data:        return "Couldn't retrieve top movers."    gainers = data.get("top_gainers", [])[:3]    losers = data.get("top_losers", [])[:3]    result = "**Top Gainers**\n"    result += "\n".join([        f"{g['ticker']} ({g.get('change_percentage', 'N/A')})"        for g in gainers    ])    result += "\n\n**Top Losers**\n"    result += "\n".join([        f"{l['ticker']} ({l.get('change_percentage', 'N/A')})"        for l in losers    ])    return result

Running the server

Finally, let’s initialize and run the server:

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

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

Step 5: Testing the server

First, ensure you have Claude for Desktop installed. If not, download and install the latest version from the official source. If you already have it, make sure it’s up to date.

Next, you’ll need to configure Claude to connect with your MCP server. To do this, open the claude_desktop_config.json file located in the Claude directory using any text editor. If the file doesn’t exist, go ahead 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 know that:

Once you’ve added this to your config file, save the file and restart Claude for Desktop to apply the changes.

Test with commands

To confirm that Claude for Desktop has recognized the two tools from your stockNews server, look for the hammer icon in the Claude interface — this icon indicates tool access.

After clicking on the hammer icon, you should see two tools listed:

We can test the server by running the following prompts:

When you ask Claude a question:

    The client sends your query to Claude.Claude reviews the available tools (like get_news_sentiment or get_top_movers) and determines which one(s) to use based on your question.The selected tool is executed via the MCP server you configured earlier.The tool returns the results back to Claude.Claude uses those results to craft a natural language response.The final response is shown to you in the chat interface.

This seamless flow is what allows Claude to interact with real-time data in a structured and controlled way.

Conclusion:

Our MCP-based stock insights server extends Claude Desktop’s capabilities by enabling real-time financial data retrieval. By integrating the AlphaVantage API with a custom MCP server, users can fetch live news sentiment and track top market movers directly through Claude. This setup empowers users with timely, actionable stock insights—all within a conversational interface—making financial analysis more efficient, contextual, and interactive.

The post Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop appeared first on MarkTechPost.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

MCP Claude Desktop AlphaVantage 金融数据 LLM
相关文章