What is MCP?
The Model Context Protocol (MCP) is an open standard that enables AI models to securely access external data sources and tools. MCP servers provide a standardized way to expose tools, resources, and prompts that models can interact with.Using MCP Servers as Tools
You can pass an MCP session directly as a tool in your generate content requests. The SDK will automatically handle function calling with the MCP server.Basic Example
Here’s a complete example using a weather MCP server:How It Works
- Create server parameters: Define the MCP server command, arguments, and optional environment variables
- Establish connection: Use
stdio_clientto connect to the MCP server - Initialize session: Create a
ClientSessionand initialize the connection - Pass session as tool: Add the session to the
toolslist in yourGenerateContentConfig - Automatic function calling: The SDK automatically calls the MCP server’s tools using the automatic function calling feature
Server Parameters
When creatingStdioServerParameters, you can specify:
command: The executable to run (e.g., “npx”, “python”, “node”)args: Arguments to pass to the executable (e.g., [“-y”, “@philschmid/weather-mcp”])env: Optional dictionary of environment variables for the server process
Available MCP Servers
You can use any MCP-compatible server, including:- Weather MCP:
@philschmid/weather-mcp- Get weather information - File System MCP: Access local file systems
- Database MCP: Query databases
- API MCP: Interact with REST APIs
- Custom MCP servers: Build your own using the MCP protocol
Requirements
MCP support requires async/await and the
mcp Python package:Limitations
- MCP support is currently experimental and may change in future releases
- Only async operations are supported (use
client.aio.models.generate_content) - The MCP session must be initialized before being used as a tool
- Automatic function calling is required for MCP sessions
Best Practices
- Always initialize: Call
await session.initialize()before using the session as a tool - Use context managers: Properly manage connections with
async withstatements - Handle errors: Wrap MCP operations in try-except blocks for better error handling
- Set temperature: Use lower temperatures (0-0.5) for more deterministic tool usage