diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ebe438..0f75fe5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ce85d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +.pytest_cache/ +.venv/ +*.py[cod] +.env* diff --git a/README.md b/README.md index 9b13aac..b4b522d 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/client.py b/client.py new file mode 100644 index 0000000..5286161 --- /dev/null +++ b/client.py @@ -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()) + diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..875646a --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,5 @@ +-r requirements.txt +pytest==9.1.1 +ruff==0.16.5 +mypy==2.3.1 +pip-audit==2.10.1 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6839686 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +mcp==2.1.1 diff --git a/server.py b/server.py index 0fd05a8..c8e2b49 100644 --- a/server.py +++ b/server.py @@ -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() + diff --git a/test_server.py b/test_server.py new file mode 100644 index 0000000..301bb84 --- /dev/null +++ b/test_server.py @@ -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." +