MCP SSE session
The SSE Session API creates a Server-Sent Events (SSE) session between a client and the Model Context Protocol (MCP) server in Lucenia. The session establishes a persistent connection that allows the server to push updates to the client in real-time.
Overview
Server-Sent Events provide a unidirectional communication channel from the MCP server to connected clients. This is ideal for:
- Real-time tool execution results
- Server status updates
- Tool discovery notifications
- Error reporting and diagnostics
Create SSE session
Request
GET /_plugins/_ml/mcp/sse
Headers
Header | Value | Required | Description |
---|---|---|---|
Accept | text/event-stream | Yes | Specifies SSE content type |
Cache-Control | no-cache | No | Prevents caching of the stream |
Connection | keep-alive | No | Maintains persistent connection |
Query parameters
Parameter | Type | Description | Default |
---|---|---|---|
append_to_base_url | Boolean | For Python clients, appends parameters to base URL | false |
session_id | String | Custom session identifier | Auto-generated |
timeout | Number | Session timeout in seconds | 300 |
Example requests
Basic SSE connection
curl -X GET "https://localhost:9200/_plugins/_ml/mcp/sse" \
-H "Accept: text/event-stream" \
-H "Cache-Control: no-cache" \
-H "Authorization: Basic $(echo -n 'username:password' | base64)"
Connection with custom session ID
curl -X GET "https://localhost:9200/_plugins/_ml/mcp/sse?session_id=my-session-123" \
-H "Accept: text/event-stream" \
-H "Authorization: Basic $(echo -n 'username:password' | base64)"
Python client connection
curl -X GET "https://localhost:9200/_plugins/_ml/mcp/sse?append_to_base_url=true" \
-H "Accept: text/event-stream" \
-H "Authorization: Basic $(echo -n 'username:password' | base64)"
SSE response format
The server sends events in the standard SSE format:
event: event_type
data: {"key": "value"}
id: unique_event_id
retry: 5000
Event types
Event Type | Description | Data Format |
---|---|---|
connection | Session establishment confirmation | Session metadata |
tool_list | Available tools information | Array of tool definitions |
tool_result | Tool execution results | Execution output and metadata |
error | Error notifications | Error details and context |
heartbeat | Keep-alive signal | Timestamp |
close | Session termination | Closure reason |
Example responses
Session establishment
event: connection
data: {"session_id": "session-abc123", "server_version": "0.7.0", "connected_at": "2024-01-01T12:00:00Z", "timeout": 300}
id: conn-001
Tool discovery
event: tool_list
data: {"tools": [{"name": "document_search", "description": "Search documents", "parameters": {...}}, {"name": "text_analyzer", "description": "Analyze text", "parameters": {...}}], "total": 2}
id: tools-001
Tool execution result
event: tool_result
data: {"tool": "document_search", "execution_id": "exec-456", "result": {"matches": [{"title": "Document 1", "score": 0.95}], "total": 1}, "execution_time_ms": 250, "status": "completed"}
id: result-001
Error notification
event: error
data: {"error_type": "ToolExecutionError", "message": "Tool 'invalid_tool' not found", "details": {"requested_tool": "invalid_tool", "available_tools": ["document_search", "text_analyzer"]}, "timestamp": "2024-01-01T12:00:30Z"}
id: error-001
Heartbeat
event: heartbeat
data: {"timestamp": "2024-01-01T12:00:45Z", "session_active": true}
id: heartbeat-001
Session management
Session lifecycle
- Connection: Client establishes SSE connection
- Authentication: Server validates credentials
- Discovery: Server sends available tools list
- Active: Session is ready for tool interactions
- Timeout/Close: Session ends due to timeout or explicit closure
Session parameters
When a session is established, the server responds with session metadata:
{
"session_id": "session-abc123",
"server_version": "0.7.0",
"connected_at": "2024-01-01T12:00:00Z",
"timeout": 300,
"capabilities": [
"tool_execution",
"real_time_results",
"error_reporting"
],
"rate_limits": {
"messages_per_minute": 60,
"concurrent_executions": 5
}
}
Client implementation examples
JavaScript/Browser
const eventSource = new EventSource('/_plugins/_ml/mcp/sse', {
headers: {
'Authorization': 'Basic ' + btoa('username:password')
}
});
eventSource.addEventListener('connection', (event) => {
const sessionData = JSON.parse(event.data);
console.log('Connected to session:', sessionData.session_id);
});
eventSource.addEventListener('tool_result', (event) => {
const result = JSON.parse(event.data);
console.log('Tool result:', result);
});
eventSource.addEventListener('error', (event) => {
const error = JSON.parse(event.data);
console.error('MCP Error:', error.message);
});
// Close connection when done
// eventSource.close();
Python
import requests
import json
def handle_sse_stream():
url = "https://localhost:9200/_plugins/_ml/mcp/sse?append_to_base_url=true"
headers = {
'Accept': 'text/event-stream',
'Authorization': 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' # base64 encoded
}
response = requests.get(url, headers=headers, stream=True, verify=False)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = json.loads(line[6:]) # Remove 'data: ' prefix
print(f"Received: {data}")
handle_sse_stream()
Error handling
Connection errors
Status Code | Description | Action |
---|---|---|
401 | Authentication failed | Check credentials |
403 | Insufficient permissions | Verify user roles |
429 | Rate limit exceeded | Implement backoff strategy |
503 | Service unavailable | Retry with exponential backoff |
Stream errors
event: error
data: {"error_type": "ConnectionError", "message": "Session timeout", "retry_after": 30}
id: error-timeout
Reconnection strategy
Implement automatic reconnection with exponential backoff:
function connectWithRetry(retryCount = 0) {
const eventSource = new EventSource('/_plugins/_ml/mcp/sse');
eventSource.onerror = (error) => {
eventSource.close();
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000);
setTimeout(() => connectWithRetry(retryCount + 1), delay);
};
}
Best practices
- Connection management: Always close SSE connections when no longer needed
- Error handling: Implement robust error handling and reconnection logic
- Rate limiting: Respect server rate limits to avoid disconnection
- Heartbeat monitoring: Monitor heartbeat events to detect connection issues
- Resource cleanup: Properly clean up event listeners and connections