API Reference

Complete API documentation for MCP development.

Reference
1
Server Class

The main Server class provides the foundation for building MCP servers. It handles tool registration, request routing, and response formatting.

from mcp import Server

class MyServer(Server):
    def __init__(self):
        super().__init__()
        # Register tool handlers
        self.register_tool_handler("tool_name", self.tool_handler)
    
    async def list_tools(self, request: ListToolsRequest) -> ListToolsResult:
        """Return list of available tools"""
        return ListToolsResult(tools=[...])
    
    async def tool_handler(self, request: CallToolRequest) -> CallToolResult:
        """Handle tool calls"""
        return CallToolResult(content=[...])
2
Request Types

MCP defines several request types for different operations. Each request type has specific fields and validation rules.

from mcp.types import (
    CallToolRequest,
    ListToolsRequest,
    GetPromptsRequest,
    GetPromptVariablesRequest,
    ListResourcesRequest,
    ReadResourceRequest,
    GetResourceRequest,
    ListActionsRequest,
    CallActionRequest
)

# Tool-related requests
call_request = CallToolRequest(
    name="tool_name",
    arguments={"key": "value"}
)

list_tools_request = ListToolsRequest()

# Resource-related requests
list_resources_request = ListResourcesRequest(
    uri="file:///path/to/resource"
)

read_resource_request = ReadResourceRequest(
    uri="file:///path/to/resource"
)
3
Response Types

Response types define the structure of data returned by MCP servers. Each response type corresponds to a specific request type.

from mcp.types import (
    CallToolResult,
    ListToolsResult,
    GetPromptsResult,
    GetPromptVariablesResult,
    ListResourcesResult,
    ReadResourceResult,
    GetResourceResult,
    ListActionsResult,
    CallActionResult
)

# Tool responses
tool_result = CallToolResult(
    content=[
        {
            "type": "text",
            "text": "Tool response content"
        }
    ],
    isError=False
)

tools_list = ListToolsResult(
    tools=[
        Tool(
            name="tool_name",
            description="Tool description",
            inputSchema={
                "type": "object",
                "properties": {
                    "input": {"type": "string"}
                }
            }
        )
    ]
)
4
Transport Layer

The transport layer handles communication between MCP clients and servers. MCP supports multiple transport protocols.

from mcp import StdioServerTransport, StdioClientTransport

# Server transport
transport = StdioServerTransport()
async def run_server():
    server = MyServer()
    await transport.run(server)

# Client transport
client_transport = StdioClientTransport()
async def run_client():
    async with ClientSession(client_transport) as session:
        tools = await session.list_tools()
        result = await session.call_tool("tool_name", {"arg": "value"})

# HTTP transport (if supported)
from mcp import HTTPServerTransport
http_transport = HTTPServerTransport(port=8000)
5
Error Handling

Proper error handling is essential for robust MCP servers. Use structured error responses and appropriate error codes.

from mcp.types import CallToolResult

async def handle_tool_call(self, request: CallToolRequest) -> CallToolResult:
    try:
        # Validate input
        if not request.arguments.get("required_field"):
            return CallToolResult(
                content=[{
                    "type": "text",
                    "text": "Error: Missing required field"
                }],
                isError=True
            )
        
        # Process request
        result = await self.process_request(request.arguments)
        
        return CallToolResult(
            content=[{
                "type": "text",
                "text": f"Success: {result}"
            }]
        )
    
    except ValueError as e:
        return CallToolResult(
            content=[{
                "type": "text",
                "text": f"Validation error: {str(e)}"
            }],
            isError=True
        )
    
    except Exception as e:
        return CallToolResult(
            content=[{
                "type": "text",
                "text": "Internal server error"
            }],
            isError=True
        )
6
Configuration

MCP servers can be configured through various methods including environment variables, configuration files, and command-line arguments.

import os
import json
from dataclasses import dataclass

@dataclass
class ServerConfig:
    host: str = "localhost"
    port: int = 8000
    debug: bool = False
    api_keys: list = None
    
    @classmethod
    def from_env(cls):
        return cls(
            host=os.getenv("MCP_HOST", "localhost"),
            port=int(os.getenv("MCP_PORT", "8000")),
            debug=os.getenv("MCP_DEBUG", "false").lower() == "true",
            api_keys=os.getenv("MCP_API_KEYS", "").split(",") if os.getenv("MCP_API_KEYS") else []
        )
    
    @classmethod
    def from_file(cls, filepath: str):
        with open(filepath, 'r') as f:
            config_data = json.load(f)
        return cls(**config_data)

# Usage
config = ServerConfig.from_env()
# or
config = ServerConfig.from_file("config.json")
API Sections
Related Docs

Server Development Guide

Building MCP servers

Best Practices

Development best practices