> ## Documentation Index
> Fetch the complete documentation index at: https://slide.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Model Context Protocol (MCP)

> Using MCP to extend Slide agents with external tools and services

<Note>
  **Recommended Reading**: For practical implementation details, see the [MCP Integration Guide](/guides/mcp-integration).
</Note>

**💻 Code Examples**

<CardGroup cols={2}>
  <Card title="Basic MCP" icon="rocket" href="https://github.com/adamwdraper/slide/blob/main/packages/tyler/examples/300_mcp_basic.py">
    Get started with MCP
  </Card>

  <Card title="Advanced MCP" icon="server" href="https://github.com/adamwdraper/slide/blob/main/packages/tyler/examples/301_mcp_advanced.py">
    Multiple servers & filtering
  </Card>
</CardGroup>

## What is MCP?

The Model Context Protocol (MCP) is an open standard that enables seamless communication between AI applications and external tools. Slide's Tyler package includes first-class MCP support, allowing your agents to:

* Connect to any MCP-compatible server
* Use tools from external services
* Share context across applications
* Build interoperable AI systems

Tyler follows the MCP `2025-11-25` stable transport framing: Streamable HTTP is the default for remote servers, `stdio` is for local subprocess servers, and SSE is legacy compatibility.

## MCP Architecture in Slide

```mermaid theme={null}
graph LR
    A[Slide Agent] --> B[MCP SDK]
    B --> C[ClientSessionGroup]
    C --> D[MCP Server 1]
    C --> E[MCP Server 2]
    C --> F[MCP Server N]
    D --> G[External Tools]
    E --> H[Databases]
    F --> I[APIs]
```

Tyler uses the official MCP SDK's `ClientSessionGroup` to manage connections to multiple MCP servers simultaneously. This provides:

* Automatic session lifecycle management
* Tool discovery and aggregation across servers
* Tool execution routing to the correct server
* Standard MCP transports (`stdio`, Streamable HTTP) plus legacy SSE compatibility

## Quick Start

### Python API (Recommended)

```python theme={null}
import asyncio
from tyler import Agent, Thread, Message

async def main():
    # Create agent with MCP config (validates schema immediately)
    agent = Agent(
        name="Tyler",
        model_name="gpt-4.1",
        tools=["web"],
        mcp={
            "servers": [{
                "name": "docs",
                "transport": "streamablehttp",  # Use for Mintlify and hosted servers
                "url": "https://slide.mintlify.app/mcp"
            }]
        }
    )

    try:
        # Connect to MCP servers (fail fast!)
        await agent.connect_mcp()
        
        # Use the agent - MCP tools are now available
        thread = Thread()
        thread.add_message(Message(
            role="user",
            content="How do I create a Tyler agent?"
        ))
        
        result = await agent.run(thread)
        print(result.content)
    finally:
        await agent.cleanup()

if __name__ == "__main__":
    asyncio.run(main())
```

### Using MCP Tools

Once connected, MCP tools are automatically available to your agent with namespaced names:

```python theme={null}
# Tools from server "docs" become available as:
# - docs_SearchSlideFramework
# - docs_GetDocument
# etc.

# The agent automatically selects and uses appropriate tools
thread = Thread()
thread.add_message(Message(
    role="user",
    content="Search the Slide documentation for information about streaming"
))

result = await agent.run(thread)
```

## MCP Server Types

### 1. Stdio Servers

Local processes that communicate via standard input/output. Great for local tools and development:

```python theme={null}
mcp={
    "servers": [{
        "name": "filesystem",
        "transport": "stdio",
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
        "env": {"NODE_ENV": "production"}  # Optional environment
    }]
}
```

### 2. Streamable HTTP Servers

HTTP-based servers using the current remote transport. Recommended for hosted MCP servers:

```python theme={null}
mcp={
    "servers": [{
        "name": "docs",
        "transport": "streamablehttp",
        "url": "https://slide.mintlify.app/mcp",
        "headers": {"X-API-Key": "${API_KEY}"}  # Optional auth
    }]
}
```

### 3. SSE (Server-Sent Events) Servers

Legacy HTTP transport for backward compatibility with older MCP servers:

```python theme={null}
mcp={
    "servers": [{
        "name": "legacy",
        "transport": "sse",
        "url": "https://legacy.example.com/mcp"
    }]
}
```

## Creating MCP Servers

### Using FastMCP (Python)

Create an MCP server that exposes tools to Slide:

```python theme={null}
from fastmcp import FastMCP

# Create MCP server
mcp = FastMCP()

@mcp.tool()
async def search_knowledge_base(query: str) -> str:
    """Search internal knowledge base."""
    results = await db.search(query)
    return format_results(results)

@mcp.tool()
async def execute_sql(query: str, database: str = "main") -> dict:
    """Execute SQL query safely."""
    if not is_safe_query(query):
        return {"error": "Unsafe query"}
    
    conn = get_connection(database)
    results = await conn.execute(query)
    return {"data": results}

# Run the server
if __name__ == "__main__":
    mcp.run()
```

