Rust MCP Analytics installation

The Rust SDK is experimental and unsupported

posthog::mcp is experimental and not officially supported. Its API, its options, and the $mcp_* events it captures may change in any posthog release.

Try it, and report bugs or send patches to posthog-rs. Don't build production reporting on it yet.

posthog::mcp ships inside the posthog crate, behind the mcp feature. It instruments servers built on rmcp, the official Rust MCP SDK, over stdio and Streamable HTTP. It serves both the 2025-11-25 and 2026-07-28 protocol revisions.

You need Rust 1.88+, rmcp 3.7 or later, posthog 1.0 or later, and a PostHog project token. Dispatching MCP requests without an rmcp server? See Custom dispatchers.

Learn more

The wizard adds the crate with its mcp feature and wraps your server with posthog::mcp::instrument for you. To install by hand, follow the steps below.

  1. Install the crate

    Required
    Terminal
    cargo add posthog@1 --features mcp

    The mcp feature enables rmcp's server feature and the async client. The snippets on this page also need tokio with its macros and rt-multi-thread features, and rmcp with transport-io for stdio or transport-streamable-http-server for HTTP.

  2. Wrap your server

    Required

    Pass your ServerHandler and a shared client to posthog::mcp::instrument, then serve the wrapped server as usual:

    Rust
    use std::sync::Arc;
    use rmcp::ServiceExt;
    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = std::env::var("POSTHOG_PROJECT_TOKEN")?;
    let posthog = Arc::new(
    posthog::client((token.as_str(), "https://us.i.posthog.com")).await, // or https://eu.i.posthog.com
    );
    let server = posthog::mcp::instrument(NotesServer, posthog.clone());
    server.serve(rmcp::transport::stdio()).await?.waiting().await?;
    posthog.shutdown().await;
    Ok(())
    }

    NotesServer is your own rmcp server. The wrapped server answers every request as yours would. It only adds the analytics arguments to your tools, a conversation handle to tool results, and, when you turn it on, the get_more_tools tool.

    For Streamable HTTP, hand the wrapped server to StreamableHttpService in place of yours:

    Rust
    use std::sync::Arc;
    use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
    use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
    let server = posthog::mcp::instrument(NotesServer, posthog.clone());
    let service = StreamableHttpService::new(
    move || Ok(server.clone()),
    Arc::new(LocalSessionManager::default()),
    StreamableHttpServerConfig::default(),
    );
    // Mount `service` on your HTTP router, such as axum's `Router::new().nest_service("/mcp", service)`.

    Your server must implement Clone. Each clone of the wrapped server serves its own connection and session. Clones share everything else.

  3. Send queued events on shutdown

    Required

    The posthog crate sends events in the background. Call posthog.shutdown().await before the process exits, as above. On a server you stop with a signal, call it from your shutdown handler.

  4. Check your first events

    Required

    Connect an agent to your server and call a tool. Then run this query in the SQL editor, or through the execute-sql tool of the PostHog MCP server:

    SQL
    SELECT
    timestamp,
    event,
    properties.$mcp_tool_name AS tool,
    properties.$mcp_is_error AS failed
    FROM events
    WHERE startsWith(event, '$mcp_')
    AND timestamp > now() - INTERVAL 1 HOUR
    ORDER BY timestamp DESC
    LIMIT 20

    You should see a $mcp_tool_call row for the tool you called. Events can take a minute to arrive. No rows? See Troubleshooting. See the event reference for every property.

For a runnable server, see examples/mcp_server.rs. The example reads the token from POSTHOG_API_KEY, so pass it your POSTHOG_PROJECT_TOKEN:

Terminal
POSTHOG_API_KEY="$POSTHOG_PROJECT_TOKEN" cargo run --example mcp_server --features mcp

Configuration

instrument uses the default options. To change them, build McpOptions with McpOptionsBuilder and wrap your server through McpAnalytics:

Rust
use posthog::mcp::{McpAnalytics, McpOptionsBuilder};
let options = McpOptionsBuilder::default()
.missing_capability_tool("get_more_tools")
.capture_responses(false)
.build()?;
let server = McpAnalytics::new(posthog.clone(), options).instrument(NotesServer);

