Machine Learning

Motocol Protocol Study (MCP) Lesson: Create your first MCP server in 6 steps

Gotortetche Protopol (MCP)?

As a result of the appearance of the Agents AI and RAG requests in recent years, there is a growing need for customizing large languages ​​(llms) by including foreign resources (eg .th-based systems). This improves existing skills of llms' by installing external information and empowering services to come.

The Model GroteCol Protocol (MCP) is first introduced in November 2024 with anthropic, growing in popularity as it provides in a compatible and unchanging way to connect each API charges. MCP is a well-made organization, allowed for an open source that gives a fixed interface that allows the llm to participate with various foreign tools and resources, so allow the last users to the MCP integrated server. Compared with Agentic System Avestic System patterns, the MCP provides several important benefits:

  • Increase the rating and stability of the program by using normal integration.
  • Reduced double development effort because the implementation of one MCP server applies to multiple MCP customers.
  • Avoid closing Vendor by providing flexibility to change between the LLM suppliers, since the llm is no longer a strong integration of the Agentic program.
  • Prompt the most advanced process by enabling immediate creation of practical products.

The objective article guide you through the basic of the model's context and the essential construction of the MCP server. We will use these concepts with an effective example of building a MCP server that allows the llms to skip and visualize GitHub codes by simply giving the URL as an example below.

User Input:

MCP lists:


Understanding parts of MCP

MCP Building

MCP Building

The MCP allows customerization-server when the client is a device or app requesting services provided by the medium server. Practical rehabilitation of customer service is customer and restaurant. The customer is acting as a customer's side, sending requests by order from the menu, while the restaurant is like server, providing services such as containers and seats. The restaurant is with sufficient resources to serve many customers in a short period of time, while customers need to be concerned only by receiving their orders.

The MCP structure contains three elements: The MCP server, MCP client and MCP Host. The MCP server It provides tools and resources, disclosing AI models that can benefit from using organized applications. The MCP host It provides a place of time running communications between customers and servers, such as Claude Desktop or Ints have adverbs supported by MCP. If we continue the Restaurant Restaurants above, MCP keeper may be considered to be a play management program that guides between customers (clients) and restaurants, processing payment and payment. The MCP Client Often designed in the hosting app that allows users to work with server using the interface. However, there is a flexibility to improve the custom MCP clients to use special cases and requirements, such as easy AI application using complete ending.

MCP server components

In this article, we will focus on the understanding of the MCP server and use our information to build simple, MCP for simple MCP. The MCP server is a variety of Apis calls on external tools and resources, making customers up to this connection without worrying about the net setup. The MCP server supports three types of components associated with three ordinary llm strategies.

  • Resources It is data, files and documents that apply as the basis for external information to enhance existing LLM information. This is especially useful in the RAG program.
  • Tools It is the functions and integration of other enriching programs llm's Action Space, for example, do Google search, create Figma prototype etc.
  • Motivation Pre-defined images of the OLM exit, is an answer in a technological or common tone. This is useful in the beneficiary system from instant engineering strategies.

If you are interested in knowing more about LLM strategies, check my previous article and video on “6 Normalized LLM strategies described briefly”.

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


Create your MCP server in 6 steps

We will use a simple example to show how to create your first MCP server using Python, which enables calling culture visualize_code Turning tool for the Raw Code issued in GitTub Repositories into visual paintings such as the following example.

For people privacy for the scientific secret to create the MCP servers, there are several ideas for unusual software but important to treat asynchronous activities, as well as Python decorates, as well as Python decorates by changing behavior. We will explain these concepts with more details as we are walking in this practical example.

Step 1. Environmental Search

  • Package Manager Setup: MCP uses uv as an automated package manager. For the Macos program and Linux, enter uv and use it using sh by a shell command:
  • Start a new performance guide /visualActivate visible nature, create project structure to keep the main text 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
  • Enter the Required Required: pip install mcp httpx fastapi uvicorn

To learn more:

The blog Official Port from anthropic “server Developers – The Model Development Status” provides a simple guide to set up the MCP server's development environment.

Step 2: Basic Server Setup

In visual.py Script, import the required libraries and start our MCP example and describe the HTTP application agent. We will use FastMCP as Python MCP Official SDK.

