Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Report: 71% of tech leaders won’t hire devs without AI skills

      July 17, 2025

      Slack’s AI search now works across an organization’s entire knowledge base

      July 17, 2025

      In-House vs Outsourcing for React.js Development: Understand What Is Best for Your Enterprise

      July 17, 2025

      Tiny Screens, Big Impact: The Forgotten Art Of Developing Web Apps For Feature Phones

      July 16, 2025

      Too many open browser tabs? This is still my favorite solution – and has been for years

      July 17, 2025

      This new browser won’t monetize your every move – how to try it

      July 17, 2025

      Pokémon has partnered with one of the biggest PC gaming brands again, and you can actually buy these accessories — but do you even want to?

      July 17, 2025

      AMD’s budget Ryzen AI 5 330 processor will introduce a wave of ultra-affordable Copilot+ PCs with its mobile 50 TOPS NPU

      July 17, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The details of TC39’s last meeting

      July 18, 2025
      Recent

      The details of TC39’s last meeting

      July 18, 2025

      Reclaim Space: Delete Docker Orphan Layers

      July 18, 2025

      Notes Android App Using SQLite

      July 17, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      KeySmith – SSH key management

      July 17, 2025
      Recent

      KeySmith – SSH key management

      July 17, 2025

      Pokémon has partnered with one of the biggest PC gaming brands again, and you can actually buy these accessories — but do you even want to?

      July 17, 2025

      AMD’s budget Ryzen AI 5 330 processor will introduce a wave of ultra-affordable Copilot+ PCs with its mobile 50 TOPS NPU

      July 17, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop

    Code Implementation to Building a Model Context Protocol (MCP) Server and Connecting It with Claude Desktop

    April 13, 2025

    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:

    Copy CodeCopiedUse a different Browser
    curl -LsSf https://astral.sh/uv/install.sh | sh  

    For Windows (PowerShell):

    Copy CodeCopiedUse a different Browser
    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

    Copy CodeCopiedUse a different Browser
    uv init stockNews
    cd stockNews

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

    Copy CodeCopiedUse a different Browser
    uv venv
    source .venv/bin/activate

    For Windows:

    Copy CodeCopiedUse a different Browser
    uv venv
    .venvScriptsactivate

    We will now install the required dependencies

    Copy CodeCopiedUse a different Browser
    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:

    Copy CodeCopiedUse a different Browser
    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

    Copy CodeCopiedUse a different Browser
    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.

    Copy CodeCopiedUse a different Browser
    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.

    Copy CodeCopiedUse a different Browser
    @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 += "nn**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:

    Copy CodeCopiedUse a different Browser
    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:

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

    For Windows:

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

    This configuration lets Claude for Desktop know that:

    • There’s an MCP server called “stockNews”.
    • It should be launched using the following command:
      uv –directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/stockNews run stockNews.py

    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:

    • What is the news sentiment for Apple?
    • Who are the top gainers and losers from the stock market?

    When you ask Claude a question:

    1. The client sends your query to Claude.
    2. Claude reviews the available tools (like get_news_sentiment or get_top_movers) and determines which one(s) to use based on your question.
    3. The selected tool is executed via the MCP server you configured earlier.
    4. The tool returns the results back to Claude.
    5. Claude uses those results to craft a natural language response.
    6. 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.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleReasoning Models Know When They’re Right: NYU Researchers Introduce a Hidden-State Probe That Enables Efficient Self-Verification and Reduces Token Usage by 24%
    Next Article 8 Comic-Inspired Snippets Powered by CSS & JavaScript

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    July 18, 2025
    Machine Learning

    Implementing on-demand deployment with customized Amazon Nova models on Amazon Bedrock

    July 17, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-36560 – A-Blog CMS SSRF Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Avast Antivirus Vulnerability Let Attackers Escalate Privileges

    Security

    I’m a Linux power user, and the latest Ubuntu update put a smile on my face

    News & Updates

    Four Critical RCE Flaws Found in Grafana Plugins via Chromium: Patch Now!

    Security

    Highlights

    CVE-2025-37834 – Linux Kernel: Dirty Swapcache Page Reclamation Vulnerability

    May 8, 2025

    CVE ID : CVE-2025-37834

    Published : May 8, 2025, 7:15 a.m. | 58 minutes ago

    Description : In the Linux kernel, the following vulnerability has been resolved:

    mm/vmscan: don’t try to reclaim hwpoison folio

    Syzkaller reports a bug as follows:

    Injecting memory failure for pfn 0x18b00e at process virtual address 0x20ffd000
    Memory failure: 0x18b00e: dirty swapcache page still referenced by 2 users
    Memory failure: 0x18b00e: recovery action for dirty swapcache page: Failed
    page: refcount:2 mapcount:0 mapping:0000000000000000 index:0x20ffd pfn:0x18b00e
    memcg:ffff0000dd6d9000
    anon flags: 0x5ffffe00482011(locked|dirty|arch_1|swapbacked|hwpoison|node=0|zone=2|lastcpupid=0xfffff)
    raw: 005ffffe00482011 dead000000000100 dead000000000122 ffff0000e232a7c9
    raw: 0000000000020ffd 0000000000000000 00000002ffffffff ffff0000dd6d9000
    page dumped because: VM_BUG_ON_FOLIO(!folio_test_uptodate(folio))
    ————[ cut here ]————
    kernel BUG at mm/swap_state.c:184!
    Internal error: Oops – BUG: 00000000f2000800 [#1] SMP
    Modules linked in:
    CPU: 0 PID: 60 Comm: kswapd0 Not tainted 6.6.0-gcb097e7de84e #3
    Hardware name: linux,dummy-virt (DT)
    pstate: 80400005 (Nzcv daif +PAN -UAO -TCO -DIT -SSBS BTYPE=–)
    pc : add_to_swap+0xbc/0x158
    lr : add_to_swap+0xbc/0x158
    sp : ffff800087f37340
    x29: ffff800087f37340 x28: fffffc00052c0380 x27: ffff800087f37780
    x26: ffff800087f37490 x25: ffff800087f37c78 x24: ffff800087f377a0
    x23: ffff800087f37c50 x22: 0000000000000000 x21: fffffc00052c03b4
    x20: 0000000000000000 x19: fffffc00052c0380 x18: 0000000000000000
    x17: 296f696c6f662865 x16: 7461646f7470755f x15: 747365745f6f696c
    x14: 6f6621284f494c4f x13: 0000000000000001 x12: ffff600036d8b97b
    x11: 1fffe00036d8b97a x10: ffff600036d8b97a x9 : dfff800000000000
    x8 : 00009fffc9274686 x7 : ffff0001b6c5cbd3 x6 : 0000000000000001
    x5 : ffff0000c25896c0 x4 : 0000000000000000 x3 : 0000000000000000
    x2 : 0000000000000000 x1 : ffff0000c25896c0 x0 : 0000000000000000
    Call trace:
    add_to_swap+0xbc/0x158
    shrink_folio_list+0x12ac/0x2648
    shrink_inactive_list+0x318/0x948
    shrink_lruvec+0x450/0x720
    shrink_node_memcgs+0x280/0x4a8
    shrink_node+0x128/0x978
    balance_pgdat+0x4f0/0xb20
    kswapd+0x228/0x438
    kthread+0x214/0x230
    ret_from_fork+0x10/0x20

    I can reproduce this issue with the following steps:

    1) When a dirty swapcache page is isolated by reclaim process and the
    page isn’t locked, inject memory failure for the page.
    me_swapcache_dirty() clears uptodate flag and tries to delete from lru,
    but fails. Reclaim process will put the hwpoisoned page back to lru.

    2) The process that maps the hwpoisoned page exits, the page is deleted
    the page will never be freed and will be in the lru forever.

    3) If we trigger a reclaim again and tries to reclaim the page,
    add_to_swap() will trigger VM_BUG_ON_FOLIO due to the uptodate flag is
    cleared.

    To fix it, skip the hwpoisoned page in shrink_folio_list(). Besides, the
    hwpoison folio may not be unmapped by hwpoison_user_mappings() yet, unmap
    it in shrink_folio_list(), otherwise the folio will fail to be unmaped by
    hwpoison_user_mappings() since the folio isn’t in lru list.

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    NVIDIA NeMo Framework: High-Risk Vulnerabilities Allow Remote Code Execution

    April 23, 2025

    CVE-2023-53140 – “Linux Kernel SCSI Core /proc/scsi Directory Removal Vulnerability”

    May 2, 2025

    CISA Warns 2 SonicWall Vulnerabilities Under Active Exploitation

    May 6, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.