Skip to main content

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.

Issue #2: LLM Provider Format

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.mcp 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

MCP Tools Not Found

If you get โ€œMCP tool cannot be foundโ€ errors:
  1. Check MCP Server Command: Ensure the MCP server command is correct and the server starts successfully
  2. Verify Dependencies: Make sure all required dependencies (Node.js, npm, etc.) are installed
  3. Test Manually: Try running the MCP server command manually first
  4. Enable Debug Mode: Set debug=True in MCP constructor for detailed logs

Tool Calling Issues

If tools arenโ€™t being called properly:
  1. Use Standard LLM Format: Avoid provider/model format like "ollama/llama3.2"
  2. Check API Keys: Ensure proper environment variables are set for your chosen LLM
  3. Session State: Verify agent is properly stored in session state
  4. Timeout Settings: Increase timeout if needed: MCP(command, timeout=120)

Threading Conflicts

If you encounter threading-related errors:
  1. Single Agent Instance: Use only one agent instance per session
  2. Proper Cleanup: Let Streamlit handle cleanup naturally
  3. 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:
  1. Proper session state management - Initialize agent only once
  2. Standard LLM format - Avoid provider/model format in Streamlit
  3. Comprehensive error handling - Provide user feedback
  4. 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.