## Advanced MCP Usage

### Multiple Server Connections

Connect to multiple MCP servers simultaneously:

```python theme={null}
agent = Agent(
    name="multi-server-agent",
    model_name="gpt-4.1",
    mcp={
        "servers": [
            {
                "name": "docs",
                "transport": "streamablehttp",
                "url": "https://slide.mintlify.app/mcp",
                "prefix": "slide"  # Custom prefix
            },
            {
                "name": "github",
                "transport": "stdio",
                "command": "npx",
                "args": ["-y", "@modelcontextprotocol/server-github"],
                "env": {"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"},
                "prefix": "gh",
                "fail_silent": True  # Continue if GitHub unavailable
            },
            {
                "name": "filesystem",
                "transport": "stdio",
                "command": "npx",
                "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
                "exclude_tools": ["write_file", "delete_file"]  # Read-only
            }
        ]
    }
)

try:
    await agent.connect_mcp()

    # Agent now has tools from all servers:
    # - slide_SearchSlideFramework
    # - gh_search_repos
    # - filesystem_read_file, filesystem_list_directory
finally:
    await agent.cleanup()
```

### Tool Filtering

Control which tools are available:

```python theme={null}
{
    "name": "filesystem",
    "transport": "stdio",
    "command": "mcp-server-filesystem",
    "include_tools": ["read_file", "list_directory"],  # Whitelist
    "exclude_tools": ["delete_file"]  # Blacklist (applied after include)
}
```

### Custom Prefixes

Override the default namespace prefix for cleaner tool names:

```python theme={null}
{
    "name": "wandb_documentation_server",  # Long server name
    "prefix": "docs",  # Short, clean prefix
    "transport": "streamablehttp",
    "url": "https://docs.wandb.ai/mcp"
}
# Tools become: docs_search, docs_query (not wandb_documentation_server_search)
```

### Environment Variable Substitution

Use environment variables for secrets (recommended!):

```python theme={null}
mcp={
    "servers": [{
        "name": "api",
        "transport": "streamablehttp",
        "url": "https://api.example.com/mcp",
        "headers": {
            "Authorization": "Bearer ${API_TOKEN}",  # Substituted from env
            "X-API-Key": "${API_KEY}"
        }
    }]
}
```

### Graceful Degradation

Control failure behavior per server:

```python theme={null}
{
    "servers": [
        {
            "name": "critical",
            "url": "...",
            "fail_silent": False  # Fail startup if unavailable
        },
        {
            "name": "optional",
            "url": "...",
            "fail_silent": True  # Continue if unavailable (default)
        }
    ]
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="1. Connection Management">
    Always cleanup MCP connections:

    ```python theme={null}
    agent = Agent(mcp={...})
    try:
        await agent.connect_mcp()
        # Use agent
    finally:
        await agent.cleanup()
    ```
  </Accordion>

  <Accordion title="2. Security">
    Never hardcode secrets:

    ```python theme={null}
    # Good
    "headers": {"Authorization": "Bearer ${API_TOKEN}"}

    # Bad
    "headers": {"Authorization": "Bearer sk-1234567890"}
    ```

    Only connect to reviewed MCP servers. MCP tools execute with your agent's permissions, local `stdio` servers run with the same privileges as Tyler, and tool annotations/metadata are advisory unless the server is trusted.
  </Accordion>

  <Accordion title="3. Tool Organization">
    Use custom prefixes for cleaner tool names:

    ```python theme={null}
    {
        "name": "long_server_name",
        "prefix": "short",  # Tools become short_toolname
        ...
    }
    ```
  </Accordion>

  <Accordion title="4. Fail-Safe Configuration">
    Use `fail_silent: True` for optional servers:

    ```python theme={null}
    {
        "name": "optional_feature",
        "fail_silent": True,  # Won't break startup
        ...
    }
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

<Warning>
  Common MCP issues and solutions:

  * **Connection refused**: Check if MCP server is running and URL is correct
  * **Tool not found**: Verify tool is exposed by server, check `include_tools`/`exclude_tools`
  * **Timeout errors**: Increase timeout or check network connectivity
  * **Permission denied**: Verify authentication credentials
  * **Environment variable not substituted**: Ensure variable is set before running
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="MCP Integration Guide" icon="plug" href="/guides/mcp-integration">
    Detailed configuration reference
  </Card>

  <Card title="MCP Examples" icon="code" href="https://github.com/adamwdraper/slide/tree/main/packages/tyler/examples">
    See MCP integration examples
  </Card>

  <Card title="Create MCP Server" icon="server" href="https://github.com/modelcontextprotocol/python-sdk">
    Build your own MCP server
  </Card>

  <Card title="MCP Specification" icon="book" href="https://modelcontextprotocol.org">
    Read the MCP specification
  </Card>
</CardGroup>
