MCP server

Let AI agents operate Sockudo through the Model Context Protocol with scoped tokens, audited tools, resources, and prompts.

8 min read
View .mdEdit on GitHub

Sockudo ships a Model Context Protocol (MCP) server so agents such as Claude can inspect and operate a deployment through a typed, permissioned tool surface instead of hand-built HTTP calls. Use it when you want an agent to debug channels, triage incidents, read history, or publish events while you keep control over exactly what it may touch.

The protocol layer is the official rmcp SDK; Sockudo adds signed API access, scopes, tools, resources, and prompts.

How it works

The MCP tools are a thin layer over the public HTTP API. Every tool call is turned into a signed HTTP API request and runs through the same validation, idempotency, rate limits, metrics, feature gates, and role restrictions as any external caller. Tool results are the documented HTTP API response shapes, so anything you know about the HTTP API applies.

Agent
MCP endpoint
Sockudo API router
1tools/call with Bearer token
Scope check, rate limit, app allow-list
2Signed HTTP API request
3JSON response
4Tool result and structuredContent
sequenceDiagram
    participant A as Agent
    participant M as MCP endpoint
    participant R as Sockudo API router
    A->>M: tools/call with Bearer token
    Note over M: Scope check, rate limit, app allow-list
    M->>R: Signed HTTP API request
    R-->>M: JSON response
    M-->>A: Tool result and structuredContent

Two deployment shapes share the same code:

ShapeTransport to SockudoMCP transportUse when
Embedded (sockudo binary, mcp feature)In-process: the server drives its own API router with self-signed requestsStreamable HTTP on /mcp (shared or dedicated port)Hosted agents, shared team access, production
Standalone (sockudo-mcp binary)Signed HTTP to a remote deploymentstdio or Streamable HTTPClaude Desktop, Claude Code, local IDEs

Enable the embedded server

  1. Build with the mcp feature (it is also part of the full feature set):

    Terminal window
    cargo build -p sockudo --release --features "v2,mcp,redis,postgres"
  2. Add an [mcp] section with at least one token:

    config.toml
    [mcp]
    enabled = true
    path = "/mcp"
    # port = 6100 # optional dedicated listener (host defaults to the server host)
    allowed_hosts = [] # empty = accept any Host (fine behind a trusted proxy)
    allowed_origins = [] # browser origins; empty disables Origin checks
    rate_limit_per_minute = 600 # per token; 0 disables
    request_timeout_ms = 30000
    session_ttl_seconds = 1800
    [[mcp.tokens]]
    name = "ops-agent"
    token = "${SOCKUDO_MCP_OPS_TOKEN}" # >= 16 chars; use env interpolation
    scopes = ["read", "write"]
    apps = ["*"]
    [[mcp.tokens]]
    name = "readonly-dashboard"
    token = "${SOCKUDO_MCP_RO_TOKEN}"
    scopes = ["read"]
    apps = ["app-1"]
  3. Start Sockudo and send an initialize request to confirm the endpoint answers:

    Terminal window
    curl -sS http://127.0.0.1:6001/mcp \
    -H "Authorization: Bearer $SOCKUDO_MCP_OPS_TOKEN" \
    -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" \
    -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
  4. Register the endpoint with your agent (see Connect a client).

Configuration reference

KeyDefaultMeaning
enabledfalseServe MCP. Requires the mcp Cargo feature.
path"/mcp"URL path of the Streamable HTTP endpoint.
hostunsetBind host for a dedicated listener; defaults to the server host.
portunsetDedicated MCP port. When unset, MCP shares the main HTTP listener.
allowed_hosts[]Allowed Host authorities (DNS-rebinding protection). Empty accepts any host.
allowed_origins[]Allowed browser origins. Empty disables Origin validation.
allow_anonymousfalseAccept unauthenticated requests with anonymous_scopes. Development only.
anonymous_scopes["read"]Scopes granted to anonymous callers.
tokens[]Bearer token principals (name, token, scopes, apps).
request_timeout_ms30000Per-tool upstream timeout.
max_body_bytes1048576Maximum MCP POST body size (minimum 1024).
session_ttl_seconds1800Idle session lifetime for session-based protocol versions.
rate_limit_per_minute600Per-token tool and resource call budget. 0 disables.
disabled_tools[]Tool names to hide entirely.
instructionsunsetExtra text appended to the MCP server instructions.

