| name | mcp-sdk |
| description | Reference for `modelcontextprotocol/python-sdk` version 1.28.1 (v1.x specification). Use when building or interacting with Model Context Protocol (MCP) servers and clients using FastMCP in Python.
|
Model Context Protocol (MCP) Python SDK v1.28.1 (v1.x)
The official Python SDK for building MCP servers and clients using FastMCP. Version 1.28.1 conforms to the v1.x specification, where transport configurations are set in the FastMCP constructor and exceptions inherit from McpError.
Installation
pip install "mcp[cli]>=1.28.1"
Server Implementation (FastMCP)
FastMCP is the high-level framework to build MCP servers quickly. It parses docstrings and type annotations to generate schemas automatically.
1. Basic Server Setup
from typing import Optional
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("WorkShield")
@mcp.tool()
def parse_contract(file_path: str, contract_type: Optional[str] = None) -> dict:
"""
๊ณ์ฝ์ ํ์ผ(HWP/PDF)์ ์กฐํญ ๋จ์๋ก ๋ถํดํ์ฌ ๋ฐํํฉ๋๋ค.
Args:
file_path: ๋ถ์ํ ๊ณ์ฝ์ ํ์ผ์ ์ ๋ ๊ฒฝ๋ก.
contract_type: ๊ณ์ฝ ์ข
๋ฅ ์ปจํ
์คํธ (SW_FREELANCE / SW_EMPLOYMENT).
"""
return {"status": "OK", "clauses": []}
@mcp.resource("contract://template/{name}")
def get_template(name: str) -> str:
"""
ํ์ค ๊ณ์ฝ์ ํ
ํ๋ฆฟ์ ๋ณธ๋ฌธ์ ๊ฐ์ ธ์ต๋๋ค.
"""
return f"Standard contract template content for {name}"
@mcp.prompt()
def review_prompt(contract_text: str) -> str:
"""
๊ณ์ฝ์ ๊ฒํ ๋ฅผ ์์ฒญํ๋ ํ๋กฌํํธ ํ
ํ๋ฆฟ์ ์์ฑํฉ๋๋ค.
"""
return f"๋ค์ ๊ณ์ฝ์์ ๋ถ๋ฆฌํ ์กฐํญ์ ๊ฒํ ํด์ฃผ์ธ์:\n\n{contract_text}"
if __name__ == "__main__":
mcp.run()
2. Transport Configurations (v1.x Specification)
In v1.x, transport-specific options (host, port, sse_path, json_response, etc.) are passed directly to the FastMCP constructor, not to the .run() method.
Stdio Transport (Default)
mcp = FastMCP("Demo")
mcp.run()
SSE (Server-Sent Events) Transport
mcp = FastMCP("Server", host="0.0.0.0", port=9000, sse_path="/events")
mcp.run(transport="sse")
Streamable HTTP Transport
mcp = FastMCP("Demo", json_response=True, stateless_http=True)
mcp.run(transport="streamable-http")
Client Implementation & Exceptions
1. Exception Handling (v1.x McpError)
In v1.x, errors related to MCP communications are raised as McpError (Capitalized as McpError in v1, changed to MCPError in v2).
from mcp.shared.exceptions import McpError
try:
result = await session.call_tool("parse_contract", {"file_path": "a.pdf"})
except McpError as e:
print(f"MCP Call Failed: {e.error.message} (Code: {e.error.code})")
2. Standard Client Setup (Stdio Connection)
import asyncio
import os
from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def run_client():
server_params = StdioServerParameters(
command="python",
args=["src/server/server.py"],
env=os.environ.copy()
)
async with AsyncExitStack() as exit_stack:
stdio_transport = await exit_stack.enter_async_context(stdio_client(server_params))
read_stream, write_stream = stdio_transport
session = await exit_stack.enter_async_context(ClientSession(read_stream, write_stream))
await session.initialize()
response = await session.call_tool("parse_contract", {"file_path": "data/contract.pdf"})
print("Response:", response.content)
if __name__ == "__main__":
asyncio.run(run_client())
Debugging and Testing
1. Using MCP Inspector
You can test the stdio server interactively by calling:
npx @modelcontextprotocol/inspector uv run python src/server/server.py
(Note: Ensure all required environment variables are set in the inspector execution environment if needed.)