How to use MCP with Claude Code
Quick answer
Use the
mcp Python SDK to create an MCP server that connects with Claude Code. Implement the server with mcp.server.stdio.stdio_server to handle communication, enabling Claude to interact with external tools and resources via the MCP protocol.PREREQUISITES
Python 3.8+Claude API key (set as environment variable)pip install mcp anthropic>=0.20
Setup
Install the mcp SDK and anthropic client to interact with Claude Code and implement the MCP protocol. Set your Claude API key as an environment variable for secure authentication.
pip install mcp anthropic>=0.20 Step by step
This example shows how to create a simple MCP server using stdio_server that integrates with Claude Code. The server listens for MCP requests and responds accordingly, enabling Claude to use external tools or resources.
import os
from anthropic import Anthropic
from mcp.server.stdio import stdio_server
from mcp.server import Server
# Initialize the Anthropic client with your Claude API key
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# Define a simple MCP server class
class ClaudeMCPServer(Server):
def __init__(self):
super().__init__()
async def handle_request(self, request):
# Example: Echo back the request content
response = {
"result": f"Received: {request.get('input', '')}"
}
return response
# Run the MCP stdio server with the ClaudeMCPServer instance
if __name__ == "__main__":
server = ClaudeMCPServer()
stdio_server(server) Common variations
You can customize the MCP server to handle different types of requests or integrate with other APIs. For asynchronous usage, ensure your handle_request method is async. You can also switch to other Claude models by changing the Anthropic client initialization.
import asyncio
# Example async handler variation
class AsyncClaudeMCPServer(Server):
async def handle_request(self, request):
# Simulate async processing
await asyncio.sleep(0.1)
return {"result": f"Async received: {request.get('input', '')}"}
# Usage remains the same with stdio_server Troubleshooting
- If the server does not start, verify your environment variable
ANTHROPIC_API_KEYis set correctly. - If requests time out, check that your
handle_requestmethod returns a valid JSON-serializable dictionary. - For permission errors, ensure your Python environment has access to standard input/output streams.
Key Takeaways
- Use the official
mcpPython SDK to implement MCP servers for Claude Code integration. - Run MCP servers with
stdio_serverfor simple, local communication over standard IO. - Customize
handle_requestto connect Claude with external tools or APIs asynchronously. - Always secure your Claude API key in environment variables and never hardcode it.
- Troubleshoot by verifying environment setup and ensuring proper JSON responses in MCP handlers.