Automationscribe.com
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automation Scribe
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us
No Result
View All Result
Automationscribe.com
No Result
View All Result

Constructing a Easy MCP Server in Python

admin by admin
March 17, 2026
in Artificial Intelligence
0
Constructing a Easy MCP Server in Python
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


On this article, you’ll be taught what Mannequin Context Protocol (MCP) is and how you can construct a easy, sensible task-tracker MCP server in Python utilizing FastMCP.

Subjects we are going to cowl embrace:

  • How MCP works, together with hosts, purchasers, servers, and the three core primitives.
  • Tips on how to implement MCP instruments, assets, and prompts with FastMCP.
  • Tips on how to run and check your MCP server utilizing the FastMCP shopper.

Let’s not waste any extra time.

Building Simple MCP Server Python

Constructing a Easy MCP Server in Python
Picture by Editor

Introduction

Have you ever ever tried connecting a language mannequin to your personal knowledge or instruments? In that case, it typically means writing customized integrations, managing API schemas, and wrestling with authentication. And each new AI software can really feel like rebuilding the identical connection logic from scratch.

Mannequin Context Protocol (MCP) solves this by standardizing how massive language fashions (LLMs) and different AI fashions work together with exterior methods. FastMCP is a framework that makes constructing MCP servers easy.

On this article, you’ll be taught what MCP is, the way it works, and how you can construct a sensible job tracker server utilizing FastMCP. You’ll create instruments to handle duties, assets to view job lists, and prompts to information AI interactions.

You may get the code on GitHub.

Understanding the Mannequin Context Protocol

As talked about, Mannequin Context Protocol (MCP) is an open protocol that defines how AI functions talk with exterior methods.

How MCP Works

MCP has three parts:

Hosts are the AI-powered functions customers really work together with. The host will be Claude Desktop, an IDE with AI options, or a customized app you’ve constructed. The host incorporates (or interfaces with) the language mannequin and initiates connections to MCP servers.

Purchasers hook up with servers. When a bunch wants to speak to an MCP server, it creates a shopper occasion to handle that particular connection. One host can run a number of purchasers concurrently, every linked to a distinct server. The shopper handles all protocol-level communication.

Servers are what you construct. They expose particular capabilities — database entry, file operations, API integrations — and reply to shopper requests by offering instruments, assets, and prompts.

So the person interacts with the host, the host makes use of a shopper to speak to your server, and the server returns structured outcomes again up the chain.

To be taught extra about MCP, learn The Full Information to Mannequin Context Protocol.

The Three Core Primitives

MCP servers expose three varieties of performance:

Instruments are capabilities that carry out actions. They’re like executable instructions the LLM can invoke. add_task, send_an_email, and query_a_database are some examples of instruments.

Sources present read-only entry to knowledge. They permit viewing info with out altering it. Examples embrace lists of duties, configuration recordsdata, and person profiles.

Prompts are templates that information AI interactions. They construction how the mannequin approaches particular duties. Examples embrace “Analyze these duties and counsel priorities” and “Evaluation this code for safety points.”

In observe, you’ll mix these primitives. An AI mannequin may use a useful resource to view duties, then a software to replace one, guided by a immediate that defines the workflow.

Setting Up Your Setting

You’ll want Python 3.10 or later. Set up FastMCP utilizing pip (or uv if you happen to desire):

Let’s get began!

Constructing a Process Tracker Server

We’ll construct a server that manages a easy job checklist. Create a file known as task_server.py and add the imports:

from fastmcp import FastMCP

from datetime import datetime

These give us the FastMCP framework and datetime dealing with for monitoring when duties had been created.

Initializing the Server

Now arrange the server and a easy in-memory storage:

mcp = FastMCP(“TaskTracker”)

 

# Easy in-memory job storage

duties = []

task_id_counter = 1

Right here’s what this does:

  • FastMCP("TaskTracker") creates your MCP server with a descriptive title.
  • duties is an inventory that shops all duties.
  • task_id_counter generates distinctive IDs for every job.

In an actual software, you’d use a database. For this tutorial, we’ll maintain it easy.

Creating Instruments

Instruments are capabilities adorned with @mcp.software(). Let’s create three helpful instruments.

