> ## Documentation Index
> Fetch the complete documentation index at: https://docs-v1.agno.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Model Context Protocol (MCP)

> Learn how to use MCP with Agno to enable your agents to interact with external systems through a standardized interface.

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) enables Agents to interact with external systems through a standardized interface.
You can connect your Agents to any MCP server, using Agno's MCP integration.

## Usage

<Steps>
  <Step title="Find the MCP server you want to use">
    You can use any working MCP server. To see some examples, you can check [this GitHub repository](https://github.com/modelcontextprotocol/servers), by the maintainers of the MCP themselves.
  </Step>

  <Step title="Initialize the MCP integration">
    Intialize the `MCPTools` class and connect to the MCP server. This needs to be done inside an async function.

    The recommended way to define the MCP server, is to use the `command` or `url` parameters. With `command`, you can pass the command used to run the MCP server you want. With `url`, you can pass the URL of the running MCP server you want to use.

    For example, to use the "[mcp-server-git](https://github.com/modelcontextprotocol/servers/tree/main/src/git)" server, you can do the following:

    ```python theme={null}
    from agno.tools.mcp import MCPTools

    async def run_mcp_agent():

        # Initialize the MCP tools
        mcp_tools = MCPTools(command=f"uvx mcp-server-git")

        # Connect to the MCP server
        await mcp_tools.connect()
        ...
    ```
  </Step>

  <Step title="Provide the MCPTools to the Agent">
    When initializing the Agent, pass the `MCPTools` class in the `tools` parameter.

    The agent will now be ready to use the MCP server:

    ```python theme={null}
    from agno.agent import Agent
    from agno.models.openai import OpenAIChat
    from agno.tools.mcp import MCPTools

    async def run_mcp_agent():

        # Initialize the MCP tools
        mcp_tools = MCPTools(command=f"uvx mcp-server-git")

        # Connect to the MCP server
        await mcp_tools.connect()

        # Setup and run the agent
        agent = Agent(model=OpenAIChat(id="gpt-4o"), tools=[mcp_tools])
        await agent.aprint_response("What is the license for this project?", stream=True)
    ```
  </Step>
</Steps>

### Basic example: Filesystem Agent

Here's a filesystem agent that uses the [Filesystem MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem) to explore and analyze files:

```python filesystem_agent.py theme={null}
import asyncio
from pathlib import Path
from textwrap import dedent

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.mcp import MCPTools
from mcp import StdioServerParameters


async def run_mcp_agent(message: str) -> None:
    """Run the filesystem agent with the given message."""

    file_path = str(Path(__file__).parent.parent.parent.parent)

    # Initialize the MCP tools
    mcp_tools = MCPTools(f"npx -y @modelcontextprotocol/server-filesystem {file_path}")

    # Connect to the MCP server
    await mcp_tools.connect()

    # Use the MCP tools with an Agent
    agent = Agent(
        model=OpenAIChat(id="gpt-4o"),
        tools=[mcp_tools],
        instructions=dedent("""\
            You are a filesystem assistant. Help users explore files and directories.

            - Navigate the filesystem to answer questions
            - Use the list_allowed_directories tool to find directories that you can access
            - Provide clear context about files you examine
            - Use headings to organize your responses
            - Be concise and focus on relevant information\
        """),
        markdown=True,
        show_tool_calls=True,
    )

    # Run the agent
    await agent.aprint_response(message, stream=True)

    # Close the MCP connection
    await mcp_tools.close()


# Example usage
if __name__ == "__main__":
    # Basic example - exploring project license
    asyncio.run(run_agent("What is the license for this project?"))
```

## Using MCP in Agno Playground

You can also run MCP servers in the Agno Playground, which provides a web interface for interacting with your agents. Here's an example of a GitHub agent running in the Playground:

```python github_playground.py theme={null}
from contextlib import asynccontextmanager
from os import getenv
from textwrap import dedent

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.playground import Playground
from agno.storage.agent.sqlite import SqliteAgentStorage
from agno.tools.mcp import MCPTools
from fastapi import FastAPI
from mcp import StdioServerParameters

agent_storage_file: str = "tmp/agents.db"


# MCP server parameters setup
github_token = getenv("GITHUB_TOKEN") or getenv("GITHUB_ACCESS_TOKEN")
if not github_token:
    raise ValueError("GITHUB_TOKEN environment variable is required")

server_params = StdioServerParameters(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-github"],
)


# This is required to start the MCP connection correctly in the FastAPI lifecycle
@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage MCP connection lifecycle inside a FastAPI app"""
    global mcp_tools

    # Startuplogic: connect to our MCP server
    mcp_tools = MCPTools(server_params=server_params)
    await mcp_tools.connect()

    # Add the MCP tools to our Agent
    agent.tools = [mcp_tools]

    yield

    # Shutdown: Close MCP connection
    await mcp_tools.close()


agent = Agent(
    name="MCP GitHub Agent",
    instructions=dedent("""\
        You are a GitHub assistant. Help users explore repositories and their activity.

        - Use headings to organize your responses
        - Be concise and focus on relevant information\
    """),
    model=OpenAIChat(id="gpt-4o"),
    storage=SqliteAgentStorage(
        table_name="basic_agent",
        db_file=agent_storage_file,
        auto_upgrade_schema=True,
    ),
    add_history_to_messages=True,
    num_history_responses=3,
    add_datetime_to_instructions=True,
    markdown=True,
)

# Setup the Playground app
playground = Playground(
    agents=[agent],
    name="MCP Demo",
    description="A playground for MCP",
    app_id="mcp-demo",
)

# Initialize the Playground app with our lifespan logic
app = playground.get_app(lifespan=lifespan)


if __name__ == "__main__":
    playground.serve(app="mcp_demo:app", reload=True)
```

## Best Practices

1. **Error Handling**: Always include proper error handling for MCP server connections and operations.

2. **Resource Cleanup**: Remember to close the connection to the MCP server when using `MCPTools` or `MultiMCPTools`:

```python theme={null}
# Before exiting
await mcp_tools.close()
```

3. **Clear Instructions**: Provide clear and specific instructions to your agent:

```python theme={null}
instructions = """
You are a filesystem assistant. Help users explore files and directories.
- Navigate the filesystem to answer questions
- Use the list_allowed_directories tool to find accessible directories
- Provide clear context about files you examine
- Be concise and focus on relevant information
"""
```

## More Information

* Find examples of Agents that use MCP [here](https://docs-v1.agno.com/examples/concepts/tools/mcp/airbnb).
* Find a collection of MCP servers [here](https://github.com/modelcontextprotocol/servers).
* Read the [MCP documentation](https://modelcontextprotocol.io/introduction) to learn more about the Model Context Protocol.
* Checkout the Agno [Cookbook](https://github.com/agno-agi/agno/tree/main/cookbook/tools/mcp) for more examples of Agents that use MCP.
