Learn how to use SDK and external MCP servers with the Claude Agent SDK
The Claude Agent SDK supports both SDK MCP servers (in-process) and external MCP servers (separate processes). SDK servers run directly within your Python application, providing better performance and simpler deployment.
SDK MCP servers are in-process MCP servers that run directly within your Python application, eliminating the need for separate processes that regular MCP servers require.
Use the @tool decorator to define tools and create_sdk_mcp_server() to bundle them:
from claude_agent_sdk import ( tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient)# Define a tool using the @tool decorator@tool("greet", "Greet a user", {"name": str})async def greet_user(args): return { "content": [ {"type": "text", "text": f"Hello, {args['name']}!"} ] }# Create an SDK MCP serverserver = create_sdk_mcp_server( name="my-tools", version="1.0.0", tools=[greet_user])# Use it with Claudeoptions = ClaudeAgentOptions( mcp_servers={"tools": server}, allowed_tools=["mcp__tools__greet"])async with ClaudeSDKClient(options=options) as client: await client.query("Greet Alice") async for msg in client.receive_response(): print(msg)
MCP tool names follow the pattern mcp__<server_name>__<tool_name>. For example, a tool named greet in a server named tools becomes mcp__tools__greet.
You can check the connection status of your MCP servers:
from claude_agent_sdk import ClaudeSDKClientasync with ClaudeSDKClient(options=options) as client: # Get MCP server status status = await client.get_mcp_status() for server in status["mcpServers"]: print(f"Server: {server['name']}") print(f"Status: {server['status']}") if server['status'] == 'connected': print(f"Server Info: {server.get('serverInfo')}") print(f"Tools: {[tool['name'] for tool in server.get('tools', [])]}") elif server['status'] == 'failed': print(f"Error: {server.get('error')}")
You can load MCP server configurations from a JSON file:
from pathlib import Pathfrom claude_agent_sdk import ClaudeAgentOptions# Point to a configuration fileoptions = ClaudeAgentOptions( mcp_servers="/path/to/mcp-servers.json" # or use Path object # mcp_servers=Path("/path/to/mcp-servers.json"))
The configuration file should follow the standard MCP server configuration format.
SDK servers provide better performance and simpler deployment. Use external servers only when you need to integrate with existing services or languages other than Python.
Handle errors gracefully
Always validate inputs and handle errors in your tool functions. Return is_error: True to indicate failures to Claude.
Use descriptive names and descriptions
Clear tool names and descriptions help Claude understand when and how to use your tools.
Keep tools focused
Each tool should do one thing well. Break complex operations into multiple focused tools.
Use allowed_tools for security
Always specify allowed_tools to control which tools Claude can access, preventing unauthorized tool usage.