|
| 1 | +--- |
| 2 | +title: "MCP SSE Integration" |
| 3 | +sidebarTitle: "MCP SSE" |
| 4 | +description: "Guide for integrating Server-Sent Events (SSE) with PraisonAI agents using MCP" |
| 5 | +icon: "server" |
| 6 | +--- |
| 7 | + |
| 8 | +## Add SSE Tool to AI Agent |
| 9 | + |
| 10 | +```mermaid |
| 11 | +flowchart LR |
| 12 | + In[In] --> Agent[AI Agent] |
| 13 | + Agent --> Tool[SSE MCP] |
| 14 | + Tool --> Agent |
| 15 | + Agent --> Out[Out] |
| 16 | + |
| 17 | + style In fill:#8B0000,color:#fff |
| 18 | + style Agent fill:#2E8B57,color:#fff |
| 19 | + style Tool fill:#4169E1,color:#fff |
| 20 | + style Out fill:#8B0000,color:#fff |
| 21 | +``` |
| 22 | + |
| 23 | +## Quick Start |
| 24 | + |
| 25 | +<Steps> |
| 26 | + <Step title="Create a client file"> |
| 27 | + |
| 28 | +```python |
| 29 | +from praisonaiagents import Agent, MCP |
| 30 | + |
| 31 | +search_agent = Agent( |
| 32 | + instructions="""You are a weather agent that can provide weather information for a given city.""", |
| 33 | + llm="gpt-4o-mini", |
| 34 | + tools=MCP("http://localhost:8080/sse") |
| 35 | +) |
| 36 | + |
| 37 | +search_agent.start("What is the weather in London?") |
| 38 | +``` |
| 39 | + |
| 40 | + </Step> |
| 41 | + <Step title="Set Up SSE MCP Server"> |
| 42 | + |
| 43 | +```python |
| 44 | +# python mcp-sse-direct-server.py --host 127.0.0.1 --port 8080 |
| 45 | +from typing import Any |
| 46 | +import httpx |
| 47 | +from mcp.server.fastmcp import FastMCP |
| 48 | +from starlette.applications import Starlette |
| 49 | +from mcp.server.sse import SseServerTransport |
| 50 | +from starlette.requests import Request |
| 51 | +from starlette.routing import Mount, Route |
| 52 | +from mcp.server import Server |
| 53 | +import uvicorn |
| 54 | +import argparse |
| 55 | +import logging |
| 56 | +import os |
| 57 | +import inspect |
| 58 | + |
| 59 | +# Set up logging based on environment variable |
| 60 | +log_level = os.environ.get("LOGLEVEL", "info").upper() |
| 61 | +logging.basicConfig(level=getattr(logging, log_level)) |
| 62 | +logger = logging.getLogger("mcp-server") |
| 63 | + |
| 64 | +# Initialize FastMCP server for simple tools (SSE) |
| 65 | +mcp = FastMCP("simple-tools") |
| 66 | + |
| 67 | +@mcp.tool() |
| 68 | +async def get_greeting(name: str) -> str: |
| 69 | + """Get a personalized greeting. |
| 70 | +
|
| 71 | + Args: |
| 72 | + name: Name of the person to greet |
| 73 | + """ |
| 74 | + logger.debug(f"get_greeting called with name: {name}") |
| 75 | + return f"Hello, {name}! Welcome to our MCP SSE server." |
| 76 | + |
| 77 | +@mcp.tool() |
| 78 | +async def get_weather(city: str) -> str: |
| 79 | + """Get a simulated weather report for a city. |
| 80 | +
|
| 81 | + Args: |
| 82 | + city: Name of the city |
| 83 | + """ |
| 84 | + logger.debug(f"get_weather called with city: {city}") |
| 85 | + # This is a mock implementation |
| 86 | + weather_data = { |
| 87 | + "Paris": "Sunny with a temperature of 22°C", |
| 88 | + "London": "Rainy with a temperature of 15°C", |
| 89 | + "New York": "Cloudy with a temperature of 18°C", |
| 90 | + "Tokyo": "Clear skies with a temperature of 25°C", |
| 91 | + "Sydney": "Partly cloudy with a temperature of 20°C" |
| 92 | + } |
| 93 | + |
| 94 | + return weather_data.get(city, f"Weather data not available for {city}") |
| 95 | + |
| 96 | +def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette: |
| 97 | + """Create a Starlette application that can serve the provided mcp server with SSE.""" |
| 98 | + sse = SseServerTransport("/messages/") |
| 99 | + |
| 100 | + async def handle_sse(request: Request) -> None: |
| 101 | + logger.debug(f"SSE connection request received from {request.client}") |
| 102 | + async with sse.connect_sse( |
| 103 | + request.scope, |
| 104 | + request.receive, |
| 105 | + request._send, # noqa: SLF001 |
| 106 | + ) as (read_stream, write_stream): |
| 107 | + await mcp_server.run( |
| 108 | + read_stream, |
| 109 | + write_stream, |
| 110 | + mcp_server.create_initialization_options(), |
| 111 | + ) |
| 112 | + |
| 113 | + return Starlette( |
| 114 | + debug=debug, |
| 115 | + routes=[ |
| 116 | + Route("/sse", endpoint=handle_sse), |
| 117 | + Mount("/messages/", app=sse.handle_post_message), |
| 118 | + ], |
| 119 | + ) |
| 120 | + |
| 121 | +if __name__ == "__main__": |
| 122 | + mcp_server = mcp._mcp_server # noqa: WPS437 |
| 123 | + |
| 124 | + parser = argparse.ArgumentParser(description='Run MCP SSE-based server') |
| 125 | + parser.add_argument('--host', default='localhost', help='Host to bind to') |
| 126 | + parser.add_argument('--port', type=int, default=8080, help='Port to listen on') |
| 127 | + args = parser.parse_args() |
| 128 | + |
| 129 | + print(f"Starting MCP SSE server on {args.host}:{args.port}") |
| 130 | + |
| 131 | + # Hardcode the tool names since we know what they are |
| 132 | + tool_names = ["get_greeting", "get_weather"] |
| 133 | + print(f"Available tools: {', '.join(tool_names)}") |
| 134 | + |
| 135 | + # Bind SSE request handling to MCP server |
| 136 | + starlette_app = create_starlette_app(mcp_server, debug=True) |
| 137 | + |
| 138 | + uvicorn.run(starlette_app, host=args.host, port=args.port) |
| 139 | +``` |
| 140 | + </Step> |
| 141 | + |
| 142 | + <Step title="Install Dependencies"> |
| 143 | + Make sure you have the required packages installed: |
| 144 | + ```bash |
| 145 | + pip install "praisonaiagents[llm]" mcp starlette uvicorn httpx |
| 146 | + ``` |
| 147 | + </Step> |
| 148 | + <Step title="Export API Key"> |
| 149 | + ```bash |
| 150 | + export OPENAI_API_KEY="your_api_key" |
| 151 | + ``` |
| 152 | + </Step> |
| 153 | + |
| 154 | + <Step title="Run the Server and Agent"> |
| 155 | + First, start the SSE server: |
| 156 | + ```bash |
| 157 | + python mcp-sse-direct-server.py --host 127.0.0.1 --port 8080 |
| 158 | + ``` |
| 159 | + |
| 160 | + Then, in a new terminal, run the agent: |
| 161 | + ```bash |
| 162 | + python weather_agent.py |
| 163 | + ``` |
| 164 | + </Step> |
| 165 | +</Steps> |
| 166 | + |
| 167 | +<Note> |
| 168 | + **Requirements** |
| 169 | + - Python 3.10 or higher |
| 170 | + - MCP server dependencies |
| 171 | +</Note> |
| 172 | + |
| 173 | +## Alternative LLM Integrations |
| 174 | + |
| 175 | +### Using Groq with SSE |
| 176 | + |
| 177 | +```python |
| 178 | +from praisonaiagents import Agent, MCP |
| 179 | + |
| 180 | +weather_agent = Agent( |
| 181 | + instructions="""You are a weather agent that can provide weather information for a given city.""", |
| 182 | + llm="groq/llama-3.2-90b-vision-preview", |
| 183 | + tools=MCP("http://localhost:8080/sse") |
| 184 | +) |
| 185 | + |
| 186 | +weather_agent.start("What is the weather in London?") |
| 187 | +``` |
| 188 | + |
| 189 | +### Using Ollama with SSE |
| 190 | + |
| 191 | +```python |
| 192 | +from praisonaiagents import Agent, MCP |
| 193 | + |
| 194 | +weather_agent = Agent( |
| 195 | + instructions="""You are a weather agent that can provide weather information for a given city.""", |
| 196 | + llm="ollama/llama3.2", |
| 197 | + tools=MCP("http://localhost:8080/sse") |
| 198 | +) |
| 199 | + |
| 200 | +weather_agent.start("What is the weather in London? Use get_weather tool, city is the required parameter.") |
| 201 | +``` |
| 202 | + |
| 203 | +## Gradio UI Integration |
| 204 | + |
| 205 | +Create a Gradio UI for your weather service: |
| 206 | + |
| 207 | +```python |
| 208 | +from praisonaiagents import Agent, MCP |
| 209 | +import gradio as gr |
| 210 | + |
| 211 | +def get_weather_info(query): |
| 212 | + weather_agent = Agent( |
| 213 | + instructions="""You are a weather agent that can provide weather information for a given city.""", |
| 214 | + llm="gpt-4o-mini", |
| 215 | + tools=MCP("http://localhost:8080/sse") |
| 216 | + ) |
| 217 | + |
| 218 | + result = weather_agent.start(query) |
| 219 | + return f"## Weather Information\n\n{result}" |
| 220 | + |
| 221 | +demo = gr.Interface( |
| 222 | + fn=get_weather_info, |
| 223 | + inputs=gr.Textbox(placeholder="What's the weather in London?"), |
| 224 | + outputs=gr.Markdown(), |
| 225 | + title="Weather MCP Agent", |
| 226 | + description="Ask about the weather in any major city:" |
| 227 | +) |
| 228 | + |
| 229 | +if __name__ == "__main__": |
| 230 | + demo.launch() |
| 231 | +``` |
| 232 | + |
| 233 | +## Features |
| 234 | + |
| 235 | +<CardGroup cols={2}> |
| 236 | + <Card title="Real-time Updates" icon="bolt"> |
| 237 | + Receive server-sent events in real-time from your AI agent. |
| 238 | + </Card> |
| 239 | + <Card title="Multi-Agent Support" icon="users"> |
| 240 | + Combine SSE with other MCP tools for complex workflows. |
| 241 | + </Card> |
| 242 | + <Card title="Multiple LLM Options" icon="brain"> |
| 243 | + Use with OpenAI, Groq, Ollama, or other supported LLMs. |
| 244 | + </Card> |
| 245 | + <Card title="Gradio UI" icon="window"> |
| 246 | + Create user-friendly interfaces for your SSE integrations. |
| 247 | + </Card> |
| 248 | +</CardGroup> |
0 commit comments