Each [[mcp.tokens]] entry takes a unique name (used in audit logs), a token of at least 16 characters, scopes (default ["read"]), and apps (default ["*"]).

Startup validation fails when:

  • enabled = true and there are no tokens, unless allow_anonymous = true.
  • path is not an absolute path, or shadows a Sockudo API route (/apps, /app, /up, /live, /usage, /stats, /operator, /accept-traffic, /metrics) while sharing the main listener.
  • port equals the main HTTP port or the metrics port.
  • A token name is empty or duplicated, a token is shorter than 16 characters, or a scope is not one of read, write, admin.

Tokens from the environment

MCP_TOKEN, MCP_TOKEN_NAME, MCP_TOKEN_SCOPES, and MCP_TOKEN_APPS add a token without touching the file. The name defaults to env, scopes to read,write, and apps to *; an existing file token with the same name is replaced. Every other [mcp] key has an MCP_* override; see Environment variables.

Terminal window
MCP_ENABLED=true \
MCP_TOKEN="$(openssl rand -hex 24)" \
MCP_TOKEN_NAME=ops-agent \
MCP_TOKEN_SCOPES=read,write \
MCP_TOKEN_APPS=app-1 \
sockudo --config config.toml

Connect a client

Clients authenticate with Authorization: Bearer <token>. A missing or invalid token is rejected before MCP processing with HTTP 401 and a JSON body:

{ "error": "unauthorized", "message": "invalid bearer token" }

Claude Code:

Terminal window
claude mcp add --transport http sockudo https://rt.example.com/mcp \
--header "Authorization: Bearer $SOCKUDO_MCP_OPS_TOKEN"

Claude API (MCP connector):

{
"mcp_servers": [{ "type": "url", "url": "https://rt.example.com/mcp", "name": "sockudo",
"authorization_token": "<token>" }],
"tools": [{ "type": "mcp_toolset", "mcp_server_name": "sockudo" }]
}

For interactive exploration, point npx @modelcontextprotocol/inspector at /mcp with the same Authorization header.

Standalone binary

sockudo-mcp runs outside the server and talks to a remote deployment over signed HTTP. Use it for desktop agents and IDEs, where stdio is the natural transport.

Terminal window
cargo install --path crates/sockudo-mcp --features cli
# stdio for Claude Desktop / Claude Code
sockudo-mcp --url https://rt.example.com --app app-1:key:secret --scopes read,write
claude mcp add sockudo -- sockudo-mcp --url https://rt.example.com --app app-1:key:secret
# Streamable HTTP with tokens
sockudo-mcp --transport http --listen 127.0.0.1:6100 \
--token 'ops/read+write=<16+ char token>' --url https://rt.example.com --app app-1:key:secret \
--metrics-url http://rt.example.com:9601/metrics
FlagEnvDefaultMeaning
--urlSOCKUDO_URLhttp://127.0.0.1:6001Base URL of the Sockudo HTTP API (may include a path prefix).
--appSOCKUDO_MCP_APPSnoneapp_id:app_key:app_secret; repeatable or comma-separated.
--app-id, --app-key, --app-secretSOCKUDO_APP_ID, SOCKUDO_APP_KEY, SOCKUDO_APP_SECRETnoneSingle-app convenience form.
--transportSOCKUDO_MCP_TRANSPORTstdiostdio or http.
--listenSOCKUDO_MCP_LISTEN127.0.0.1:6100Listen address for --transport http.
--pathSOCKUDO_MCP_PATH/mcpURL path for --transport http.
--tokenSOCKUDO_MCP_TOKENSnonetoken, name=token, or name/scope+scope=token; repeatable or comma-separated.
--scopesSOCKUDO_MCP_SCOPESread,writeScopes for stdio and for tokens without explicit scopes.
--allow-anonymousSOCKUDO_MCP_ALLOW_ANONYMOUSoffServe HTTP without authentication (development only).
--metrics-urlSOCKUDO_METRICS_URLnonePrometheus URL; enables sockudo_server_metrics.
--timeout-msSOCKUDO_MCP_TIMEOUT_MS30000Per-request timeout.
--allowed-hostsSOCKUDO_MCP_ALLOWED_HOSTSemptyAllowed Host authorities for HTTP.
--allowed-originsSOCKUDO_MCP_ALLOWED_ORIGINSemptyAllowed browser origins for HTTP.
--disable-toolSOCKUDO_MCP_DISABLED_TOOLSnoneTools to hide; repeatable or comma-separated.
--instructionsSOCKUDO_MCP_INSTRUCTIONSnoneExtra text appended to the server instructions.

