Skip to main content

Overview

MCPTools enables agents to connect to MCP (Model Context Protocol) servers for accessing external tools, databases, and services. MCP provides a standardized way to extend agent capabilities with external integrations.

Installation

pip install agno

Basic Usage

import asyncio
from agno.agent import Agent
from agno.models.nebius import Nebius
from agno.tools.mcp import MCPTools
import os

async def run_agent():
    # Initialize MCP tools with a command to start the MCP server
    mcp_tools = MCPTools(
        "uvx --from gibson-cli@latest gibson mcp run",
        timeout_seconds=300
    )
    
    # Connect to the MCP server
    await mcp_tools.connect()
    
    agent = Agent(
        name="DatabaseAgent",
        model=Nebius(
            id="meta-llama/Meta-Llama-3.1-70B-Instruct",
            api_key=os.getenv("NEBIUS_API_KEY")
        ),
        tools=[mcp_tools],
        description="Agent for managing database projects and schemas",
        markdown=True,
        show_tool_calls=True
    )
    
    await agent.aprint_response("Create a new database project", stream=True)
    
    # Close the MCP connection
    await mcp_tools.close()

asyncio.run(run_agent())

API Reference

MCPTools

command
string
required
The command to start the MCP server. This can be a shell command that launches the MCP server process.Example: "uvx --from gibson-cli@latest gibson mcp run"
timeout_seconds
integer
default:"120"
Maximum time in seconds to wait for MCP server operations.Example: 300

Methods

connect()

Establishes connection to the MCP server.
await mcp_tools.connect()
return
None
Establishes the connection. Raises exception if connection fails.

close()

Closes the connection to the MCP server.
await mcp_tools.close()
return
None
Cleanly closes the MCP server connection.

Common MCP Server Examples

GibsonAI Database MCP

mcp_tools = MCPTools(
    "uvx --from gibson-cli@latest gibson mcp run",
    timeout_seconds=300
)

agent = Agent(
    name="GibsonAIAgent",
    model=Nebius(
        id="meta-llama/Meta-Llama-3.1-70B-Instruct",
        api_key=os.getenv("NEBIUS_API_KEY")
    ),
    tools=[mcp_tools],
    instructions="""You are a GibsonAI database assistant. Help users manage their database projects and schemas.

Your capabilities include:
- Creating new GibsonAI projects
- Managing database schemas (tables, columns, relationships)
- Deploying schema changes to hosted databases
- Querying database schemas and data
- Providing insights about database structure and best practices
""",
    markdown=True,
    show_tool_calls=True
)

GitHub MCP Server

For GitHub integration using the official GitHub MCP server:
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStdio
import os

async def run_github_agent():
    async with MCPServerStdio(
        params={
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {"GITHUB_PERSONAL_ACCESS_TOKEN": os.environ["GITHUB_TOKEN"]}
        }
    ) as server:
        agent = Agent(
            name="GitHubAgent",
            mcp_servers=[server],
            instructions="Help manage GitHub repositories and issues"
        )
        
        result = await Runner.run(
            agent,
            "List all open issues in my repositories"
        )
        print(result.final_output)

asyncio.run(run_github_agent())

Custom MCP Server

mcp_tools = MCPTools(
    "python custom_mcp_server.py",
    timeout_seconds=180
)

Agent Configuration with MCP

Database Agent Example

async def run_database_agent(message: str):
    mcp_tools = MCPTools(
        "uvx --from gibson-cli@latest gibson mcp run",
        timeout_seconds=300
    )
    
    await mcp_tools.connect()
    
    agent = Agent(
        name="DatabaseAgent",
        model=Nebius(
            id="meta-llama/Meta-Llama-3.1-70B-Instruct",
            api_key=os.getenv("NEBIUS_API_KEY")
        ),
        tools=[mcp_tools],
        description="Agent for managing database projects and schemas",
        instructions="""You are a GibsonAI database assistant. Help users manage their database projects and schemas.

Your capabilities include:
- Creating new GibsonAI projects
- Managing database schemas (tables, columns, relationships)
- Deploying schema changes to hosted databases
- Querying database schemas and data
- Providing insights about database structure and best practices
""",
        markdown=True,
        show_tool_calls=True
    )
    
    await agent.aprint_response(message, stream=True)
    await mcp_tools.close()

Example Use Cases

Create Database Schema

await run_database_agent(
    "Create a new GibsonAI project for my Blog Application with tables for users, posts, and comments"
)

GitHub Repository Management

await run_github_agent(
    "Create a new issue in my project repository about adding dark mode support"
)

File System Operations

mcp_tools = MCPTools(
    "npx -y @modelcontextprotocol/server-filesystem /path/to/dir",
    timeout_seconds=120
)

Best Practices

  1. Always close connections: Use await mcp_tools.close() to properly clean up resources
  2. Set appropriate timeouts: Adjust timeout_seconds based on expected operation duration
  3. Handle exceptions: MCP connections can fail, implement proper error handling
  4. Use async/await: MCP tools require async context
  5. Verify server availability: Ensure the MCP server command is accessible

Connection Lifecycle

async def mcp_lifecycle_example():
    # 1. Initialize
    mcp_tools = MCPTools(
        "uvx --from gibson-cli@latest gibson mcp run",
        timeout_seconds=300
    )
    
    try:
        # 2. Connect
        await mcp_tools.connect()
        
        # 3. Use with agent
        agent = Agent(
            name="Agent",
            model=Nebius(id="meta-llama/Meta-Llama-3.1-70B-Instruct", api_key=os.getenv("NEBIUS_API_KEY")),
            tools=[mcp_tools]
        )
        
        await agent.aprint_response("Your query here", stream=True)
        
    finally:
        # 4. Always close
        await mcp_tools.close()

Available MCP Servers

  • @modelcontextprotocol/server-github: GitHub integration
  • @modelcontextprotocol/server-filesystem: File system access
  • gibson-cli: Database management (GibsonAI)
  • Custom servers: Build your own MCP server

Error Handling

try:
    await mcp_tools.connect()
    # Use the agent
except TimeoutError:
    print("MCP server connection timeout")
except ConnectionError:
    print("Failed to connect to MCP server")
finally:
    await mcp_tools.close()

Build docs developers (and LLMs) love