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 with Streamlit
This guide explains how to properly integrate MCP (Model Context Protocol) tools with PraisonAI Agents in Streamlit applications, addressing common issues and providing working solutions.
Common Issues
When integrating MCP tools with Streamlit, users often encounter these problems:
Issue #1: Agent Re-initialization
Problem: Agent gets re-initialized on every Streamlit interaction, causing MCP tools to fail.
Solution: Use Streamlitโs session state to initialize the agent only once.
Problem: Using provider/model format like "ollama/llama3.2" can cause tool calling issues in Streamlit environments.
Solution: Use standard model names like "gpt-4o-mini" instead of provider/model format.
Issue #3: Missing Error Handling
Problem: No user feedback when MCP initialization fails.
Solution: Implement comprehensive error handling with user-friendly messages.
Working Example
Hereโs a complete working example that demonstrates the correct approach:
import streamlit as st
from praisonaiagents import Agent
from praisonaiagents import MCP
import traceback
st.title("๐ AI Airbnb Assistant")
# Configuration in sidebar
with st.sidebar:
st.header("โ๏ธ Configuration")
# Use standard model names, not provider/model format
llm_model = st.selectbox(
"Choose LLM Model",
options=[
"gpt-4o-mini", # โ
Correct format
"gpt-4o",
"claude-3-5-sonnet-20241022"
],
index=0
)
debug_mode = st.checkbox("Enable Debug Mode", value=False)
# Initialize session state (CRITICAL for Streamlit)
if "agent_initialized" not in st.session_state:
st.session_state.agent_initialized = False
st.session_state.agent = None
st.session_state.init_error = None
# Function to initialize agent with proper error handling
def initialize_agent():
try:
with st.spinner("๐ Initializing AI agent..."):
# Create MCP tools
mcp_tools = MCP(
"npx -y @openbnb/mcp-server-airbnb --ignore-robots-txt",
timeout=60,
debug=debug_mode
)
# Create agent - this should only happen ONCE
agent = Agent(
instructions="You are a helpful Airbnb assistant...",
llm=llm_model, # Use standard format
tools=mcp_tools,
verbose=debug_mode
)
return agent, None
except Exception as e:
error_msg = f"Failed to initialize agent: {str(e)}"
if debug_mode:
error_msg += f"\n\nFull traceback:\n{traceback.format_exc()}"
return None, error_msg
# Agent initialization (only runs once)
if not st.session_state.agent_initialized:
if st.button("๐ Initialize AI Assistant", type="primary"):
agent, error = initialize_agent()
if agent:
st.session_state.agent = agent
st.session_state.agent_initialized = True
st.session_state.init_error = None
st.success("โ
AI Assistant initialized successfully!")
st.rerun()
else:
st.session_state.init_error = error
st.error(f"โ Initialization failed: {error}")
# Main interface (only show if agent is ready)
if st.session_state.agent_initialized and st.session_state.agent:
query = st.text_input("๐ What are you looking for?")
if st.button("Search") and query:
try:
with st.spinner("๐ Searching..."):
# Use the SAME agent instance from session state
result = st.session_state.agent.start(query)
st.write(result)
except Exception as e:
st.error(f"โ Search failed: {str(e)}")
Best Practices
1. Session State Management
Always use Streamlitโs session state to manage agent lifecycle:
# โ
Correct - Initialize once in session state
if "agent" not in st.session_state:
st.session_state.agent = Agent(...)
# โ Wrong - Re-initializes on every interaction
agent = Agent(...)
2. LLM Model Selection
Use standard model names, avoid provider/model format in Streamlit:
# โ
Correct - Standard model names
llm="gpt-4o-mini"
llm="claude-3-5-sonnet-20241022"
# โ Problematic in Streamlit - Provider/model format
llm="ollama/llama3.2"
llm="anthropic/claude-3-5-sonnet"
3. Error Handling
Implement comprehensive error handling:
try:
# MCP initialization
mcp_tools = MCP("your-mcp-command")
agent = Agent(tools=mcp_tools, ...)
except Exception as e:
st.error(f"Initialization failed: {str(e)}")
# Provide troubleshooting tips
4. User Feedback
Provide clear feedback during initialization:
with st.spinner("๐ Initializing AI agent and MCP tools..."):
# Initialization code here
pass
if initialization_successful:
st.success("โ
AI Assistant initialized successfully!")
else:
st.error("โ Initialization failed")
Troubleshooting
If you get โMCP tool cannot be foundโ errors:
- Check MCP Server Command: Ensure the MCP server command is correct and the server starts successfully
- Verify Dependencies: Make sure all required dependencies (Node.js, npm, etc.) are installed
- Test Manually: Try running the MCP server command manually first
- Enable Debug Mode: Set
debug=True in MCP constructor for detailed logs
If tools arenโt being called properly:
- Use Standard LLM Format: Avoid provider/model format like
"ollama/llama3.2"
- Check API Keys: Ensure proper environment variables are set for your chosen LLM
- Session State: Verify agent is properly stored in session state
- Timeout Settings: Increase timeout if needed:
MCP(command, timeout=120)
Threading Conflicts
If you encounter threading-related errors:
- Single Agent Instance: Use only one agent instance per session
- Proper Cleanup: Let Streamlit handle cleanup naturally
- Avoid Manual Threading: Donโt create additional threads in Streamlit
Complete Working Example
For a complete, production-ready example, see:
This example includes:
- โ
Proper session state management
- โ
Comprehensive error handling
- โ
User-friendly interface
- โ
Debug mode support
- โ
Troubleshooting guidance
- โ
Configuration options
Environment Setup
Make sure your environment has the required dependencies:
# Install PraisonAI Agents
pip install praisonaiagents
# Install Streamlit
pip install streamlit
# For Airbnb MCP server example
npm install -g @openbnb/mcp-server-airbnb
# Set environment variables for your chosen LLM
export OPENAI_API_KEY="your-key"
# or
export ANTHROPIC_API_KEY="your-key"
Running the Example
# Run the working example
streamlit run examples/python/ui/mcp-streamlit-airbnb.py
# Or create your own based on the patterns above
streamlit run your-mcp-app.py
Summary
The key to successfully using MCP with Streamlit is:
- Proper session state management - Initialize agent only once
- Standard LLM format - Avoid provider/model format in Streamlit
- Comprehensive error handling - Provide user feedback
- Correct usage patterns - Follow Streamlit best practices
By following these guidelines, MCP tools will work reliably in your Streamlit applications without requiring any modifications to the core MCP implementation.