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

# MCP Lifecycle Management

> Context manager and cleanup for MCP connections

# MCP Lifecycle Management

PraisonAI Agents v0.5.0+ includes improved lifecycle management for MCP (Model Context Protocol) connections with context manager support and explicit cleanup.

## Context Manager Support

Use MCP as a context manager for automatic cleanup:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents import MCP

# Using context manager - automatic cleanup
with MCP("uvx mcp-server-time") as mcp:
    agent = Agent(
        name="TimeAgent",
        instructions="Get the current time",
        tools=mcp
    )
    response = agent.chat("What time is it?")
    print(response)
# MCP connection automatically closed here
```

## Manual Cleanup

For cases where context manager isn't suitable:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import MCP

mcp = MCP("uvx mcp-server-time")

try:
    # Use MCP
    tools = mcp.get_tools()
    # ... do work ...
finally:
    # Explicit cleanup
    mcp.shutdown()
```

## Lifecycle Methods

### `__enter__` / `__exit__`

Context manager protocol for automatic resource management:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP(command) as mcp:
    # MCP is initialized and ready
    pass
# __exit__ calls shutdown() automatically
```

### `shutdown()`

Explicitly close all connections and cleanup resources:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
mcp = MCP("uvx mcp-server-time")
# ... use mcp ...
mcp.shutdown()  # Clean up
```

### `__del__`

Destructor ensures cleanup even if shutdown() wasn't called:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
mcp = MCP("uvx mcp-server-time")
del mcp  # __del__ calls shutdown()
```

## Connection Types

MCP supports multiple connection types, all with proper cleanup:

### Stdio (Command-based)

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("uvx mcp-server-time") as mcp:
    # Subprocess is managed
    pass
# Process terminated on exit
```

### SSE (Server-Sent Events)

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("http://localhost:8080/sse") as mcp:
    # SSE connection managed
    pass
# Connection closed on exit
```

### HTTP Stream

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("http://localhost:8080") as mcp:
    # HTTP stream managed
    pass
# Stream closed on exit
```

### WebSocket

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("ws://localhost:8080") as mcp:
    # WebSocket managed
    pass
# WebSocket closed on exit
```

## Best Practices

### Always Use Context Manager

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Good - automatic cleanup
with MCP(command) as mcp:
    agent = Agent(tools=mcp)
    agent.chat("Hello")

# Avoid - manual cleanup required
mcp = MCP(command)
agent = Agent(tools=mcp)
agent.chat("Hello")
mcp.shutdown()  # Easy to forget
```

### Handle Exceptions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import MCP

try:
    with MCP("uvx mcp-server-time") as mcp:
        # Work that might fail
        result = mcp.call_tool("get_time", {})
except Exception as e:
    print(f"Error: {e}")
# Cleanup happens even on exception
```

### Multiple MCP Instances

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("uvx mcp-server-time") as time_mcp:
    with MCP("uvx mcp-server-fetch") as fetch_mcp:
        agent = Agent(
            name="MultiMCP",
            tools=[time_mcp, fetch_mcp]
        )
        agent.chat("Get time and fetch a URL")
# Both cleaned up properly
```

## Environment Variables

Pass environment variables to MCP servers:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import os

with MCP(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-brave-search"],
    env={"BRAVE_API_KEY": os.environ.get("BRAVE_API_KEY")}
) as mcp:
    agent = Agent(tools=mcp)
    agent.chat("Search for Python tutorials")
```

## Timeout Configuration

Set timeouts for MCP operations:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
with MCP("uvx mcp-server-time", timeout=30) as mcp:
    # Operations timeout after 30 seconds
    result = mcp.call_tool("get_time", {})
```

## Related

* [MCP CLI](/docs/cli/mcp)
* [MCP Module](/docs/sdk/praisonaiagents/mcp/mcp)
* [MCP Transports](/docs/mcp/transports)
