MCP integration for LlamaIndex using llama-index-tools-mcp.
This module provides MCP server connection management for LlamaIndex agents.
Unlike CrewAI which uses a context manager, LlamaIndex uses async calls to
fetch tools from MCP servers.
mcp_tools_context
async
mcp_tools_context(mcp_config: MCPConfig) -> AsyncGenerator[list[BaseTool], None]
Asynchronously load MCP tools for LlamaIndex.
Parameters:
| Name |
Type |
Description |
Default |
mcp_config
|
MCPConfig
|
MCP configuration including server connection parameters
|
required
|
Returns
List of MCP tools, or empty list if no MCP configuration is present.
Source code in datarobot_genai/llama_index/mcp.py
| @asynccontextmanager
async def mcp_tools_context(
mcp_config: MCPConfig,
) -> AsyncGenerator[list[BaseTool], None]:
"""
Asynchronously load MCP tools for LlamaIndex.
Args:
mcp_config: MCP configuration including server connection parameters
Returns
-------
List of MCP tools, or empty list if no MCP configuration is present.
"""
server_params = mcp_config.server_config
if not server_params:
logger.info("No MCP server configured, using empty tools list")
yield []
return
url = server_params["url"]
headers = server_params.get("headers", {})
logger.info("Connecting to MCP server: %s", url)
try:
# Create BasicMCPClient with headers to pass authentication
client = BasicMCPClient(command_or_url=url, headers=headers)
tools = await aget_tools_from_mcp_url(
command_or_url=url,
client=client,
)
# Ensure list
tools = list(tools) if tools is not None else []
logger.info("Successfully connected to MCP server, got %d tools", len(tools))
except (ConnectionError, OSError, TimeoutError, ExceptionGroup) as exc:
logger.warning(
"Failed to connect to MCP server at %s: %s. Continuing without MCP tools.",
url,
exc,
)
yield []
return
yield tools
|