MCP Connector

Connect to MCP Servers and Access Tools

LlamaIndex package that connects agents to MCP servers as tools, with a full MCP client, OAuth support and a workflow-to-MCP helper.

Works with openai

78
Spark score
out of 100
Updated 4 days ago
Source checked Sep 19, 2026
Version 0.14.24

Add to Favorites

Why it matters

Integrate your AI agent with MCP Servers to leverage their tools and resources. This asset enables seamless communication, allowing agents to call remote functions and access data.

Outcomes

What it gets done

01

Connect to MCP servers via HTTP, SSE, or stdio.

02

List and call tools exposed by MCP servers.

03

Access and read resources managed by MCP servers.

04

Convert LlamaIndex Workflows into MCP applications.

Source

Get it from source

Spark does not host a copy of it.

Open source

Reports

Agent outcome reports

No reports yet

Capabilities

Tools your agent gets

list_tools

List available tools from an MCP server.

call_tool

Call a tool on an MCP server with specified parameters.

list_resources

List available resources from an MCP server.

read_resource

Read a resource from an MCP server and get its content.

list_prompts

List available prompts from an MCP server.

get_prompt

Get a prompt from an MCP server with optional parameters.

Overview

MCP ToolSpec

A LlamaIndex integration that connects agents to MCP servers and turns their tools into LlamaIndex tools. It also provides an MCP client with OAuth and a helper that exposes workflows as MCP apps. Use it when a LlamaIndex agent needs tools from an MCP server, or when you want to serve a LlamaIndex workflow over MCP. It is a client library and needs an MCP server.

What it does

MCP ToolSpec is a LlamaIndex integration that connects to MCP servers and lets an agent call the tools those servers provide. The idea is migrated from a post on integrating MCP tools into LlamaIndex. Usage is described as connecting to an MCP server and getting its tools: you create a BasicMCPClient pointing at the server (the example uses an SSE endpoint at 127.0.0.1:8000), wrap it in McpToolSpec, and call to_tool_list for a synchronous list or to_tool_list_async for an async one.

McpToolSpec has two optional settings. allowed_tools filters the tools by name, and include_resources adds MCP resources to the tool list. The resulting tools plug straight into a LlamaIndex FunctionAgent, for example one backed by an OpenAI model with a system prompt, which can then be run with a question such as the weather in Tokyo.

The package also includes helper functions. workflow_as_mcp converts a LlamaIndex Workflow into an MCP app: you define events and steps, create the workflow and call workflow_as_mcp with a start event model, then launch it with mcp dev when the mcp[cli] extra is installed. get_tools_from_mcp_url and its async variant aget_tools_from_mcp_url return a list of FunctionTools from an MCP server URL or command.

When to use - and when NOT to

Use it when you want a LlamaIndex agent to call tools that live on an MCP server, when you need to expose a LlamaIndex Workflow as an MCP server, or when you need a full MCP client with tools, resources and prompts. The package states it is designed as a way to call the tools provided by MCP servers.

It is a Python client library, not an MCP server of its own, so you need an MCP server to connect to.

Inputs and outputs

The inputs are the URL or command of an MCP server and optional filters. Outputs are LlamaIndex tools for an agent, or an MCP app built from a workflow. Install it with:

pip install llama-index-tools-mcp

BasicMCPClient gives broader access to MCP capabilities than just tools. It connects over three transports: Streamable HTTP with an https URL, Server-Sent Events, and local stdio by launching a command such as python with a server.py argument. It can list and call tools, list and read resources, and list and get prompts, for example calling a calculate tool with x and y arguments or fetching a greet prompt with a name.

Integrations

The client supports OAuth 2.0 for protected MCP servers through BasicMCPClient.with_oauth, which takes a client name, redirect URIs, a redirect handler that shows the authorization URL and a callback handler that supplies the authorization code. In-memory token storage is the simple option, and for production you can implement a custom TokenStorage, such as one that stores OAuth tokens in a file. The client can also use a custom httpx.AsyncClient, available only for the Streamable HTTP transport. A Jupyter notebook with a more extensive example is linked from the package README.

It integrates with the LlamaIndex agent workflow (FunctionAgent), LlamaIndex workflows and the mcp Python package.

Who it's for

It is for Python developers building LlamaIndex agents who want to reuse the growing ecosystem of MCP servers, and for teams that want to publish a LlamaIndex workflow as an MCP service.

Source README

MCP ToolSpec

This tool connects to MCP Servers and allows an Agent to call the tools provided by MCP Servers.

This idea is migrated from Integrate MCP Tools into LlamaIndex.

Installation

pip install llama-index-tools-mcp

Usage

Usage is as simple as connecting to an MCP Server and getting the tools.

from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

# We consider there is a mcp server running on 127.0.0.1:8000, or you can use the mcp client to connect to your own mcp server.
mcp_client = BasicMCPClient("http://127.0.0.1:8000/sse")
mcp_tool_spec = McpToolSpec(
    client=mcp_client,
    # Optional: Filter the tools by name
    # allowed_tools=["tool1", "tool2"],
    # Optional: Include resources in the tool list
    # include_resources=True,
)

# sync
tools = mcp_tool_spec.to_tool_list()

# async
tools = await mcp_tool_spec.to_tool_list_async()

Then you can use the tools in your agent!

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI

agent = FunctionAgent(
    name="Agent",
    description="Some description",
    llm=OpenAI(model="gpt-4o"),
    tools=tools,
    system_prompt="You are a helpful assistant.",
)