OptionDefaultWhat it does
context(bool)trueAdds a required context argument to capture agent intent. The SDK removes it before your tool runs.
context_description(text)–Replaces the context argument's description. Keep the default's instruction to leave out personal details.
intent_fallback(callback)–Fn(&RequestInfo) -> Option<String>. Supplies intent when the agent sends no context. Captured with $mcp_intent_source: "inferred".
capture_model(bool)trueCaptures the calling model from the request _meta, or from a required llm_model argument the SDK adds.
model_description(text)–Replaces the llm_model argument's description.
conversation_id(bool)trueAdds an optional conversation_id argument to group calls across requests. When the SDK mints a handle, it appends a last {"conversation_id": ...} text block to the result.
identify(callback)–Fn(&RequestInfo) -> Option<Identity>. Maps a request to a person and groups. See Identify the caller.
event_options(callback)–Fn(&RequestInfo) -> Option<serde_json::Map<String, Value>>. Sets event options on each request's events.
missing_capability_tool(name)offAdds the get_more_tools virtual tool under this name. A blank name uses get_more_tools.
exception_autocapture(bool)trueSends a $exception event for each failed tool call.
capture_parameters(bool)trueCaptures the tool arguments as $mcp_parameters.
capture_responses(bool)trueCaptures the tool result as $mcp_response. A failed call's error text is captured either way.
before_send(hook)–FnMut(Event) -> Option<Event>. Changes or drops each MCP event after redaction. Dropping a $mcp_tool_call also drops its $exception.

A tool that declares its own context, llm_model, or conversation_id argument keeps it. A tool whose input schema uses $ref, allOf, anyOf, or oneOf at the top level gets no added arguments, so the SDK captures no intent or model from its arguments.

The SDK logs its warnings through tracing, never to stdout. On a stdio server, point your tracing subscriber at stderr, because stdout carries the protocol.

Event options

Set event options, such as cookieless_mode or process_person_profile, with McpOptionsBuilder::event_options. Its callback returns options for each request's events. In the manual API, ToolCallRequest::event_option(key, value) sets an option on one call and wins over the callback:

Rust
use posthog::mcp::{McpOptionsBuilder, ToolCallRequest};
let options = McpOptionsBuilder::default()
.event_options(|_request| {
let mut options = serde_json::Map::new();
options.insert("cookieless_mode".into(), true.into());
Some(options)
})
.build()?;
let call = ToolCallRequest::new("search_docs", None).event_option("cookieless_mode", true)?;

Identify the caller

The identify callback receives a RequestInfo with the JSON-RPC method, the tool name and arguments, the request _meta, and, on HTTP, the request's http::request::Parts. Read the user your HTTP middleware attached to the request extensions:

Rust
use posthog::mcp::{Identity, McpAnalytics, McpOptionsBuilder};
/// What your HTTP auth middleware inserts into the request extensions.
#[derive(Clone)]
struct AuthenticatedUser {
id: String,
plan: String,
org_id: String,
}
let options = McpOptionsBuilder::default()
.identify(|request| {
let user = request.http?.extensions.get::<AuthenticatedUser>()?;
Some(
Identity::new(user.id.clone())
.with_property("plan", user.plan.clone())
.with_group("organization", user.org_id.clone()),
)
})
.build()?;
let server = McpAnalytics::new(posthog.clone(), options).instrument(NotesServer);

with_property values go out as $set on every MCP event, and with_group values as $groups. Without an identity, events are anonymous and create no person profile. Never put a raw credential, such as an Authorization header, in a property: person properties aren't redacted.

Sessions

Every event has a $session_id. See session resolution. Stateless HTTP has no transport session, so the SDK uses conversation IDs. A client that ignores the handle gets a new session per request, so use identify to group those calls by user.

Intent from client metadata

When the client sends _meta["io.modelcontextprotocol/aiInvocation"].userIntent, the SDK captures it as $mcp_intent with $mcp_intent_source: "client_metadata". It takes priority over the context argument, and the intent fallback doesn't run.

Report missing capabilities