Device 1: Including a New Process

First, let’s create a software that provides duties to our checklist:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@mcp.software()

def add_task(title: str, description: str = “”) -> dict:

    “”“Add a brand new job to the duty checklist.”“”

    world task_id_counter

    

    job = {

        “id”: task_id_counter,

        “title”: title,

        “description”: description,

        “standing”: “pending”,

        “created_at”: datetime.now().isoformat()

    }

    

    duties.append(job)

    task_id_counter += 1

    

    return job

This software does the next:

  • Takes a job title (required) and an elective description.
  • Creates a job dictionary with a singular ID, standing, and timestamp.
  • Provides it to our duties checklist.
  • Returns the created job.

The mannequin can now name add_task("Write documentation", "Replace API docs") and get a structured job object again.

Device 2: Finishing a Process

Subsequent, let’s add a software to mark duties as full:

@mcp.software()

def complete_task(task_id: int) -> dict:

    “”“Mark a job as accomplished.”“”

    for job in duties:

        if job[“id”] == task_id:

            job[“status”] = “accomplished”

            job[“completed_at”] = datetime.now().isoformat()

            return job

    

    return {“error”: f“Process {task_id} not discovered”}

The software searches the duty checklist for an identical ID, updates its standing to “accomplished”, and stamps it with a completion timestamp. It then returns the up to date job or an error message if no match is discovered.

Device 3: Deleting a Process

Lastly, add a software to take away duties:

@mcp.software()

def delete_task(task_id: int) -> dict:

    “”“Delete a job from the checklist.”“”

    for i, job in enumerate(duties):

        if job[“id”] == task_id:

            deleted_task = duties.pop(i)

            return {“success”: True, “deleted”: deleted_task}

    

    return {“success”: False, “error”: f“Process {task_id} not discovered”}

This software searches for a job, removes it from the checklist, and returns affirmation with the deleted job knowledge.

These three instruments give the mannequin create, learn, replace, and delete (CRUD) operations for job administration.

Including Sources

Sources let the AI software view knowledge with out modifying it. Let’s create two assets.

Useful resource 1: Viewing All Duties

This useful resource returns the whole job checklist:

