Data Science

Model Context Protocol (MCP) Tutorial: Build your first MCP Server in 6 Steps

Context Protocol (MCP)?

Due to the emergence of AI agents and RAG-based applications in recent years, the demand for customized big-word models (LLMs) has been growing through integration with external resources such as rag-based systems and tools such as agent-based systems. This enhances the existing functionality of LLMS by combining external knowledge and enabling autonomous task execution.

The Model Context Protocol (MCP) was first introduced by human anthropomorphism in November 2024, thanks to its offering a more coherent, consistent approach to connecting LLM with external tools and resources, making it a compelling alternative to building custom API integrations for each use case. MCP is a standardized open source protocol that provides a consistent interface that enables LLM to interact with a variety of external tools and resources, thus enabling end users to use encapsulated enhanced MCP servers. Compared with the current proxy system design pattern, MCP provides several key benefits:

  • Improve system scalability and maintainability through standardized integration.
  • Reduce duplicate development efforts because a single MCP server implementation works with multiple MCP clients.
  • By providing flexibility to switch between LLM providers, avoiding vendor lock-in, as LLM is no longer closely integrated with the proxy system.
  • By creating viable products quickly, the development process can be significantly accelerated.

The purpose of this article is to guide you through the basics of model context protocols and the basic components of building an MCP server. We will apply these concepts through a practical example of building an MCP server that allows LLMS to summarize and visualize the GitHub code base by simply providing the following examples.

User input:

MCP output:


Understand MCP components

MCP architecture

MCP architecture

MCP adopts a client-server architecture, where the client is a device or application that requests services provided by a centralized server. A useful analogy to client-server relationships is the relationship between the client and the restaurant. The client acts like a client, ordering from a menu to send requests, while a restaurant is similar to a server, providing services such as tableware and seating. The restaurant has enough resources to serve multiple customers in a short time, and customers just have to worry about receiving orders.

The MCP architecture consists of three components: MCP server, MCP client and MCP host. MCP Server Provide tools and resources to reveal the functions that AI models can utilize through structured requests. MCP Host Provides a runtime environment that manages communication between clients and servers, such as Claude Desktop or an IDE with MCP support extensions. If we continue with the same customer-restaurant analogy above, we can think of the MCP host as a restaurant management system that coordinates communication between the client (customer) and the restaurant, processing order collection and payment processing. MCP Client It is usually built into the host application, allowing users to interact with the server through the interface. However, custom MCP clients can be developed for professional use cases and requirements, such as using simplified, simple AI web applications to support more front-end features.

MCP Server Components

In this article, we will focus on understanding MCP servers and apply our knowledge to build simple custom MCP servers. MCP servers revolve around various APIs to call external tools and resources, allowing customers to access these features without worrying about additional settings. MCP servers support merging three types of components that align with three common LLM custom policies.

  • resource It is data, files and documents that can serve as an external knowledge base that enriches the existing knowledge of LLM. This is especially useful in rag-based systems.
  • tool It is executable functions and integration with other programs to enrich the action space of LLM, such as performing Google searches, creating FIGMA prototypes, etc., which can be utilized in a proxy-based system.
  • hint is a predefined instruction template to guide the output of the LLM, such as responding in a professional or casual tone. This is useful in systems that benefit from rapid engineering techniques.

If you are interested in learning more about LLM custom policies, check out my previous article and video “A Brief Explain 6 Common LLM Custom Strategies”.

https://www.youtube.com/watch?v=jflqodtb1fg


Build your MCP server in 6 steps

We will use a simple example to demonstrate how to build your first MCP server using Python, which can call custom visualize_code A tool for converting original code files extracted from the GITHUB repository to visual charts, as shown in the following example.

For those with a background in data science learning to build MCP servers, there are several software development concepts that may not be familiar with but are important to understand: asynchronous programming for handling asynchronous operations, client/server architecture, and Python Decorator for modifying functional behavior. We will explain these concepts in more detail as we look at this actual example.

Step 1. Environment settings

  • Package Manager Settings: MCP Use uv As the default package manager. For MacOS and Linux systems, please install uv And use sh Use the shell command:
  • Start a new working directory /visualactivate the virtual environment, create the project structure to store the main script visual.py:
# Create a new directory for our project
uv init visual
cd visual

# Create virtual environment and activate it
uv venv
source .venv/bin/activate

# Install dependencies
uv add "mcp[cli]" httpx

# Create our server file
touch visual.py
  • Dependencies required for installation: pip install mcp httpx fastapi uvicorn

Further reading:

The official blog post for anthropomorphic “For Server Developers – Model Context Protocol” provides easy-to-follow guides to set up an MCP server development environment.

Step 2: Basic Server Settings

exist visual.py Scripts, import the required libraries and start our MCP server instance and define the user agent used to make HTTP requests. We will use FastMCP as 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 Assistant Features

We will create an accessibility feature get_code() Get the code from the GitHub URL.