Set missing_capability_tool to give agents a get_more_tools tool to report what your server lacks. The SDK answers the call itself, so your handlers never see it.

The SDK skips its own tool when your server has one of the same name. It finds yours through get_tool, which #[tool_handler] servers implement. A server without get_tool should give the virtual tool a name its own tools don't use.

Custom dispatchers

For a server that isn't an rmcp ServerHandler, such as a gateway or your own JSON-RPC router, use the manual API on McpAnalytics. It sends the tool call events: $mcp_tool_call, $exception, $mcp_unknown_tool, and $mcp_input_required. It doesn't send $mcp_tools_list or $mcp_initialize.

Create one McpAnalytics with McpAnalytics::new(posthog.clone(), options) and share it. When you answer tools/list, pass your tools through list_tools, which adds the analytics arguments. For each tools/call, start the call with the arguments as the agent sent them, run the tool with the arguments the SDK hands back, and finish the call:

Rust
use posthog::mcp::{
McpAnalytics, ToolCallError, ToolCallRequest, ToolRegistration, TransportSession,
};
use rmcp::model::{CallToolResult, JsonObject, Tool};
/// Answers `tools/list` with your tools plus the analytics arguments.
fn list_tools(analytics: &McpAnalytics, my_tools: Vec<Tool>) -> Vec<Tool> {
analytics.list_tools(my_tools)
}
/// Answers one `tools/call` for a tool you have, on a session with an id.
async fn call_tool(
analytics: &McpAnalytics,
tool: Tool,
arguments: Option<JsonObject>, // as the agent sent them
mcp_session_id: String,
) -> Result<CallToolResult, std::io::Error> {
let call = analytics.start_tool_call(
ToolCallRequest::new(tool.name.to_string(), arguments)
.tool(ToolRegistration::Registered(tool))
.transport_session(TransportSession::Id(mcp_session_id)),
);
match run_tool(call.arguments()).await {
// Return what `complete` gives back: it may carry a conversation handle.
Ok(result) => Ok(call.complete(result)),
Err(error) => {
call.fail(ToolCallError::new(&error).error_type("timeout"));
Err(error)
}
}
}
/// Your tool's own code, given the arguments without the analytics ones.
async fn run_tool(arguments: Option<&JsonObject>) -> Result<CallToolResult, std::io::Error> {
todo!("your tool's code, reading {arguments:?}")
}

std::io::Error stands in for your own error type. ToolCallError::new takes any std::error::Error.

  • call.arguments() no longer holds the context, llm_model, or conversation_id arguments, when the SDK knows it added them: the tool is ToolRegistration::Registered, or it went through list_tools earlier.
  • ToolRegistration::NotRegistered sends $mcp_unknown_tool instead of a tool call. Use ToolRegistration::NoRegistry when you can't tell. Then the SDK removes the analytics arguments only for tools it saw in list_tools.
  • ToolCallRequest also takes the request _meta with .meta(), the HTTP request with .http(), your server's Implementation with .server(), the arrival time with .started_at(), and event options with .event_option().
  • TransportSession::Id groups requests that share a session ID. For a one-client connection, create one Connection::new() per connection and pass TransportSession::Connection. Without a transport session, the call is a stateless request.
  • On a 2026-07-28 round, call call.input_required(&round) to send $mcp_input_required. The retry that completes the call is a call of its own.
  • ToolCallError::new labels the failure with the error's type name. Use .error_type(...) to set $mcp_error_type yourself.

The manual API never answers get_more_tools. Only instrument does.

Troubleshooting

SymptomCause and fix
No events at allCheck that the process calls posthog.shutdown().await before it exits, because queued events are lost without it. Check the token is the project token (phc_...) and the host matches your region: https://us.i.posthog.com or https://eu.i.posthog.com.
A stdio client can't connect, or reports invalid JSONSomething writes to stdout, which carries the protocol. Send logs and your tracing subscriber to stderr.

Limits

The Rust SDK doesn't yet have:

  • Resource and prompt events
  • Task handling
  • $identify or a custom-event handle. Call capture on your posthog client instead

Still have questions?

Was this page useful?