Skip to main content
Version: 0.7.0

MCP SSE session

Introduced 0.7.0

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

HeaderValueRequiredDescription
Accepttext/event-streamYesSpecifies SSE content type
Cache-Controlno-cacheNoPrevents caching of the stream
Connectionkeep-aliveNoMaintains persistent connection

Query parameters

ParameterTypeDescriptionDefault
append_to_base_urlBooleanFor Python clients, appends parameters to base URLfalse
session_idStringCustom session identifierAuto-generated
timeoutNumberSession timeout in seconds300

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 TypeDescriptionData Format
connectionSession establishment confirmationSession metadata
tool_listAvailable tools informationArray of tool definitions
tool_resultTool execution resultsExecution output and metadata
errorError notificationsError details and context
heartbeatKeep-alive signalTimestamp
closeSession terminationClosure 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

  1. Connection: Client establishes SSE connection
  2. Authentication: Server validates credentials
  3. Discovery: Server sends available tools list
  4. Active: Session is ready for tool interactions
  5. 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 CodeDescriptionAction
401Authentication failedCheck credentials
403Insufficient permissionsVerify user roles
429Rate limit exceededImplement backoff strategy
503Service unavailableRetry 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

  1. Connection management: Always close SSE connections when no longer needed
  2. Error handling: Implement robust error handling and reconnection logic
  3. Rate limiting: Respect server rate limits to avoid disconnection
  4. Heartbeat monitoring: Monitor heartbeat events to detect connection issues
  5. Resource cleanup: Properly clean up event listeners and connections