When building integrations between Pydantic AI and the MT5 MCP server, follow these patterns:
Error Handling
Always check result.isError when calling MCP tools to prevent the agent from proceeding with invalid data.
try:
result = await session.call_tool("get_account_info", arguments={})
if result.isError:
print(f"Error: {result.content}")
else:
account_info = result.content[0].text
except Exception as e:
print(f"MCP call failed: {e}")
Connection Management
Use async with blocks for both the stdio_client and ClientSession to ensure resources are cleaned up. Always call the shutdown tool in a finally block to properly close the MT5 connection.
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
try:
# logic
pass
finally:
await session.call_tool("shutdown", arguments={})
Type Safety and Dependency Injection
- Structured Outputs: Use Pydantic models as the
result_type for agents to ensure the AI returns data in a format your code can reliably use. - Dependency Injection: Pass the MCP
session and other configuration (like max_risk_per_trade) into the agent using the deps parameter. This allows tools to access the active session via RunContext.