async def get_code(url: str) -> str:
    """
    Fetch source code from a GitHub URL.
    
    Args:
        url: GitHub URL of the code file
    Returns:
        str: Source code content or error message
    """
    USER_AGENT = "visual-fastmcp/0.1"

    headers = {
        "User-Agent": USER_AGENT,
        "Accept": "text/html"
    }
    
    async with httpx.AsyncClient() as client:
        try:
            # Convert GitHub URL to raw content URL
            raw_url = url.replace("github.com", "raw.githubusercontent.com")
                        .replace("/blob/", "/")
            response = await client.get(raw_url, headers=headers, timeout=30.0)
            response.raise_for_status()
            return response.text
        except Exception as e:
            return f"Error fetching code: {str(e)}"

Let’s break it down get_code() Functions are divided into several components.

Asynchronous implementation

Asynchronous programming allows multiple operations to run simultaneously, thereby increasing efficiency without blocking execution while waiting for the operation to complete. It is often used to efficiently handle I/O operations such as network requests, user inputs, and API calls. Instead, synchronous operations commonly used for machine learning tasks are performed sequentially, each blocking until completed and then moving to the next task. The following changes were made to define this feature exceptionally:

  • This function async def Allows multiple operations to be processed simultaneously.
  • use async with Context Manager and httpx.AsyncClient() For non-blocking HTTP requests.
  • Handle asynchronous HTTP requests by adding await Keywords to client.get().

URL processing

Configure the accept header that accepts HTML content and set up the appropriate user agent to identify the client that makes the HTTP request, i.e. visual-fastmcp/0.1 . Convert regular github URLs to original file format.

Error handling

Capture HTTP-specific abnormalities (httpx.RequestError,,,,, httpx.HTTPStatusError) and catch other general exception handling as fallback, then return a descriptive error message for debugging.

Further reading:

Step 4: Implement the MCP Server Tools

Using a few lines of code, we can now create our main MCP server tool visualize_code().

@mcp.tool()
async def visualize_code(url: str) -> str:
    """
    Visualize the code extracted from a Github repository URL in the format of SVG code.

    Args:
        url: The GitHub repository URL
    
    Returns:
        SVG code that visualizes the code structure or hierarchy.
    """

    code = await get_code(url)
    if "error" in code.lower():
        return code
    else:
        return "n---n".join(code)
    return "n".join(visualization)

Decorators

Python decorator is a special feature Modify or enhance the behavior of other functions or methods Its original code has not been changed. FASTMCP provides decorators around custom functions to integrate them into an MCP server. For example, we use @mcp.tool() Create MCP server tool by decorating visualize_code Function. Similarly, we can use @mcp.resource() for resources and @mcp.prompt() hint.

Type prompts and docstring

The FastMCP class uses Python type prompts and DocStrings to automatically enhance tool definitions, thereby simplifying the creation and maintenance of MCP tools. For our use case, we create tool features with type prompts visualize_code(url: str) -> straccept input parameters url Use string format and generate output as a combined string of all code extracted from the source file. Then, add the Docstring below to help LLM understand the tool usage.

    """
    Visualize the code extracted from a Github repository URL in the format of SVG code.

    Args:
        url: The GitHub repository URL
    
    Returns:
        SVG code that visualizes the code structure or hierarchy.
    """

Let’s compare the functionality of the MCP tool when it provides and does not provide DOCSTREN by calling the MCP server via Claude Desktop.

Model output without Docstring – generate only text summary

The provided model output provides the provided docstring – generated text summary and graph

Further reading:

Step 5: Configure the MCP Server

Add the main execution block as the last step visual.py script. Run the server locally with simple I/O transport using “STDIO”. When running the code on the local computer, the MCP server is on the local computer and listens to tool requests from the MCP client. For production deployments, you can configure different transport options such as “Stream HTTP” for web-based deployments.

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

Step 6. MCP server using Claude Desktop

However, we will demonstrate how to use this MCP server through the Claude desktop, however, note that it allows the server to be connected to a different host (e.g. the cursor) with a slightly tweaked configuration. Check out the “Claude Desktop Users – Model Context Protocol” of Claude’s official guide.

  1. Download Claude Desktop
  2. Setting the configuration file for server settings in the local folder ~/Library/Application\ Support/Claude/claude_desktop_config.json (for MacOS) and updates to your own working folder path.
{
    "mcpServers": {
        "visual": {
            "command": "uv",
            "args": [
                "--directory",
                "/visual",
                "run",
                "visual.py"
            ]
        }
    }
}
  1. Run with the command line uv --directory /visual run visual.py
  2. Start (or restart) Claude Desktop, then select Search and Tools, and then select Visual. You should be able to visualize_code The tool we just created.
  1. For example, try the visualization tool by providing a GitHub URL:

Take home news

This article provides an overview of the MCP architecture (MCP client, host, and server), focusing mainly on MCP server components and applications. It guides the process of building a custom MCP server that enables code to numbers from the GitHub repository.

Basic steps to build a custom MCP server:

  1. Environment settings
  2. Basic Server Settings
  3. Create Assistant Function
  4. Implementing MCP Tools
  5. Configure the MCP server
  6. MCP server using Claude Desktop

If you are interested in further exploration, potential directions include exploring remote MCP servers on cloud providers, enabling security features and powerful error handling.

More content like this

https://www.youtube.com/watch?v=jflqodtb1fg

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button