from typing import Any
import httpx
from mcp.server.fastmcp import FastMCP

# Initialize FastMCP server
mcp = FastMCP("visual_code_server")

Step 3: Create assistance activities

We will build a relief work get_code() Downloading 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 postpone us get_code() work on a few buildings.

Asynchronous implementation

ASYNCHRONOS SERVICES AVAILABLE WORKS TO WORK AND INFORMATION, improve poor performance of being done while waiting for jobs to finish. Usually it is used to treat the operation of I / O effectively, such as network application, API users and telephones. In contrast, harmonious tasks, often used for machine learning activities, is being done in a row, with a restricted workout until the next work. The following changes are made to describe this asynchronously function:

  • Activity is announced with async def allowing to treat many tasks at the same time.
  • Work async with Princior Manager and httpx.AsyncClient() with unrestricted requests of http.
  • Manage Asynchronous HTTP requests by adding await The keyword in the client.get().

URL processing

Configure Header in HTML content and set up the appropriate user agent to identify the HTTP applications, ie visual-fastmcp/0.1 . Convert the standard GitHub URLs into the green file format.

Error to Manage

Different catch of http (httpx.RequestError, httpx.HTTPStatusError) And holding some common normality as collapse, and return the default default error messages.

To learn more:

Step 4: Use MCP SEVA Tool

Using the extra few lines of the code, we can now create our main MCP 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)

Lonter

Python decoration is the special work that transforms or improves work in another activity or method without turning its original code. FASTMCP provides the decorators that congratulate custom activities to integrate them to the MCP server. For example, we use @mcp.tool() To create a MCP server tool by decorating the visualize_code work. Similarly, we can use @mcp.resource() services and @mcp.prompt() with desires.

Type Suggestions and DocSring

FASTMCP Class for Fastmcp Python Type Pynts and DocStrings to automatically develop definitions of tools, to facilitate the creation and maintenance of MCP. To find our case for use, we create toolback activities with the kind of strategies visualize_code(url: str) -> strTo accept the installation parameter url In the string format and produce the result as a combined string of the entire code issued from the source file. Then, add lower docstring to help the llm understand the use of tools.

    """
    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 us compare how the MCP tool works and without a given Doctring device, by calling the MCP server with a Claude Desktop.

Model release without Doctring – A summary of the text only

Model release with a given Doctring – both text abbreviations and drawing produced

To learn more:

Step 5: Prepare the MCP server

Add the main murder block as the last step in visual.py Script. Run the server in your area with I / O Transport using the “Stdio”. If you use the code on your local machine, the MCP server is available on your local machine and listening to tool applications from MCP customers. By sending a product, you can edit different travel options such as “HTTP” options on the Sub Sub.

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

Step 6. Use the MCP server from Claude Desktop

We will show how we can use this MCP server with a Claude Desktop, anyway, Please note that it allows for the server to different armies. See “Claude Desktop Users – Protocol Montlect Protocol” for the official Claude Guide.

  1. Download Claude Desktop
  2. Set the server settings file to your local folder ~/Library/Application\ Support/Claude/claude_desktop_config.json (with Macos) and update in your method of active folder.
{
    "mcpServers": {
        "visual": {
            "command": "uv",
            "args": [
                "--directory",
                "/visual",
                "run",
                "visual.py"
            ]
        }
    }
}
  1. Run using command line uv --directory /visual run visual.py
  2. Start (or restart) Claude Desktop and select “Search and Tools” and then “viewed”. You should be able to convert to visualize_code The tool just created.
  1. Try a view tool by giving a GitHub URL, for example:

The That-Home message

This document provides a review of the MCP building (MCP client, copper and server), with basic focus on the components of the MCP server and applications. It oversees the process of building a customer for the customer empowering code-to-diagram from GitHub repositories.

Important steps to build a custom MCP server:

  1. Ecosystem
  2. Proper server setup
  3. Create Help Activities
  4. Verify MCP tool
  5. Prepare the MCP server
  6. Use the MCP server from Claude Desktop

If you are interested in re-evaluated, potential directions include checking MCP servers from the cloud supplier, using safety features and handling strong error.

More content like this

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

Source link

Related Articles

Leave a Reply

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

Back to top button