Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
name: CI Pipeline

name: CI
on:
push:
branches: [ "main", "master" ]
branches: [main, master]
pull_request:
branches: [ "main", "master" ]

branches: [main, master]
jobs:
build:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v3
with:
python-version: "3.10"
- name: Run linting
run: |
python -m pip install --upgrade pip
pip install flake8
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: python -m pip install -r requirements-dev.txt
- run: ruff check .
- run: mypy server.py client.py
- run: pytest -q
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__pycache__/
.pytest_cache/
.venv/
*.py[cod]
.env*
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
# MCP Quickstart (Python)

A quickstart template for building Model Context Protocol (MCP) servers in Python.
A minimal Model Context Protocol server built with the official Python SDK. It
uses the standard stdio transport and exposes one typed tool.

## Setup
1. Ensure you have Python 3.10+ installed.
2. Install dependencies: `pip install -r requirements.txt` (or equivalent).
3. Run the server locally.
1. Ensure Python 3.10+ is installed.
2. Install dependencies: `python -m pip install -r requirements.txt`.
3. Run `python client.py`; it starts the server over stdio, performs the MCP
handshake, lists the tool and calls `hello_world`.

The server writes protocol traffic to stdout through the SDK. Do not print
diagnostics there; use stderr for diagnostics. This example has no network
service, authentication or persistent state. Run `python -m pip install
-r requirements-dev.txt` for lint, type and test checks.
23 changes: 23 additions & 0 deletions client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Small stdio client for manually exercising server.py."""
from __future__ import annotations

import asyncio
from pathlib import Path

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.types import TextContent


async def main() -> None:
server = StdioServerParameters(command="python", args=[str(Path(__file__).with_name("server.py"))])
async with stdio_client(server) as (read, write), ClientSession(read, write) as session:
await session.initialize()
result = await session.call_tool("hello_world", {"name": "Ada"})
first = result.content[0]
if not isinstance(first, TextContent):
raise TypeError("hello_world returned a non-text MCP content block")
print(first.text)

if __name__ == "__main__": asyncio.run(main())

5 changes: 5 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-r requirements.txt
pytest==9.1.1
ruff==0.16.5
mypy==2.3.1
pip-audit==2.10.1
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mcp==2.1.1
71 changes: 10 additions & 61 deletions server.py
Original file line number Diff line number Diff line change
@@ -1,65 +1,14 @@
import asyncio
import json
import sys
from typing import Dict, Any, Callable
"""A minimal protocol-correct MCP server using the official Python SDK."""
from mcp.server import MCPServer

class MCPServer:
"""A lightweight, zero-dependency MCP (Model Context Protocol) Server Boilerplate."""

def __init__(self, name: str):
self.name = name
self.tools: Dict[str, Callable] = {}
self.running = False
mcp = MCPServer("QuickstartMCP")

def tool(self, name: str, description: str):
"""Decorator to register an MCP tool."""
def decorator(func):
self.tools[name] = {
"func": func,
"description": description,
"name": name
}
return func
return decorator
@mcp.tool()
def hello_world(name: str = "World") -> str:
"""Return a greeting from the quickstart server."""
return f"Hello, {name}! This is running via MCP."

async def _handle_request(self, req: str):
try:
data = json.loads(req)
action = data.get("action")

if action == "list_tools":
return {"tools": [{"name": k, "description": v["description"]} for k, v in self.tools.items()]}

if action == "call_tool":
tool_name = data.get("tool")
kwargs = data.get("args", {})
if tool_name in self.tools:
result = await self.tools[tool_name]["func"](**kwargs)
return {"status": "success", "result": result}
return {"status": "error", "message": f"Tool '{tool_name}' not found."}

except Exception as e:
return {"status": "error", "message": str(e)}

async def serve(self):
"""Starts the stdio JSON-RPC loop."""
self.running = True
print(f"[{self.name}] MCP Server started.", file=sys.stderr)

while self.running:
line = await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)
if not line:
break

response = await self._handle_request(line.strip())
print(json.dumps(response), flush=True)

# === Usage Example ===
if __name__ == "__main__":
app = MCPServer("QuickstartMCP")

@app.tool(name="hello_world", description="Returns a simple greeting.")
async def hello_world(name: str = "World"):
return f"Hello, {name}! This is running via MCP."

asyncio.run(app.serve())
# FastMCP uses stdio by default. stdout is reserved for protocol messages.
mcp.run()

12 changes: 12 additions & 0 deletions test_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import pytest

try:
from mcp.server import MCPServer # noqa: F401
except ImportError:
pytest.skip("local environment has the pre-v2 MCP SDK", allow_module_level=True)
from server import hello_world


def test_hello_world():
assert hello_world("Ada") == "Hello, Ada! This is running via MCP."

Loading