MCP Python SDK

1.26.0 · active · verified Sun Mar 01

Official Python SDK for the Model Context Protocol (MCP), maintained by Anthropic. Used to build MCP servers (exposing tools, resources, prompts to LLMs) and MCP clients. Two important ecosystem distinctions: (1) mcp package bundles FastMCP 1.0 via mcp.server.fastmcp; (2) standalone 'fastmcp' package on PyPI is a separate, more feature-rich framework that diverged from the bundled version. v2 of the mcp package is in pre-alpha on main branch — v1.x is stable.

Warnings

Install

Imports

Quickstart

Two server modes: stdio for local/Claude Desktop integration, streamable-http for production remote deployments. FastMCP derives tool schemas from Python type hints and docstrings automatically.

# Server (stdio transport — for Claude Desktop, local agents)
from mcp.server.fastmcp import FastMCP

mcp = FastMCP('My Server')

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@mcp.resource('data://{name}')
def get_data(name: str) -> str:
    """Fetch named data"""
    return f'Data for {name}'

@mcp.prompt()
def review_code(code: str) -> str:
    return f'Please review this code:\n\n{code}'

if __name__ == '__main__':
    mcp.run()  # defaults to stdio

# ---

# Server (streamable-http — for remote/production deployments)
mcp = FastMCP('My Server', stateless_http=True, json_response=True)

if __name__ == '__main__':
    mcp.run(transport='streamable-http')  # serves at /mcp by default

# ---

# Client (connecting to an MCP server)
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
import asyncio

async def main():
    async with streamablehttp_client('http://localhost:8000/mcp') as (r, w, _):
        async with ClientSession(r, w) as session:
            await session.initialize()
            tools = await session.list_tools()
            result = await session.call_tool('add', {'a': 1, 'b': 2})
            print(result)

asyncio.run(main())

view raw JSON →