resp = await agent.run("What is the weather in Tokyo?")

Helper Functions

This package also includes several helper functions for working with MCP Servers.

workflow_as_mcp

This function converts a Workflow to an MCP app.

from llama_index.core.workflow import (
    Context,
    Workflow,
    Event,
    StartEvent,
    StopEvent,
    step,
)
from llama_index.tools.mcp import workflow_as_mcp


class RunEvent(StartEvent):
    msg: str


class InfoEvent(Event):
    msg: str


class LoudWorkflow(Workflow):
    """Useful for converting strings to uppercase and making them louder."""

    @step
    def step_one(self, ctx: Context, ev: RunEvent) -> StopEvent:
        ctx.write_event_to_stream(InfoEvent(msg="Hello, world!"))

        return StopEvent(result=ev.msg.upper() + "!")


workflow = LoudWorkflow()

mcp = workflow_as_mcp(workflow, start_event_model=RunEvent)

Then, you can launch the MCP server (assuming you have the mcp[cli] extra installed):

mcp dev script.py

get_tools_from_mcp_url / aget_tools_from_mcp_url

This function get a list of FunctionTools from an MCP server or command.

from llama_index.tools.mcp import (
    get_tools_from_mcp_url,
    aget_tools_from_mcp_url,
)

tools = get_tools_from_mcp_url("http://127.0.0.1:8000/sse")

# async
tools = await get_tools_from_mcp_url("http://127.0.0.1:8000/sse")

MCP Client Usage

The BasicMCPClient provides comprehensive access to MCP server capabilities beyond just tools.

Basic Client Operations

from llama_index.tools.mcp import BasicMCPClient

# Connect to an MCP server using different transports
http_client = BasicMCPClient("https://example.com/mcp")  # Streamable HTTP
sse_client = BasicMCPClient("https://example.com/sse")  # Server-Sent Events
local_client = BasicMCPClient("python", args=["server.py"])  # stdio

# List available tools
tools = await http_client.list_tools()

# Call a tool
result = await http_client.call_tool("calculate", {"x": 5, "y": 10})

# List available resources
resources = await http_client.list_resources()

# Read a resource
content, mime_type = await http_client.read_resource("config://app")

# List available prompts
prompts = await http_client.list_prompts()

# Get a prompt
prompt_result = await http_client.get_prompt("greet", {"name": "World"})

OAuth Authentication

The client supports OAuth 2.0 authentication for connecting to protected MCP servers:

from llama_index.tools.mcp import BasicMCPClient

# Simple authentication with in-memory token storage
client = BasicMCPClient.with_oauth(
    "https://api.example.com/mcp",
    client_name="My App",
    redirect_uris=["http://localhost:3000/callback"],
    # Function to handle the redirect URL (e.g., open a browser)
    redirect_handler=lambda url: print(f"Please visit: {url}"),
    # Function to get the authorization code from the user
    callback_handler=lambda: (input("Enter the code: "), None),
)

# Use the authenticated client
tools = await client.list_tools()

For production use, you can implement a custom token storage:

from llama_index.tools.mcp import BasicMCPClient
from mcp.client.auth import TokenStorage
from mcp.shared.auth import OAuthToken, OAuthClientInformationFull
import json
import os


class FileTokenStorage(TokenStorage):
    """Store OAuth tokens in a file."""

    def __init__(self, file_path: str):
        self.file_path = file_path
        self._client_info: Optional[OAuthClientInformationFull] = None

    async def get_tokens(self):
        if not os.path.exists(self.file_path):
            return None
        with open(self.file_path, "r") as f:
            data = json.load(f)
            return OAuthToken(**data.get("tokens", {}))

    async def set_tokens(self, tokens):
        data = {}
        if os.path.exists(self.file_path):
            with open(self.file_path, "r") as f:
                data = json.load(f)
        data["tokens"] = tokens.__dict__
        with open(self.file_path, "w") as f:
            json.dump(data, f)

    async def get_client_info(self) -> Optional[OAuthClientInformationFull]:
        """Get the stored client information."""
        return self._client_info

    async def set_client_info(
        self, client_info: OAuthClientInformationFull
    ) -> None:
        """Store client information."""
        self._client_info = client_info


# Use custom storage
client = BasicMCPClient.with_oauth(
    "https://api.example.com/mcp",
    client_name="My App",
    redirect_uris=["http://localhost:3000/callback"],
    redirect_handler=lambda url: print(f"Please visit: {url}"),
    callback_handler=lambda: (input("Enter the code: "), None),
    token_storage=FileTokenStorage("tokens.json"),
)

Use a custom HTTP Client

The MCP Client can use a custom httpx.AsyncClient instance.
This feature is only available for Streamable HTTP transport.

httpx_async_client = AsyncClient(
    # to avoid self-signed certificates failures
    verify=false
)

client = BasicMCPClient(
    url="https://example.com/mcp", http_client=httpx_async_client
)
client_with_oauth = BasicMCPClient.with_oauth(
    "https://api.example.com/mcp",
    client_name="My App",
    redirect_uris=["http://localhost:3000/callback"],
    # Function to handle the redirect URL (e.g., open a browser)
    redirect_handler=lambda url: print(f"Please visit: {url}"),
    # Function to get the authorization code from the user
    callback_handler=lambda: (input("Enter the code: "), None),
    http_client=httpx_async_client,
)

Notebook Example

This tool has a more extensive example usage documented in a Jupyter notebook here.

This tool is designed to be used as a way to call the tools provided by MCP Servers.

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.