Close Menu
    Facebook LinkedIn YouTube WhatsApp X (Twitter) Pinterest
    Trending
    • Rehumanizing global health care with agentic AI
    • Robots-Blog | Praxisprojekt mit fischertechnik an der Hochschule Hof in Bayern
    • Ancient giant octopuses were apex predators, study finds
    • Barcelona’s Zazume raises €2.5 million to scale its AI-powered rental management platform
    • How to Shop Like a Pro During Amazon Prime Day (2026)
    • CFTC seeks injunction in Kalshi Rhode Island dispute
    • As AI Expands, Erin Brockovich Taps Communities to Map Data Center Concerns
    • Direct-to-Cell Technology: Enabling Satellite Connectivity for Legacy Devices
    Facebook LinkedIn WhatsApp
    Times FeaturedTimes Featured
    Tuesday, June 2
    • Home
    • Founders
    • Startups
    • Technology
    • Profiles
    • Entrepreneurs
    • Leaders
    • Students
    • VC Funds
    • More
      • AI
      • Robotics
      • Industries
      • Global
    Times FeaturedTimes Featured
    Home»Artificial Intelligence»Model Context Protocol (MCP) Tutorial: Build Your First MCP Server in 6 Steps
    Artificial Intelligence

    Model Context Protocol (MCP) Tutorial: Build Your First MCP Server in 6 Steps

    Editor Times FeaturedBy Editor Times FeaturedJune 11, 2025No Comments10 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Telegram Email WhatsApp Copy Link


    Context Protocol (MCP)?

    Because of the emergence of AI brokers and RAG-based purposes in recent times, there’s an growing demand for customizing Giant Language Fashions (LLMs) by integrating with exterior assets (e.g. RAG-based methods) and instruments (e.g. Agent-based methods). This enhances LLMs’ present capabilities by incorporating exterior information and enabling autonomous activity execution.

    Mannequin Context Protocol (MCP), first launched in November 2024 by Anthropic, has grown in recognition because it provides a extra coherent and constant method to join LLMs with exterior instruments and assets, making it a compelling various to constructing customized API integrations for every use case. MCP is a standardized, open-source protocol that gives a constant interface that allow LLM to work together with varied exterior instruments and assets, therefore enable finish customers to MCP server that has been encapsulated with enhanced functionalities. In comparison with present agentic system design patterns, MCP provides a number of key advantages:

    • Improve scalability and maintainability of the system by way of standardized integrations.
    • Scale back duplicate growth effort since a single MCP server implementation works with a number of MCP purchasers.
    • Keep away from vendor lock-in by offering flexibility to change between LLM suppliers, because the LLM is now not tightly coupled with the agentic system.
    • Velocity up the event course of considerably by enabling fast creation of workable merchandise.

    This text is intention for guiding you thru the basics of Mannequin Context Protocol and the important elements of constructing an MCP server. We are going to apply these ideas by way of a sensible instance of constructing a MCP server that enables LLMs to summarize and visualize GitHub codebases by merely offering a URL like the instance beneath.

    Consumer Enter:

    https://github.com/aws-samples/aws-cdk-examples/blob/main/python/codepipeline-docker-build/Base.py

    MCP Output:


    Understanding MCP Parts

    MCP Architecture

    MCP Structure

    MCP adopts a client-server structure the place the consumer is a tool or utility that requests providers supplied by a centralized server. A useful analogy for the client-server relationship is that of a buyer and a restaurant. The client acts just like the client-side, sending requests by ordering from the menu, whereas the restaurant resembles the server, offering providers like dishes and seatings. The restaurant possesses enough assets to serve a number of clients in a brief time frame, whereas clients solely want to fret about receiving their orders.

    MCP structure consists of three elements: MCP server, MCP consumer and MCP host. MCP server provides instruments and assets, exposing functionalities that AI fashions can leverage by way of structured requests. MCP host provides the runtime surroundings that manages communication between purchasers and servers, similar to Claude Desktop or IDEs with MCP-supported extensions. If we proceed with the identical customer-restaurant analogy above, MCP host may be thought of as a restaurant administration system that coordinates communications between clients (purchasers) and eating places, handles order taking and cost processing. MCP consumer is usually constructed into the host utility permitting the customers to work together with the server by way of an interface. Nevertheless, there may be the flexibleness of creating customized MCP purchasers for specialised use instances and necessities, similar to constructing a easy AI internet app utilizing Streamlit to help extra front-end functionalities.

    MCP Server Parts

    On this article, we’ll concentrate on understanding MCP server and apply our information to construct a easy, customized MCP server. MCP server wraps round varied APIs calls to the exterior instruments and assets, enabling the purchasers accessing these functionalities with out worrying concerning the further setup. The MCP server helps incorporating three varieties of elements which aligns with three frequent LLM customization methods.

    • Sources are information, recordsdata and paperwork that function the exterior information base to complement LLM’s present information. That is notably helpful in a RAG-based system.
    • Instruments are executable features and integrations with different applications to complement LLM’s motion house, for instance, carry out Google Search, create a Figma prototype and many others, which may be leveraged in an Agent-based system.
    • Prompts are pre-defined instruction templates to information LLM’s output, e.g. response in an expert or informal tone. That is helpful within the system that advantages from immediate engineering methods.

    If you’re to know extra about LLM customization methods, try my earlier article and video on “6 Common LLM Customization Strategies Briefly Explained”.


    Construct Your MCP Server in 6 Steps

    We are going to use a easy instance to exhibit the best way to construct your first MCP server utilizing Python, which allows calling a customized visualize_code instrument to show uncooked code recordsdata extracted from GitHub repositories into visible diagrams like the next instance.

    For folks with information science background studying to construct MCP servers, there are a number of software program growth ideas that could be unfamiliar however necessary to grasp: asynchronous programming for dealing with asynchronous operations, consumer/server structure, and Python decorators for modifying operate conduct. We are going to clarify these ideas in additional element as we stroll by way of this sensible instance.

    Step 1. Atmosphere Setup

    • Bundle managers setup: MCP makes use of uv because the default bundle supervisor. For macOS and Linux system, set up uv and execute it utilizing sh with the shell command:
    • Provoke a brand new working listing /visible, activate the digital surroundings, create the challenge construction to retailer the principle script visible.py:
    # Create a brand new listing for our challenge
    uv init visible
    cd visible
    
    # Create digital surroundings and activate it
    uv venv
    supply .venv/bin/activate
    
    # Set up dependencies
    uv add "mcp[cli]" httpx
    
    # Create our server file
    contact visible.py
    • Set up required dependencies: pip set up mcp httpx fastapi uvicorn

    Additional Studying:

    The official weblog put up from Anthropic “For Server Developers – Model Context Protocol” gives easy-to-follow information for establishing the MCP server growth surroundings.

    Step 2: Fundamental Server Setup

    Within the visible.py script, import the required libraries and provoke our MCP server occasion and outline a consumer agent for making HTTP requests. We are going to use FastMCP because the official Python MCP SDK.

    from typing import Any
    import httpx
    from mcp.server.fastmcp import FastMCP
    
    # Initialize FastMCP server
    mcp = FastMCP("visual_code_server")

    Step 3: Create Helper Features

    We’ll create a helper operate get_code() to fetch code from the GitHub URL.

    async def get_code(url: str) -> str:
        """
        Fetch supply code from a GitHub URL.
        
        Args:
            url: GitHub URL of the code file
        Returns:
            str: Supply code content material or error message
        """
        USER_AGENT = "visual-fastmcp/0.1"
    
        headers = {
            "Consumer-Agent": USER_AGENT,
            "Settle for": "textual content/html"
        }
        
        async with httpx.AsyncClient() as consumer:
            strive:
                # Convert GitHub URL to uncooked content material URL
                raw_url = url.substitute("github.com", "uncooked.githubusercontent.com")
                            .substitute("/blob/", "/")
                response = await consumer.get(raw_url, headers=headers, timeout=30.0)
                response.raise_for_status()
                return response.textual content
            besides Exception as e:
                return f"Error fetching code: {str(e)}"

    Let’s break down the get_code() operate into a couple of elements.

    Asynchronous Implementation

    Asynchronous programming permits a number of operations to run concurrently, bettering effectivity by not blocking execution whereas ready for operations to finish. It’s usually used to deal with I/O operations effectively, similar to community request, consumer inputs and API calls. In distinction, synchronous operations, usually used for machine studying duties, are executed sequentially, with every operation blocking till completion earlier than shifting to the subsequent activity. The next adjustments are made to outline this operate asynchronously:

    • The operate is said with async def to permit dealing with a number of operations concurrently.
    • Use async with context supervisor and httpx.AsyncClient() for non-blocking HTTP requests.
    • Deal with asynchronous HTTP requests by including await key phrase to consumer.get().

    URL Processing

    Configure Settle for header for HTML content material and set applicable Consumer-Agent to establish the consumer making the HTTP requests, i.e. visual-fastmcp/0.1 . Convert common GitHub URLs to uncooked file format.

    Error Dealing with

    Catch HTTP-specific exceptions (httpx.RequestError, httpx.HTTPStatusError) and catch different generic exception dealing with as fallback, then return descriptive error messages for debugging.

    Additional Studying:

    Step 4: Implement the MCP Server Device

    Utilizing a couple of further strains of code, we are able to now create our primary MCP server instrument visualize_code().

    @mcp.instrument()
    async def visualize_code(url: str) -> str:
        """
        Visualize the code extracted from a Github repository URL within the format of SVG code.
    
        Args:
            url: The GitHub repository URL
        
        Returns:
            SVG code that visualizes the code construction or hierarchy.
        """
    
        code = await get_code(url)
        if "error" in code.decrease():
            return code
        else:
            return "n---n".be part of(code)
        return "n".be part of(visualization)

    Decorator

    A Python Decorator is a particular operate that modifies or enhances the conduct of one other operate or methodology with out altering its authentic code. FastMCP gives decorators that wrap round customized features to combine them into the MCP server. For instance, we use @mcp.instrument() to create an MCP server instrument by adorning the visualize_code operate. Equally, we are able to use @mcp.useful resource() for assets and @mcp.immediate() for prompts.

    Kind Trace and Docstring

    The FastMCP class leverages Python kind hints and docstrings to robotically enhancing instrument definitions, simplifying the creation and upkeep of MCP instruments. For our use case, we create instrument features with kind hints visualize_code(url: str) -> str, accepting enter parameter url with string format and producing the output as a mixed string of all code extracted from the supply file. Then, add the docstring beneath to assist the LLM to grasp instrument utilization.

        """
        Visualize the code extracted from a Github repository URL within the format of SVG code.
    
        Args:
            url: The GitHub repository URL
        
        Returns:
            SVG code that visualizes the code construction or hierarchy.
        """

    Let’s examine how the MCP instrument features with and with out docstring supplied, by calling the MCP server by way of the Claude Desktop.

    Mannequin output with out docstring – solely textual content abstract is generated

    Mannequin output with docstring supplied – each textual content abstract and diagram are generated

    Additional studying:

    Step 5: Configure the MCP Server

    Add the principle execution block because the final step within the visible.py script. Run the server regionally with easy I/O transport utilizing “stdio”. When operating the code in your native machine, the MCP server is positioned in your native machine and listening for instrument requests from MCP purchasers. For manufacturing deployment, you possibly can configure totally different transport choices like “streamable-http” for web-based deployments.

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

    Step 6. Use the MCP Server from Claude Desktop

    We are going to exhibit the best way to use this MCP server by way of Claude Desktop, nonetheless, please notice that it permits connecting the server to totally different hosts (e.g. Cursor) by barely tweaking the configuration. Try “For Claude Desktop Users – Model Context Protocol” for Claude’s official information.

    1. Obtain the Claude Desktop
    2. Arrange config file for server settings in your native folder ~/Library/Utility Assist/Claude/claude_desktop_config.json (for MacOS) and replace to your personal working folder path.
    {
        "mcpServers": {
            "visible": {
                "command": "uv",
                "args": [
                    "--directory",
                    "/visual",
                    "run",
                    "visual.py"
                ]
            }
        }
    }
    1. Run it utilizing command line uv --directory /visible run visible.py
    2. Launch (or restart) Claude Desktop and choose the “Search and instruments” then “visible”. You need to have the ability to toggle on the visualize_code instrument we simply created.
    1. Attempt the visualization instrument by offering a GitHub URL, for instance:

    Take-Dwelling Message

    This text gives an outline of MCP structure (MCP consumer, host and server), with the first concentrate on MCP server elements and purposes. It guides by way of the method of constructing a customized MCP server that permits code-to-diagram from GitHub repositories.

    Important steps for constructing a customized MCP server:

    1. Atmosphere Setup
    2. Fundamental Server Setup
    3. Create Helper Features
    4. Implemente the MCP Device
    5. Configure the MCP Server
    6. Use the MCP Server from Claude Desktop

    If you’re considering additional exploration, potential instructions embody exploring distant MCP servers on cloud supplier, implementing safety features and sturdy error dealing with.

    Extra Contents Like This



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Editor Times Featured
    • Website

    Related Posts

    Escaping the Valley of Choice in BI

    June 2, 2026

    Ensuring Data Integrity with Cryptographic Hashing and the Ethereum Blockchain

    June 1, 2026

    RAG Is Not Machine Learning, and the ML Toolkit Solves the Wrong Problem

    June 1, 2026

    How to Combine Claude Code and Codex for Maximum Coding Power

    June 1, 2026

    It’s the Lessons We Learned Along the Way. Or, Is It?

    June 1, 2026

    Proxy-Pointer RAG: Eliminating Wasteful Entity & Relations Extraction in Knowledge Graphs

    May 31, 2026

    Comments are closed.

    Editors Picks

    Rehumanizing global health care with agentic AI

    June 2, 2026

    Robots-Blog | Praxisprojekt mit fischertechnik an der Hochschule Hof in Bayern

    June 2, 2026

    Ancient giant octopuses were apex predators, study finds

    June 2, 2026

    Barcelona’s Zazume raises €2.5 million to scale its AI-powered rental management platform

    June 2, 2026
    Categories
    • Founders
    • Startups
    • Technology
    • Profiles
    • Entrepreneurs
    • Leaders
    • Students
    • VC Funds
    About Us
    About Us

    Welcome to Times Featured, an AI-driven entrepreneurship growth engine that is transforming the future of work, bridging the digital divide and encouraging younger community inclusion in the 4th Industrial Revolution, and nurturing new market leaders.

    Empowering the growth of profiles, leaders, entrepreneurs businesses, and startups on international landscape.

    Asia-Middle East-Europe-North America-Australia-Africa

    Facebook LinkedIn WhatsApp
    Featured Picks

    Achieve Your Goals in 2026 With These 5 Expert Tips

    January 7, 2026

    Doctors Explain Why Your Smartwatch Is Giving You Anxiety, and How to Stop It

    May 17, 2026

    BetMGM updates integrity policy to specifically prohibit athlete harassment

    February 3, 2026
    Categories
    • Founders
    • Startups
    • Technology
    • Profiles
    • Entrepreneurs
    • Leaders
    • Students
    • VC Funds
    Copyright © 2024 Timesfeatured.com IP Limited. All Rights.
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us

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