Scopes and safety

Scopes are cumulative: admin implies write, and write implies read.

ScopeGrantsExamples
readInspectionsockudo_list_channels, sockudo_get_history, sockudo_server_stats, sockudo_server_metrics
writePublishing and mutation (implies read)sockudo_trigger_event, sockudo_update_message, sockudo_publish_annotation, sockudo_push_publish, sockudo_sign_channel_auth
adminDestructive and connection-affecting operations (implies write)sockudo_terminate_user_connections, sockudo_reset_history, sockudo_purge_history, sockudo_revoke_capability_tokens, sockudo_replay_push_dead_letter
  • tools/list only returns tools the token may call. Calling a tool above the token’s scope returns JSON-RPC error -32003 with reason: "missing_scope" and required_scope.
  • Tokens carry an app allow-list; requests for other apps fail with -32003 and reason: "app_not_allowed".
  • When a token exceeds rate_limit_per_minute, calls fail with -32004 and retry_after_seconds. The embedded limiter is in-memory, so each node enforces its own budget.
  • App secrets never leave the server. sockudo_list_apps and sockudo_get_app return keys and sanitized policy only; webhook headers are redacted.
  • Every tool call emits an audit log line on target sockudo_mcp::audit with principal, tool, app, channel, outcome, and latency.

Every admin tool requires confirm: true; calls without it fail argument validation before any request is made. sockudo_reset_history, sockudo_purge_history, and sockudo_reset_presence_history also require a reason, which is forwarded to the server. sockudo_revoke_capability_tokens accepts an optional reason recorded with the revocation.

tools/call: reset a history stream
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "sockudo_reset_history",
"arguments": {
"app_id": "app-1",
"channel": "chat:room-1",
"reason": "stream marked reset_required after storage incident",
"confirm": true
}
}
}

Errors an agent can act on

Protocol-level problems (bad arguments, missing scope, rate limits) are JSON-RPC errors. Failures from Sockudo itself come back as tool results with isError: true and a machine-readable envelope, so the agent can read the server’s code and error and recover:

isError result for an upstream 4xx
{
"error": "upstream_error",
"message": "<server error message>",
"details": {
"http_status": 404,
"upstream": { "...": "the server's JSON error body, unchanged" }
}
}

Other envelope error values are unknown_app, missing_app_id, transport_error, timeout, invalid_request, and internal_error.

Tools

AreaTools
Discovery and serversockudo_list_apps, sockudo_get_app, sockudo_server_info, sockudo_server_health, sockudo_server_accept_traffic, sockudo_server_stats, sockudo_server_usage, sockudo_server_metrics
Channelssockudo_list_channels, sockudo_get_channel, sockudo_get_presence_users
Publishsockudo_trigger_event, sockudo_trigger_batch_events
Durable historysockudo_get_history, sockudo_get_history_state, sockudo_reset_history, sockudo_purge_history
Versioned messagessockudo_get_message, sockudo_list_message_versions, sockudo_update_message, sockudo_delete_message, sockudo_append_message
Annotationssockudo_list_annotations, sockudo_publish_annotation, sockudo_delete_annotation
Presence historysockudo_get_presence_history, sockudo_get_presence_history_state, sockudo_get_presence_snapshot, sockudo_reset_presence_history
Connections and tokenssockudo_terminate_user_connections, sockudo_force_reconnect_user, sockudo_revoke_capability_tokens
Pushsockudo_push_publish, sockudo_push_batch_publish, sockudo_push_publish_status, sockudo_list_push_devices, sockudo_get_push_device, sockudo_list_push_channel_subscriptions, sockudo_list_push_subscription_channels, sockudo_list_push_dead_letters, sockudo_replay_push_dead_letter, sockudo_delete_push_scheduled_job, sockudo_list_push_credentials, sockudo_list_push_templates, sockudo_get_push_template
Auth helperssockudo_sign_channel_auth, sockudo_sign_user_auth, sockudo_verify_webhook_signature

