MCP (Model Context Protocol)
ai-query supports MCP - a standard protocol for AI tool integration. Connect to any MCP server and use its tools seamlessly withgenerate_text and stream_text.
Installation
MCP support requires themcp package:
Transports
MCP supports multiple transports for connecting to servers:Local MCP Server (stdio)
Usemcp() to connect to local MCP servers that communicate over stdio:
Using Node.js MCP Servers
Using npx for npm Packages
Many MCP servers are published as npm packages. Usenpx to run them:
Environment Variables
Pass environment variables to the subprocess:Remote MCP Server (SSE)
Usemcp_sse() for remote servers using the legacy SSE transport:
With Authentication
Remote MCP Server (Streamable HTTP)
Usemcp_http() for remote servers using the recommended Streamable HTTP transport (MCP spec 2025-11-25):
With Authentication
Combining Tool Sources
Usemerge_tools() to combine tools from multiple MCP servers or mix with local tools:
Manual Connection Management
For long-lived connections (e.g., in a web server), use the non-context-manager functions:connect_mcp()- stdio transportconnect_mcp_sse()- SSE transportconnect_mcp_http()- Streamable HTTP transport
MCPServer Object
When you connect to an MCP server, you get anMCPServer object:
Creating an MCP Server
Here’s a simple example of creating an MCP server in Python:Error Handling
Best Practices
- Use context managers - They ensure proper cleanup of connections
- Reuse connections - For multiple requests, keep the connection open
- Handle errors - MCP servers can fail or timeout
- Check available tools - Print
server.tools.keys()to see what’s available - Use merge_tools - Combine multiple sources cleanly