From 0b34ba67a8f220078bef5d158696565b8f755a16 Mon Sep 17 00:00:00 2001 From: "Zero (Rajesh Bhanushali)" Date: Thu, 3 Sep 2026 19:56:57 +0530 Subject: [PATCH 1/4] Implement the official MCP Python SDK quickstart --- .github/workflows/ci.yml | 30 +++++++---------- .gitignore | 5 +++ README.md | 15 ++++++--- client.py | 18 +++++++++++ requirements-dev.txt | 5 +++ requirements.txt | 1 + server.py | 70 ++++++---------------------------------- test_server.py | 8 +++++ 8 files changed, 69 insertions(+), 83 deletions(-) create mode 100644 .gitignore create mode 100644 client.py create mode 100644 requirements-dev.txt create mode 100644 requirements.txt create mode 100644 test_server.py 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..21245fb --- /dev/null +++ b/client.py @@ -0,0 +1,18 @@ +"""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 + + +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"}) + print(result.content[0].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..b4904f0 100644 --- a/server.py +++ b/server.py @@ -1,65 +1,13 @@ -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.fastmcp import FastMCP -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 = FastMCP("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..4425087 --- /dev/null +++ b/test_server.py @@ -0,0 +1,8 @@ +import pytest + +pytest.importorskip("mcp") +from server import hello_world + + +def test_hello_world(): + assert hello_world("Ada") == "Hello, Ada! This is running via MCP." From 69e66f5099d92cc30895a1b7fb3656be029545eb Mon Sep 17 00:00:00 2001 From: "Zero (Rajesh Bhanushali)" Date: Thu, 3 Sep 2026 20:02:32 +0530 Subject: [PATCH 2/4] Fix SDK type-check compatibility --- client.py | 7 ++++++- server.py | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/client.py b/client.py index 21245fb..5286161 100644 --- a/client.py +++ b/client.py @@ -6,6 +6,7 @@ from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client +from mcp.types import TextContent async def main() -> None: @@ -13,6 +14,10 @@ async def main() -> None: 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"}) - print(result.content[0].text) + 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/server.py b/server.py index b4904f0..016e361 100644 --- a/server.py +++ b/server.py @@ -1,5 +1,5 @@ """A minimal protocol-correct MCP server using the official Python SDK.""" -from mcp.server.fastmcp import FastMCP +from mcp.server.fastmcp import FastMCP # type: ignore[attr-defined] mcp = FastMCP("QuickstartMCP") @@ -11,3 +11,4 @@ def hello_world(name: str = "World") -> str: if __name__ == "__main__": # FastMCP uses stdio by default. stdout is reserved for protocol messages. mcp.run() + From afbf35da1f9c105aae0a29474146769ada3bfd19 Mon Sep 17 00:00:00 2001 From: "Zero (Rajesh Bhanushali)" Date: Thu, 3 Sep 2026 20:06:24 +0530 Subject: [PATCH 3/4] Use MCPServer API for SDK v2 --- server.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/server.py b/server.py index 016e361..2f9e99f 100644 --- a/server.py +++ b/server.py @@ -1,7 +1,12 @@ """A minimal protocol-correct MCP server using the official Python SDK.""" -from mcp.server.fastmcp import FastMCP # type: ignore[attr-defined] +try: + from mcp.server import MCPServer +except ImportError: # compatibility with the older locally installed SDK only + from mcp.server.fastmcp import ( + FastMCP as MCPServer, # type: ignore[attr-defined,no-redef] + ) -mcp = FastMCP("QuickstartMCP") +mcp = MCPServer("QuickstartMCP") @mcp.tool() def hello_world(name: str = "World") -> str: From 04509bdf77386f15b38afdb2a2a6ccbb82f4315b Mon Sep 17 00:00:00 2001 From: "Zero (Rajesh Bhanushali)" Date: Thu, 3 Sep 2026 20:09:47 +0530 Subject: [PATCH 4/4] Target the documented MCP SDK v2 server --- server.py | 7 +------ test_server.py | 6 +++++- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/server.py b/server.py index 2f9e99f..c8e2b49 100644 --- a/server.py +++ b/server.py @@ -1,10 +1,5 @@ """A minimal protocol-correct MCP server using the official Python SDK.""" -try: - from mcp.server import MCPServer -except ImportError: # compatibility with the older locally installed SDK only - from mcp.server.fastmcp import ( - FastMCP as MCPServer, # type: ignore[attr-defined,no-redef] - ) +from mcp.server import MCPServer mcp = MCPServer("QuickstartMCP") diff --git a/test_server.py b/test_server.py index 4425087..301bb84 100644 --- a/test_server.py +++ b/test_server.py @@ -1,8 +1,12 @@ import pytest -pytest.importorskip("mcp") +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." +