Start an agent session with sockudo_list_apps to discover valid app_id values, then sockudo_server_info, which reports the server version, transport, tool count, and the caller’s own scopes and apps:

sockudo_server_info result (abridged)
{
"mcp_server": {
"name": "sockudo",
"version": "5.2.0",
"transport": "in-process",
"tools": 48,
"request_timeout_ms": 30000,
"rate_limited": true
},
"principal": { "name": "ops-agent", "scopes": ["read", "write"], "apps": "*" }
}

Hide tools with disabled_tools = ["sockudo_purge_history"]. Tools that hit a feature the server does not enable (for example push without the push feature) return the server’s feature_disabled or 404 error rather than failing at startup. sockudo_server_stats and sockudo_server_usage require http_api.usage_enabled on the server.

Resources and prompts

Resources use the sockudo:// scheme:

ResourceContents
sockudo://server/info, server/health, server/statsServer description, health check, operator stats
sockudo://apps, apps/{app_id}Apps visible to the token and one app’s sanitized policy
sockudo://apps/{app_id}/channelsOccupied channels for an app
sockudo://apps/{app_id}/channels/{channel}One channel, with /history, /presence, and /messages/{message_serial} sub-resources
sockudo://docs/http-api, docs/channels, docs/operationsEmbedded reference docs for the agent

Prompts sockudo_debug_channel, sockudo_incident_triage, sockudo_design_realtime_feature, and sockudo_audit_app_security walk an agent through common workflows. Argument completion is available for app_id and channel.

Observability

Prometheus families (with the configured prefix):

MetricLabelsMeaning
mcp_requests_totalport, outcomeProtocol requests by outcome (tools_call, resources_read, rate_limited, unauthorized, …).
mcp_tool_calls_totalport, tool, outcomeTool calls by tool and outcome (ok, upstream_4xx, forbidden_scope, timeout, …).
mcp_tool_latency_msport, toolTool execution latency.

Tool outcomes are ok, invalid_arguments, forbidden_scope, forbidden_app, unauthorized, upstream_4xx, upstream_5xx, timeout, unknown_app, transport_error, internal_error, and unknown_tool. A rising forbidden_scope count usually means an agent is trying tools above its grant; a rising upstream_4xx count usually means bad arguments the agent is not correcting.

Testing

  • cargo test -p sockudo-mcp --all-features runs protocol, signing, catalog, and Streamable HTTP transport tests; cargo test -p sockudo --features mcp mcp:: drives the in-process transport through the real API middleware.
  • make mcp-smoke builds both binaries, starts a scratch server from tests/mcp/config.toml, and runs tests/mcp/smoke_http.py (embedded endpoint, admin and read-only tokens) and tests/mcp/smoke_stdio.py (standalone binary over stdio).
  • For interactive checks use npx @modelcontextprotocol/inspector against /mcp with the Authorization: Bearer header, or register the endpoint in Claude Code and call sockudo_server_info.

Performance notes

  • The embedded transport never touches a socket: requests are signed and dispatched to the router with tower::Service::oneshot. Cost per call is one HMAC-SHA256, one MD5 for POST bodies, and the normal handler work.
  • tools/list responses are prebuilt once per scope combination and served as an Arc clone.
  • Responses are passed through as the server’s JSON bytes; only object bodies are parsed once more to populate structuredContent.
  • Sessions are managed by rmcp with idle expiry (session_ttl_seconds); the 2026-07-28 protocol revision is served statelessly.

Next steps