DEV Community

AIRabbit
AIRabbit

Posted on

What is an MCP Server? The Complete Guide to the "USB-C for AI"

If you've tried connecting Claude or ChatGPT to your local files, database, or internal tools, you’ve likely hit a wall. You either have to paste context manually (which is tedious) or build fragile, custom API integrations (which is hard to maintain).

Enter the Model Context Protocol (MCP).

MCP is a new open standard that acts as a "universal driver" for AI. Instead of building a custom integration for every AI model, you build one MCP Server, and any MCP-compliant AI (like Claude Desktop, Cursor, or IDEs) can instantly use your data and tools.

In this comprehensive guide, we’ll cover:

  1. What an MCP Server is (and how it differs from a REST API).
  2. The 3 Core Components: Resources, Tools, and Prompts.
  3. Real-World Use Cases: Why developers are switching to MCP.
  4. Tutorial: How to build a "System Monitor" MCP Server in Python in 5 minutes.

What is an MCP Server?

An MCP Server is a lightweight application that standardizes how data and tools are exposed to AI models.

Think of it like a USB-C port for Artificial Intelligence.

  • The Host: The AI application (e.g., Claude Desktop, Cursor, VS Code).
  • The Protocol: MCP (Model Context Protocol).
  • The Server: Your custom adapter (e.g., "PostgreSQL MCP Server", "Google Drive MCP Server").

Before MCP, if you wanted Claude to query your database, you had to wait for Anthropic to build a "Database Plugin." Now, you can just run a local MCP Server, and Claude can query your database immediately—without sending your credentials to the cloud.

Architecture: Host vs. Client vs. Server

It’s important to distinguish the roles:

  • MCP Host: The app the human interacts with (e.g., Claude Desktop).
  • MCP Client: The internal connector within the Host that speaks the protocol.
  • MCP Server: The standalone process (running on your machine or remotely) that actually has the data.

The 3 Pillars of an MCP Server

An MCP Server isn't just a data pipe; it exposes three distinct capabilities to the AI:

1. Resources (Passive Context)

Resources are like files. They provide data that the AI can read to understand the current state.

  • Example: A log file, a database schema, or the current price of Bitcoin.
  • Protocol: system://logs/error.txt
  • Use Case: "Read the error log to see why the build failed."

2. Tools (Active Capabilities)

Tools are functions the AI can execute. They take inputs and return outputs, often changing the state of the system.

  • Example: execute_sql_query(query), send_slack_message(channel, text).
  • Safety: Tools often require explicit user approval ("Allow Claude to run this command?").
  • Use Case: "Fix the bug and restart the server."

3. Prompts (Reusable Workflows)

Prompts are pre-written templates that guide the AI on how to use the server.

  • Example: A "Debug Incident" prompt that automatically loads the last 50 log lines (Resource) and asks the AI to analyze them.
  • Use Case: standardized workflows for team members.

MCP Server vs. REST API

Why do we need a new standard? Why not just use OpenAPI/Swagger?

Feature REST API MCP Server
Primary Consumer Human Developers AI Models
Discovery Static Documentation Dynamic Handshake (JSON-RPC)
State Stateless (usually) Context-Aware
Data Format JSON Text/Markdown (Optimized for LLM Context Windows)
Goal CRUD Operations Providing Meaning & Action

The Key Difference: A REST API returns raw data. An MCP Server returns context—data formatted specifically for an LLM to understand and act upon.


Tutorial: Build Your First MCP Server (Python)

Let’s build a System Monitor MCP Server. This server will allow Claude to:

  1. Read your computer's CPU and Memory usage.
  2. List files in any directory you ask for.

Step 1: Installation

You'll need Python 3.10 or higher. Install the official MCP SDK:

pip install mcp
Enter fullscreen mode Exit fullscreen mode

Step 2: The Code (system_server.py)

We will use FastMCP, a high-level API that makes building servers incredibly simple.

from mcp.server.fastmcp import FastMCP
import psutil
import os
import datetime

# 1. Initialize the Server
mcp = FastMCP("My System Monitor")

# --- RESOURCES: Data the AI can read ---
@mcp.resource("system://stats")
def get_system_stats() -> str:
    """Returns real-time CPU and Memory usage statistics."""
    cpu = psutil.cpu_percent(interval=0.1)
    memory = psutil.virtual_memory()

    return f"""
    --- SYSTEM STATS SNAPSHOT ---
    Timestamp: {datetime.datetime.now()}
    CPU Usage: {cpu}%
    Memory Total: {memory.total / (1024**3):.2f} GB
    Memory Used: {memory.used / (1024**3):.2f} GB ({memory.percent}%)
    """

# --- TOOLS: Actions the AI can take ---
@mcp.tool()
def list_directory(path: str) -> str:
    """
    Lists all files and folders in a specific directory path.
    Args:
        path: The absolute path to the directory (e.g., /tmp)
    """
    if not os.path.exists(path):
        return f"Error: Path '{path}' does not exist."

    try:
        items = os.listdir(path)
        # Return a clean list formatted for the AI
        return "\n".join([f"- {item}" for item in items])
    except PermissionError:
        return f"Error: Permission denied for accessing '{path}'."

# --- PROMPTS: Reusable templates ---
@mcp.prompt()
def check_health():
    """Ask the AI to analyze system health."""
    return [
        {
            "role": "user",
            "content": "Please check the 'system://stats' resource and tell me if the system is under heavy load."
        }
    ]

if __name__ == "__main__":
    # This runs the server over Stdio (Standard Input/Output)
    mcp.run()
Enter fullscreen mode Exit fullscreen mode

Step 3: Connect to Claude Desktop

To use this server, you need to tell Claude where it is.

  1. Open or create your Claude config file:

    • Mac: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
  2. Add the configuration:

    {
      "mcpServers": {
        "my-monitor": {
          "command": "python",
          "args": ["/ABSOLUTE/PATH/TO/system_server.py"]
        }
      }
    }
    

    (Note: Replace /ABSOLUTE/PATH/TO/ with the actual path to your file).

  3. Restart Claude Desktop.

Step 4: Test It!

Look for the plug icon 🔌 in the Claude input bar. It should now show "My System Monitor".

Try asking:

"What is my current CPU usage?"
"Please list the files in my Downloads folder."

Claude will automatically call your Python functions, get the data, and answer you naturally!


Security Best Practices

Because MCP servers can execute code and read files, security is critical.

  1. Local First: Run servers locally (localhost) whenever possible. This ensures your data never leaves your network until the AI processes it.
  2. Human Approval: By default, Claude Desktop asks for permission before running any Tool. Do not disable this for sensitive tools like delete_file or execute_sql.
  3. Read-Only Resources: Prefer exposing data as Resources (passive) rather than Tools (active) whenever possible, as Resources are generally safer.

Summary

MCP Servers are the future of AI integration. They replace fragile "glue code" with a standardized protocol that makes your data AI-ready.

  • Resources give the AI eyes (read access).
  • Tools give the AI hands (write access).
  • Prompts give the AI instructions (workflows).

By building a simple MCP server, you turn a generic LLM into a specialized assistant that actually knows your system.

Top comments (0)