Skip to main content

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 with generate_text and stream_text.

Installation

MCP support requires the mcp package:

Transports

MCP supports multiple transports for connecting to servers:

Local MCP Server (stdio)

Use mcp() 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. Use npx to run them:

Environment Variables

Pass environment variables to the subprocess:

Remote MCP Server (SSE)

Use mcp_sse() for remote servers using the legacy SSE transport:

With Authentication

Remote MCP Server (Streamable HTTP)

Use mcp_http() for remote servers using the recommended Streamable HTTP transport (MCP spec 2025-11-25):

With Authentication

Combining Tool Sources

Use merge_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:
Available functions:
  • connect_mcp() - stdio transport
  • connect_mcp_sse() - SSE transport
  • connect_mcp_http() - Streamable HTTP transport

MCPServer Object

When you connect to an MCP server, you get an MCPServer object:

Creating an MCP Server

Here’s a simple example of creating an MCP server in Python:
Then use it with ai-query:

Error Handling

Best Practices

  1. Use context managers - They ensure proper cleanup of connections
  2. Reuse connections - For multiple requests, keep the connection open
  3. Handle errors - MCP servers can fail or timeout
  4. Check available tools - Print server.tools.keys() to see what’s available
  5. Use merge_tools - Combine multiple sources cleanly