PraisonAI Agents v0.5.0+ includes improved lifecycle management for MCP (Model Context Protocol) connections with context manager support and explicit cleanup.
Use MCP as a context manager for automatic cleanup:
Copy
from praisonaiagents import Agentfrom praisonaiagents.mcp import MCP# Using context manager - automatic cleanupwith 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
from praisonaiagents.mcp import MCPtry: 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
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