@mcp.useful resource(“duties://all”)

def get_all_tasks() -> str:

    “”“Get all duties as formatted textual content.”“”

    if not duties:

        return “No duties discovered”

    

    end result = “Present Duties:nn”

    for job in duties:

        status_emoji = “✅” if job[“status”] == “accomplished” else “⏳”

        end result += f“{status_emoji} [{task[‘id’]}] {job[‘title’]}n”

        if job[“description”]:

            end result += f”   Description: {job[‘description’]}n”

        end result += f”   Standing: {job[‘status’]}n”

        end result += f”   Created: {job[‘created_at’]}nn”

    

    return end result

Right here’s how this works:

  • The decorator @mcp.useful resource("duties://all") creates a useful resource with a URI-like identifier.
  • The operate codecs all duties into readable textual content with emojis for visible readability.
  • It returns a easy message if no duties exist.

The AI software can learn this useful resource to know the present state of all duties.

Useful resource 2: Viewing Pending Duties Solely

This useful resource filters for incomplete duties:

@mcp.useful resource(“duties://pending”)

def get_pending_tasks() -> str:

    “”“Get solely pending duties.”“”

    pending = [t for t in tasks if t[“status”] == “pending”]

    

    if not pending:

        return “No pending duties!”

    

    end result = “Pending Duties:nn”

    for job in pending:

        end result += f“⏳ [{task[‘id’]}] {job[‘title’]}n”

        if job[“description”]:

            end result += f”   {job[‘description’]}n”

        end result += “n”

    

    return end result

The useful resource filters the duty checklist right down to pending gadgets solely, codecs them for straightforward studying, and returns a message if there’s nothing left to do.

Sources work effectively for knowledge the mannequin must learn continuously with out making modifications.

Defining Prompts

Prompts information how the AI software interacts along with your server. Let’s create a useful immediate:

@mcp.immediate()

def task_summary_prompt() -> str:

    “”“Generate a immediate for summarizing duties.”“”

    return “”“Please analyze the present job checklist and supply:

 

1. Whole variety of duties (accomplished vs pending)

2. Any overdue or high-priority gadgets

3. Advised subsequent actions

4. Total progress evaluation

 

Use the duties://all useful resource to entry the whole job checklist.”“”

This immediate defines a structured template for job evaluation, tells the AI what info to incorporate, and references the useful resource to make use of for knowledge.

Prompts make AI interactions extra constant and helpful. When the AI mannequin makes use of this immediate, it is aware of to fetch job knowledge and analyze it on this particular format.

Working and Testing the Server

Add this code to run your server:

if __name__ == “__main__”:

    mcp.run()

Begin the server out of your terminal:

fastmcp run task_server.py

You’ll see output confirming the server is working. Now the server is able to settle for connections from MCP purchasers.

Testing with the FastMCP Shopper

You may check your server utilizing FastMCP’s built-in shopper. Create a check file known as test_client.py and run it:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

from fastmcp import Shopper

import asyncio

 

async def test_server():

    async with Shopper(“task_server.py”) as shopper:

        # Listing obtainable instruments

        instruments = await shopper.list_tools()

        print(“Accessible instruments:”, [t.name for t in tools.tools])

        

        # Add a job

        end result = await shopper.call_tool(“add_task”, {

            “title”: “Be taught MCP”,

            “description”: “Construct a job tracker with FastMCP”

        })

        print(“nAdded job:”, end result.content material[0].textual content)

        

        # View all duties

        assets = await shopper.list_resources()

        print(“nAvailable assets:”, [r.uri for r in resources.resources])

        

        task_list = await shopper.read_resource(“duties://all”)

        print(“nAll duties:n”, task_list.contents[0].textual content)

 

asyncio.run(test_server())

You’ll see your instruments execute and assets return knowledge. This confirms all the things works accurately.

Subsequent Steps

You’ve constructed a whole MCP server with instruments, assets, and prompts. Right here’s what you are able to do to enhance it:

  • Add persistence by changing in-memory storage with SQLite or PostgreSQL.
  • Add instruments to filter duties by standing, date, or key phrases.
  • Construct prompts for precedence evaluation or job scheduling.
  • Use FastMCP’s built-in auth suppliers for safe entry.

Begin with easy servers like this one. As you develop extra comfy, you’ll end up constructing helpful MCP servers to simplify extra of your work. Joyful studying and constructing!

Tags: BuildingMCPPythonServerSimple
Previous Post

Hallucinations in LLMs Are Not a Bug within the Knowledge

Leave a Reply Cancel reply

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

Popular News

  • Greatest practices for Amazon SageMaker HyperPod activity governance

    Greatest practices for Amazon SageMaker HyperPod activity governance

    405 shares
    Share 162 Tweet 101
  • Unlocking Japanese LLMs with AWS Trainium: Innovators Showcase from the AWS LLM Growth Assist Program

    403 shares
    Share 161 Tweet 101
  • Speed up edge AI improvement with SiMa.ai Edgematic with a seamless AWS integration

    403 shares
    Share 161 Tweet 101
  • Construct a serverless audio summarization resolution with Amazon Bedrock and Whisper

    403 shares
    Share 161 Tweet 101
  • Optimizing Mixtral 8x7B on Amazon SageMaker with AWS Inferentia2

    403 shares
    Share 161 Tweet 101

About Us

Automation Scribe is your go-to site for easy-to-understand Artificial Intelligence (AI) articles. Discover insights on AI tools, AI Scribe, and more. Stay updated with the latest advancements in AI technology. Dive into the world of automation with simplified explanations and informative content. Visit us today!

Category

  • AI Scribe
  • AI Tools
  • Artificial Intelligence

Recent Posts

  • Constructing a Easy MCP Server in Python
  • Hallucinations in LLMs Are Not a Bug within the Knowledge
  • Agentic AI within the Enterprise Half 2: Steerage by Persona
  • Home
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms & Conditions

© 2024 automationscribe.com. All rights reserved.

No Result
View All Result
  • Home
  • AI Scribe
  • AI Tools
  • Artificial Intelligence
  • Contact Us

© 2024 automationscribe.com. All rights reserved.