or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

auth.mdcli.mdclient.mdfastmcp-server.mdindex.mdlowlevel-server.mdtransport.mdtypes.md
tile.json

tessl/pypi-mcp

Model Context Protocol SDK for building MCP servers and clients in Python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mcp@1.13.x

To install, run

npx @tessl/cli install tessl/pypi-mcp@1.13.0

index.mddocs/

MCP Python SDK

A comprehensive Python SDK for the Model Context Protocol (MCP), an open-source standard for connecting AI applications to external systems. The SDK enables developers to build both MCP servers that expose resources, tools, and prompts to AI systems, and MCP clients that can interact with these servers.

Package Information

  • Package Name: mcp
  • Language: Python
  • Installation: pip install mcp

Core Imports

import mcp

For client operations:

from mcp import ClientSession, ClientSessionGroup, stdio_client, StdioServerParameters

For server operations:

from mcp.server import FastMCP, Server

For type definitions:

from mcp import (
    Tool, Resource, Prompt, 
    CallToolRequest, GetPromptRequest, ReadResourceRequest,
    McpError
)

Basic Usage

Client Example

import asyncio
from mcp import ClientSession, stdio_client, StdioServerParameters

async def client_example():
    # Connect to an MCP server
    server_params = StdioServerParameters(command="my-mcp-server")
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the session
            await session.initialize()
            
            # List available tools
            tools = await session.list_tools()
            print(f"Available tools: {[tool.name for tool in tools.tools]}")
            
            # Call a tool
            result = await session.call_tool("example_tool", {"param": "value"})
            print(f"Tool result: {result}")
            
            # List and read resources
            resources = await session.list_resources()
            if resources.resources:
                content = await session.read_resource(resources.resources[0].uri)
                print(f"Resource content: {content}")

asyncio.run(client_example())

Server Example (FastMCP)

from mcp.server import FastMCP
import asyncio

# Create server instance
app = FastMCP("example-server")

