Integrate MCP tools into LlamaIndex
[!NOTE] This work has been contributed to upstream llama_index as
McpToolSpecin thellama-index-tools-mcppackage. You can find the pull request llama_index#17795 feat: add mcp tool spec and try out the example notebook llama-index-tools-mcp/examples/mcp.ipynb directly.
This article mainly introduces how to convert MCP (Model Context Protocol) tools into LlamaIndex tools that can be directly used, allowing LlamaIndex users to seamlessly integrate these services like other modern and popular AI applications like Claude and Cursor, etc.
1. Background
1.1 What is MCP?
MCP(Model Context Protocol, https://modelcontextprotocol.io) is a protocol for building services that interact with AI applications. It allows developers to build servers that expose features like data (resources), functions (tools), and prompts. For example, we can define a fetch_ipinfo tool that retrieves detailed information about a specified IP address (such as city and timezone). code here: mcp_server.py
"""Get the detailed information of a specified IP address
Args:
ip(str or None): The IP address to get information for. Follow the format like 192.168.1.1 .
**kwargs: Additional keyword arguments to pass to the IPInfo handler.
Returns:
IPDetails: The detailed information of the specified IP address.
"""
=
=
return
1.2 What is LlamaIndex?
LlamaIndex (https://github.com/run-llama/llama_index) is a framework for building, managing, and calling index systems. It aims to bring external information into large language models in a structured way, achieving more efficient information retrieval, question answering, and dialogue generation. When using LlamaIndex, you often need to call external tools to get dynamic data, which can be considered as converting MCP tools into LlamaIndex tools.
2. Why do we need to convert MCP tools to LlamaIndex tools?
In actual scenarios, you may want to:
- Use the rich features exposed by the MCP servers, there is a list of MCP servers https://github.com/AlexMili/Awesome-MCP .
- Integrate MCP tools into LlamaIndex to form a unified workflow, simplifying the process of calling external APIs with large language models.
- Automatically convert MCP tools to FunctionTool objects in LlamaIndex, making it easier for LlamaIndex Agent to automatically call and manage tools.
By doing this, you can easily reuse the tools already in MCP, without having to write code again, and also use the powerful dialogue generation and context management capabilities of LlamaIndex.
3. Implementation
Implementing the conversion of MCP tools to LlamaIndex tools mainly includes the following steps:
- Communicate with MCP server:
- Establish a connection with the MCP server using the
MCPClientclass, at least supportlist_toolsandcall_toolmethods. - See mcp_client.py for reference.
- Establish a connection with the MCP server using the
- Construct adapter:
- Define the
MCPToolAdapterclass, which uses the MCPClient'slist_toolsmethod to get the tool list and uses theFunctionTool.from_defaultsmethod in LlamaIndex to wrap each MCP tool into a LlamaIndex tool. - See llamaindex_mcp_adapter.py for reference.
- Define the
- Use the adapter in LlamaIndex:
- In LlamaIndex, use the adapter to get tools, and then use the agent to call the tools.
- See llamaindex_mcp_example.py for reference.
4. Code Example
4.1 MCPToolAdapter
The following code is from llamaindex_mcp_adapter.py, which shows how to convert MCP tools to LlamaIndex tools:
: =
=
=
=
=
=
= ...
= None
=
=
=
return
=
= await
return
return await
return
Explanation:
-
JSON Schema to Pydantic model:
- The function
create_model_from_json_schemabuilds a dynamic Pydantic model based on the JSON Schema defined in the MCP tool, making it easier to validate tool parameters and provide auto-completion.
- The function
-
Adapter's list_tools method:
- This method fetches the tool list from the server using
MCPClient, then wraps each tool withFunctionTool.from_defaults, and finally obtains a list of tools that can be used by the LlamaIndex Agent.
- This method fetches the tool list from the server using
-
Dynamic call MCP tool:
- The helper method
_create_tool_fnreturns an asynchronous function, which internally callsself.client.call_toolto implement the actual tool calling logic.
- The helper method
Why we need to convert MCP tool's input parameters to Pydantic model?
MCP tool defines the input parameters in JSON Schema format (
inputSchemainToolobject, which isDict[str, Any]), and thecreate_model_from_json_schemafunction converts it to a Pydantic model, which is used as thefn_schemaof theFunctionToolin LlamaIndex.
4.2 Usage in LlamaIndex
The following code is from llamaindex_mcp_example.py, which shows how to use the MCPToolAdapter with LlamaIndex:
=
= await
=
=
return
=
= await
=
=
=
=
=
= await
await
await
Explanation:
- Get MCP tools:
- Use
MCPToolAdapterto get MCP tools and convert them to LlamaIndex tools.
- Use
- Create Agent:
- Use
ReActAgent.from_toolsto build an Agent, which embeds Azure OpenAI's LLM.
- Use
- Process user messages:
- The user's message is analyzed by the Agent, triggering the corresponding MCP tool (e.g., calling
fetch_ipinfo).
- The user's message is analyzed by the Agent, triggering the corresponding MCP tool (e.g., calling
This approach seamlessly converts MCP tools to LlamaIndex tools, greatly reducing integration complexity.
5. Running the Demo
You can run the demo with the following command:
The demo will start a MCP server using stdio mode, and then use the MCPToolAdapter to get MCP tools and convert them to LlamaIndex tools. Also, it will use the AzureOpenAI to call the tools and generate responses.
The demo also provides a sse mode, you can run the demo with the following command:
The following is the output of the demo, with the stdio mode:
> Running
6. Summary
This article details how to convert MCP tools to LlamaIndex tools. By:
- Interacting with MCP servers using
MCPClient; - Automatically converting tool parameter definitions (using JSON Schema to convert to Pydantic models) through
MCPToolAdapter; - Integrating converted tools into LlamaIndex
ReActAgentand calling them;
Now you can seamlessly integrate MCP tools into LlamaIndex, reducing development costs and providing great flexibility for AI application expansion.
Welcome to explore the combination of MCP and LlamaIndex, and further expand more practical tools and functions!
See the demo for more details.