MCP STDIO Integration
Guide for integrating Standard Input/Output (STDIO) with PraisonAI agents using MCP
Add STDIO Tool to AI Agent
Quick Start
- Create a client file
Create a new file
calculator_client.pywith the following code:python from praisonaiagents import Agent, MCP calculator_agent = Agent( instructions="""You are a calculator agent that can perform basic arithmetic operations.""", llm="gpt-4o-mini", tools=MCP("python calculator_server.py") ) calculator_agent.start("What is 25 * 16?") - Set Up STDIO MCP Server
Create a file
calculator_server.pywith the following code:python # calculator_server.py from mcp.server.fastmcp import FastMCP import logging import sys # Set up logging logging.basicConfig(level=logging.INFO, filename="calculator_server.log") logger = logging.getLogger("calculator-server") # Initialize FastMCP server for simple tools mcp = FastMCP("calculator-tools") @mcp.tool() def add(a: float, b: float) -> float: """Add two numbers. Args: a: First number b: Second number Returns: The sum of a and b """ logger.info(f"Adding {a} + {b}") return a + b @mcp.tool() def subtract(a: float, b: float) -> float: """Subtract b from a. Args: a: First number b: Second number Returns: The result of a - b """ logger.info(f"Subtracting {b} from {a}") return a - b @mcp.tool() def multiply(a: float, b: float) -> float: """Multiply two numbers. Args: a: First number b: Second number Returns: The product of a and b """ logger.info(f"Multiplying {a} * {b}") return a * b @mcp.tool() def divide(a: float, b: float) -> float: """Divide a by b. Args: a: First number (numerator) b: Second number (denominator) Returns: The result of a / b """ if b == 0: raise ValueError("Cannot divide by zero") logger.info(f"Dividing {a} / {b}") return a / b if __name__ == "__main__": # Run the MCP server using STDIO transport mcp.run() - Install Dependencies
Make sure you have the required packages installed:
bash pip install "praisonaiagents[llm]" mcp - Export API Key
bash export OPENAI_API_KEY="your_api_key" - Run the Agent
Run the agent which will automatically start the calculator server:
bash python calculator_client.py
Cleanup
For one-off scripts the calculator subprocess is reclaimed when the Python process exits, so no manual cleanup is required. For long-running hosts (gateway, API server, notebook, CI), close the agent so its MCP subprocess is terminated deterministically:
from praisonaiagents import Agent, MCP
agent = Agent(
instructions="You are a calculator agent.",
llm="gpt-4o-mini",
tools=MCP("python calculator_server.py"),
)
try:
print(agent.start("What is 25 * 16?"))
finally:
agent.close() # terminates the calculator subprocessPrefer the context-manager form when the agent’s scope is a single request:
with MCP("python calculator_server.py") as mcp:
agent = Agent(instructions="You are a calculator agent.", tools=mcp)
print(agent.start("What is 25 * 16?"))
# subprocess terminated on exitSee MCP Lifecycle Management for details.
Auto-respawn on crash
If a stdio MCP server crashes mid-session, PraisonAI respawns it on the next call.
- Closed pipes, broken connections, and EOF are detected as a lost server.
- The call that saw the crash returns
Error: MCP server connection lost: <reason>immediately, without waiting outtimeout. - The next call starts a fresh server with the same parameters and
timeout. - Respawns are capped at 3 per
MCP(...)instance. - A respawn that fails to start can be retried on a later call within the same budget.
- Resource and prompt helpers (
list_mcp_resources,read_mcp_resource,list_mcp_prompts,get_mcp_prompt) follow the restart too. - After
shutdown()begins, no replacement is started.
Each respawn logs MCP stdio server lost (<reason>); restarting (<n>/3).
Alternative LLM Integrations
Using Groq with STDIO
from praisonaiagents import Agent, MCP
calculator_agent = Agent(
instructions="""You are a calculator agent that can perform basic arithmetic operations.""",
llm="groq/llama-3.2-90b-vision-preview",
tools=MCP("python calculator_server.py")
)
calculator_agent.start("What is 144 divided by 12?")Using Ollama with STDIO
from praisonaiagents import Agent, MCP
calculator_agent = Agent(
instructions="""You are a calculator agent that can perform basic arithmetic operations.""",
llm="ollama/llama3.2",
tools=MCP("python calculator_server.py")
)
calculator_agent.start("What is 15 + 27? Use the add tool with parameters a and b.")Gradio UI Integration
Create a Gradio UI for your calculator service:
from praisonaiagents import Agent, MCP
import gradio as gr
def calculate(query):
calculator_agent = Agent(
instructions="""You are a calculator agent that can perform basic arithmetic operations.""",
llm="gpt-4o-mini",
tools=MCP("python calculator_server.py")
)
result = calculator_agent.start(query)
return f"## Calculation Result\n\n{result}"
demo = gr.Interface(
fn=calculate,
inputs=gr.Textbox(placeholder="What is 25 * 16?"),
outputs=gr.Markdown(),
title="Calculator MCP Agent",
description="Ask any arithmetic question:"
)
if __name__ == "__main__":
demo.launch()Features
Use standard input/output for easy integration with any tool or service.
Cross-PlatformWorks on any operating system that supports Python.
Multiple LLM OptionsUse with OpenAI, Groq, Ollama, or other supported LLMs.
Gradio UICreate user-friendly interfaces for your STDIO integrations.