@app.tool()
async def calculate_sum(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@app.resource("config://settings")
async def get_settings() -> str:
    """Get application settings."""
    return "setting1=value1\nsetting2=value2"

@app.prompt()
async def greeting_prompt(name: str) -> str:
    """Generate a personalized greeting."""
    return f"Hello, {name}! How can I help you today?"

# Run the server
if __name__ == "__main__":
    app.run_stdio()

Architecture

The MCP Python SDK is organized around several key components:

Transport Layer

  • stdio: Standard input/output transport for local process communication
  • HTTP/SSE: Server-Sent Events over HTTP for web-based connections
  • WebSocket: Real-time bidirectional communication
  • HTTP Streaming: Streaming HTTP connections for efficient data transfer

Session Management

  • ClientSession: Manages individual client connections to servers
  • ClientSessionGroup: Coordinates multiple concurrent server connections
  • ServerSession: Handles server-side client connections

Protocol Implementation

  • Request/Response: Structured communication using JSON-RPC 2.0
  • Notifications: One-way messages for events and updates
  • Capabilities: Negotiated feature sets between clients and servers
  • Authentication: OAuth 2.0 and bearer token support

High-Level Frameworks

  • FastMCP: Modern, decorator-based server framework for rapid development
  • Low-level Server: Full control server implementation for advanced use cases

Capabilities

Client Operations

Core client functionality for connecting to and interacting with MCP servers, including session management, tool calling, resource access, and prompt handling.

class ClientSession:
    async def initialize(self) -> InitializeResult: ...
    async def list_tools(self, cursor: str | None = None) -> ListToolsResult: ...
    async def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult: ...
    async def list_resources(self, cursor: str | None = None) -> ListResourcesResult: ...
    async def read_resource(self, uri: AnyUrl) -> ReadResourceResult: ...
    async def list_prompts(self, cursor: str | None = None) -> ListPromptsResult: ...
    async def get_prompt(self, name: str, arguments: dict[str, str] | None = None) -> GetPromptResult: ...

class ClientSessionGroup:
    async def connect_to_server(self, server_params: ServerParameters) -> ClientSession: ...  
    async def call_tool(self, name: str, args: dict[str, Any]) -> CallToolResult: ...
    @property
    def tools(self) -> dict[str, Tool]: ...
    @property 
    def resources(self) -> dict[str, Resource]: ...

Client Operations

FastMCP Server Framework

High-level server framework using decorators for rapid MCP server development, with built-in support for tools, resources, prompts, and HTTP endpoints.

class FastMCP:
    def __init__(self, name: str, **kwargs): ...
    def tool(self) -> Callable: ...
    def resource(self, uri: str) -> Callable: ...
    def prompt(self) -> Callable: ...
    def get(self, path: str) -> Callable: ...
    def post(self, path: str) -> Callable: ...
    def run_stdio(self) -> None: ...
    async def run_sse(self, host: str = "127.0.0.1", port: int = 8000) -> None: ...

class Context:
    @property
    def request_id(self) -> str: ...
    @property
    def client_session(self) -> ServerSession: ...

FastMCP Server

Low-Level Server Framework

Low-level server implementation providing full control over MCP protocol handling with decorator-based request handlers and custom lifecycle management.

class Server:
    def __init__(self, name: str, version: str | None = None, **kwargs): ...
    def list_tools(self) -> Callable: ...
    def call_tool(self) -> Callable: ...  
    def list_resources(self) -> Callable: ...
    def read_resource(self) -> Callable: ...
    def list_prompts(self) -> Callable: ...
    def get_prompt(self) -> Callable: ...
    async def run(self, read_stream, write_stream, options: InitializationOptions) -> None: ...

class NotificationOptions:
    def __init__(self, tools_changed: bool = True, resources_changed: bool = True, **kwargs): ...

Low-Level Server

Transport Mechanisms

Transport layer implementations for various connection types including stdio, HTTP, WebSocket, and streaming protocols with authentication and security features.

def stdio_client(server: StdioServerParameters) -> AsyncContextManager: ...
def stdio_server() -> AsyncContextManager: ...

class StdioServerParameters:
    def __init__(self, command: str | list[str], **kwargs): ...

def websocket_client(url: str, **kwargs) -> AsyncContextManager: ...
def sse_client(url: str, **kwargs) -> AsyncContextManager: ...
def streamablehttp_client(url: str, **kwargs) -> AsyncContextManager: ...

Transport Mechanisms

Authentication and Security

OAuth 2.0 authentication, bearer token verification, transport security settings, and middleware for protecting MCP server endpoints.

class AuthSettings:
    def __init__(
        self,
        client_id: str,
        client_secret: str,
        authorization_endpoint: str,
        token_endpoint: str,
        **kwargs
    ): ...

class TokenVerifier:
    async def verify_token(self, token: str) -> dict[str, Any]: ...

class TransportSecuritySettings:
    def __init__(self, dns_rebinding_protection: bool = True, **kwargs): ...

Authentication & Security

Type System and Protocol Types

Complete MCP protocol type definitions including requests, responses, notifications, capabilities, and data models for tools, resources, and prompts.

# Core Protocol Types
class InitializeRequest(BaseModel): ...
class InitializeResult(BaseModel): ...  
class Tool(BaseModel): ...
class Resource(BaseModel): ...
class Prompt(BaseModel): ...

# Content Types
class TextContent(BaseModel): ...
class ImageContent(BaseModel): ...
class EmbeddedResource(BaseModel): ...

# Capabilities
class ClientCapabilities(BaseModel): ...
class ServerCapabilities(BaseModel): ...

# Exceptions
class McpError(Exception): ...

Types and Protocol

CLI Tools

Command-line interface for MCP development, testing, and debugging with tools for server inspection and protocol validation.

# Available via CLI
mcp --help
mcp server inspect <server-command>
mcp client connect <server-params>

CLI Tools