> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP with Streamlit

> How to properly integrate MCP (Model Context Protocol) tools with PraisonAI Agents in Streamlit applications

# 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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# ✅ 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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# ✅ 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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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:

* [`examples/python/ui/mcp-streamlit-airbnb.py`](https://github.com/MervinPraison/PraisonAI/blob/main/examples/python/ui/mcp-streamlit-airbnb.py)

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:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# 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.
