How to use MCP with Claude API
Quick answer
Use the
mcp Python SDK to create an MCP server that connects to the Claude API by running a stdio_server with your Anthropic client. This enables AI agents to interact with external tools via the MCP protocol seamlessly.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20 mcp>=0.1
Setup
Install the required packages and set your environment variable for the Anthropic API key.
- Install packages:
pip install anthropic mcp - Set environment variable:
export ANTHROPIC_API_KEY='your_api_key'on Linux/macOS orsetx ANTHROPIC_API_KEY "your_api_key"on Windows.
pip install anthropic mcp Step by step
This example shows how to create an MCP stdio server that uses the Claude API to handle AI agent requests. The server reads from standard input/output and connects to the claude-3-5-sonnet-20241022 model.
import os
from anthropic import Anthropic
from mcp.server.stdio import stdio_server
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# Define a handler function that sends messages to Claude via Anthropic SDK
async def handler(messages, system):
response = await client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=system,
messages=messages
)
return response.content[0].text
# Run the MCP stdio server with the handler
if __name__ == "__main__":
stdio_server(handler) Common variations
You can customize the MCP integration by:
- Using different Claude models like
claude-sonnet-4-5for improved coding or reasoning. - Running the MCP server asynchronously in an event loop if integrating into larger async applications.
- Connecting MCP to other transport layers besides stdio, such as SSE or WebSocket, depending on your deployment.
import asyncio
async def async_handler(messages, system):
response = await client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system=system,
messages=messages
)
return response.content[0].text
async def main():
await stdio_server(async_handler)
if __name__ == "__main__":
asyncio.run(main()) Troubleshooting
If you see connection errors or timeouts, verify your ANTHROPIC_API_KEY is set correctly and has permissions. For JSON decode errors, ensure the MCP messages conform to the protocol. Use logging to debug message flow between MCP and Claude.
Key Takeaways
- Use the official
mcpPython SDK to run an MCP server with Claude API integration. - The
stdio_serverfunction enables easy local testing and deployment of MCP agents. - Customize the handler to use different Claude models or async patterns as needed.
- Always secure your
ANTHROPIC_API_KEYin environment variables for production. - Check MCP protocol compliance and logs to troubleshoot communication issues.