Skip to content

feat(mcp): PostHog MCP analytics SDK for Python (posthog.mcp)#691

Merged
lucasheriques merged 16 commits into
mainfrom
posthog-code/mcp-analytics-python-sdk
Jun 26, 2026
Merged

feat(mcp): PostHog MCP analytics SDK for Python (posthog.mcp)#691
lucasheriques merged 16 commits into
mainfrom
posthog-code/mcp-analytics-python-sdk

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

What

Adds posthog.mcp — a Python SDK for PostHog MCP analytics, the Python sibling of the TypeScript @posthog/mcp package. This is the #1 "what to prioritize next" item on the MCP analytics mega-issue, PostHog/posthog#64016: MCP analytics was TS-only, but many MCP servers are Python.

from posthog import Posthog
from posthog.mcp import instrument
from mcp.server.fastmcp import FastMCP

posthog = Posthog("phc_...", host="https://us.i.posthog.com")
server = FastMCP("my-server")
analytics = instrument(server, posthog)   # one line

Install: pip install posthog[mcp].

How it works

Packaged as a submodule of posthog (mirroring posthog.ai), guarded by an optional mcp extra so import posthog never requires mcp. The wire format is byte-identical to @posthog/mcp's constants.ts, so the existing MCP analytics dashboard ingests Python-server data with zero backend changes.

instrument(server, posthog_client) supports every common Python MCP server:

  • FastMCP and the low-level Server from the official modelcontextprotocol/python-sdk (the mcp package)
  • jlowin's standalone FastMCP 2.0 (the separate fastmcp package)
  • PostHogMCP (a Client subclass) for custom/edge dispatchers with no server object

Captures $mcp_tool_call, $mcp_tools_list, $mcp_initialize (lazy), $identify, $exception, and $mcp_missing_capability. Features: agent-intent capture via an injected context arg, identify, before_send, event_properties, report_missing (get_more_tools), and conversation_id.

Implementation notes:

  • FastMCP is instrumented via two central seams (ToolManager.call_tool + the ListToolsRequest handler) rather than per-tool wrapping — late-registered tools are covered automatically.
  • jlowin's FastMCP 2.0 routes through the low-level adapter (its _mcp_server subclasses the official Server); it validates against the function signature and rejects unexpected kwargs, so the injected context/conversation_id are stripped before dispatch.
  • UUIDv7 implemented inline (no new dependency); $exception_list reuses posthog.exception_utils.
  • $mcp_initialize is emitted lazily from client_params because the Python mcp SDK handles initialize in the session layer, not via request_handlers.
  • On a raw low-level Server, context/conversation_id are injected as optional schema properties (that schema is also the validation schema) so a call omitting them is never rejected.

Testing

  • 56 unit + end-to-end tests (posthog/test/mcp/), driving the real mcp / fastmcp SDK seams with a fake capture client. ruff + mypy clean.
  • Dogfooded against project 2: a demo server (examples/mcp_analytics_demo.py) sent the full $mcp_* event set; verified the events ingest with correct intent, error flag, and $mcp_source and are readable by the dashboard.

Links

Status

Alpha (minor changeset). Parity note: the TS instrument() does not emit resources/prompts events, so those are intentionally omitted here too.


Created with PostHog Code

Port the core of @posthog/mcp to Python as a posthog.mcp submodule: event
vocabulary, inline uuidv7 + FNV-1a ids, STDIO-safe logger, sanitization,
layered truncation, $mcp_* event building, $exception fan-out (reusing
posthog.exception_utils), and the sanitize->truncate->before_send->capture
sink. Adds the `mcp` optional extra. No server wrapping yet (M2).

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
…e (M2)

instrument(server, posthog_client) now wraps a FastMCP server by hooking two
central seams: ToolManager.call_tool (strip injected context before Pydantic
validation, time the call, capture $mcp_tool_call + $exception, re-raise) and
the ListToolsRequest handler ($mcp_tools_list + context-parameter injection).
$mcp_initialize is emitted lazily per session from client_params. Adds the
import guard, per-server state in a WeakKeyDictionary, session resolution with
an asyncio lock, identity dedup, and the custom-event handle.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
A runnable FastMCP server instrumented with posthog.mcp that emits the full
$mcp_* event set. Verified end-to-end against project 2: tool calls, intent,
error capture, initialize, identify, and a custom event all ingest correctly.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
instrument() now also wraps a low-level mcp.server.Server by hooking its public
request_handlers (CallToolRequest, ListToolsRequest). Errors are read from the
isError CallToolResult the low-level handler produces. context is injected as an
*optional* schema property there (the advertised schema is also the validation
schema) so a call omitting it is never rejected.

PostHogMCP is a posthog Client subclass for custom dispatchers with
capture_tool_call / capture_initialize / capture_tools_list /
capture_missing_capability + prepare_tool_list / prepare_tool_call, flowing
through the same pipeline. Shared tool-list helpers moved into instrumentation.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
reportMissing advertises the get_more_tools virtual tool in tools/list; calling
it emits $mcp_missing_capability (not $mcp_tool_call) and returns the canned
acknowledgement, across FastMCP, low-level Server, and PostHogMCP.

enableConversationId injects an optional conversation_id parameter, mints one
when the agent omits it, captures it as $mcp_conversation_id, and appends a
prompt-back asking the agent to echo it on later calls.

Parity note: the TS instrument() does not emit resources/prompts events, so
those are intentionally omitted here too.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@greptile-apps

greptile-apps Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "chore(mcp): add changeset for the Python..." | Re-trigger Greptile

Comment thread posthog/mcp/_instrumentation.py
Comment thread posthog/mcp/_intent.py
Comment thread posthog/test/mcp/test_fastmcp.py Outdated
Comment thread posthog/mcp/version.py Outdated
instrument() now also accepts a fastmcp.FastMCP (jlowin's standalone FastMCP
2.0), distinct from the official SDK's mcp.server.fastmcp.FastMCP. Its
_mcp_server is a subclass of the official low-level Server, so it routes through
the low-level adapter via its request_handlers seam — but FastMCP 2.0 validates
tool args against the function signature and rejects unexpected kwargs, so the
injected context/conversation_id are stripped before dispatch (the low-level
adapter is parameterized: strip + required-advisory for fastmcp 2.0, optional +
no-strip for a raw Server). Adds fastmcp to the test extra; tests skip if absent.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@lucasheriques

Copy link
Copy Markdown
Contributor Author

Added support for jlowin's standalone FastMCP 2.0 (the separate fastmcp package), in addition to the official SDK's FastMCP + low-level Server. instrument() now accepts all three (plus PostHogMCP for custom dispatchers).

Implementation: jlowin's FastMCP._mcp_server is a subclass of the official low-level Server, so it routes through the low-level adapter's request_handlers seam. The one wrinkle — FastMCP 2.0 validates tool args against the function signature and rejects unexpected kwargs — is handled by stripping the injected context/conversation_id before dispatch (the low-level adapter is now parameterized: strip + required-advisory for fastmcp 2.0, optional + no-strip for a raw Server). Covered by posthog/test/mcp/test_fastmcp_v2.py (56 tests total; skipped when fastmcp isn't installed).

@github-actions

github-actions Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-06-26 15:04:42 UTC
Duration: 529939ms

✅ All Tests Passed!

45/45 tests passed


Capture Tests

29/29 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields 512ms
Format Validation.Event Has Uuid 10007ms
Format Validation.Event Has Lib Properties 10006ms
Format Validation.Distinct Id Is String 10005ms
Format Validation.Token Is Present 10007ms
Format Validation.Custom Properties Preserved 10005ms
Format Validation.Event Has Timestamp 10006ms
Retry Behavior.Retries On 503 18017ms
Retry Behavior.Does Not Retry On 400 12003ms
Retry Behavior.Does Not Retry On 401 10006ms
Retry Behavior.Respects Retry After Header 16012ms
Retry Behavior.Implements Backoff 30017ms
Retry Behavior.Retries On 500 13007ms
Retry Behavior.Retries On 502 16010ms
Retry Behavior.Retries On 504 16009ms
Retry Behavior.Max Retries Respected 30016ms
Deduplication.Generates Unique Uuids 7000ms
Deduplication.Preserves Uuid On Retry 16014ms
Deduplication.Preserves Uuid And Timestamp On Retry 23016ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 16005ms
Deduplication.No Duplicate Events In Batch 10000ms
Deduplication.Different Events Have Different Uuids 10007ms
Compression.Sends Gzip When Enabled 10004ms
Batch Format.Uses Proper Batch Structure 10006ms
Batch Format.Flush With No Events Sends Nothing 5004ms
Batch Format.Multiple Events Batched Together 10004ms
Error Handling.Does Not Retry On 403 12007ms
Error Handling.Does Not Retry On 413 10008ms
Error Handling.Retries On 408 14011ms

Feature_Flags Tests

16/16 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 9501ms
Request Payload.Flags Request Uses V2 Query Param 10005ms
Request Payload.Flags Request Hits Flags Path Not Decide 10007ms
Request Payload.Flags Request Omits Authorization Header 10006ms
Request Payload.Token In Flags Body Matches Init 10006ms
Request Payload.Groups Round Trip 10005ms
Request Payload.Groups Default To Empty Object 10006ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 10005ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 10005ms
Request Payload.Disable Geoip Omitted Defaults To False 10006ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 10005ms
Request Lifecycle.No Flags Request On Init Alone 5003ms
Request Lifecycle.No Flags Request On Normal Capture 10506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 9509ms
Request Lifecycle.Mock Response Value Is Returned To Caller 10002ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 10508ms

@lucasheriques lucasheriques requested a review from pauldambra June 22, 2026 19:07
@lucasheriques lucasheriques marked this pull request as ready for review June 22, 2026 19:07
@lucasheriques lucasheriques requested a review from a team as a code owner June 22, 2026 19:07
The new posthog.mcp submodule adds public API surface; refresh the griffe
snapshot so the "Public API snapshot" CI check passes.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@greptile-apps

greptile-apps Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Reviews (2): Last reviewed commit: "chore(mcp): regenerate public API snapsh..." | Re-trigger Greptile

…ersation_id, loop leak

- Isolate analytics from the tool path: record_tool_call / record_tools_list /
  record_missing_capability swallow+log internally so a capture failure can never
  change what the tool returns or raises.
- Apply event_properties to $mcp_tools_list / $mcp_initialize / $mcp_missing_capability
  (previously only $mcp_tool_call), matching the TS fan-out.
- conversation_id: only stamp $mcp_conversation_id when the prompt-back was actually
  delivered (inject first, then capture; clear on error / non-injectable results) so
  no orphan ids; strip conversation_id from $mcp_parameters; handle FastMCP's
  (content, structured) tuple result so the prompt-back lands.
- fire_and_forget: reuse one daemon background loop for sync hosts instead of leaking
  a new event loop per call; log background-task exceptions; add drain_pending() +
  McpAnalytics.flush() to await in-flight events before shutdown (demo uses it).
- Bound initialized_sessions (FIFO, cap 1000) to stop a per-session memory leak.
- $mcp_tools_list now carries $mcp_is_error=False; fix stale "see M3" docstring.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
Comment thread posthog/mcp/__init__.py
@marandaneto

Copy link
Copy Markdown
Member

just an initial agent review before proper human review:

Blocking / high confidence findings

  1. flush() does not wait for sync background captures

    • fire_and_forget() stores concurrent.futures.Future when no event loop is running.
    • drain_pending() only awaits asyncio.Task.
    • This means PostHogMCP/sync custom dispatcher events can still be pending when users call
      flush() then shutdown(), causing dropped trailing events.
    • Files: posthog/mcp/instrumentation.py:59-87.
  2. conversation_id can break existing tools

    • Schema injection skips tools that already define conversation_id.
    • But dispatch still strips conversation_id from arguments, treating it as SDK-owned.
    • Also, if a tool owns context, the current strip logic skips stripping both context and
      conversation_id, so an injected conversation_id may be passed into a tool that doesn’t
      accept it.
    • Files: posthog/mcp/conversation_id.py:22-36, posthog/mcp/instrument_fastmcp.py:127-131,
      posthog/mcp/instrument_lowlevel.py:136-142.
    • I’d add tests for tools with real context, real conversation_id, and both.

Medium concerns

  1. Fragile dependency range

    • The implementation hooks private/internal MCP SDK seams like _tool_manager, _mcp_server,
      and request_handlers, but dependency is mcp>=1.26.0 with no upper bound.
    • I’d add an upper bound or document/test the supported MCP SDK versions.
  2. PostHogMCP requires installing mcp even though it looks usable for custom dispatchers

    • posthog.mcp.init imports/checks mcp before exporting PostHogMCP.
    • If PostHogMCP is meant to support non-official/custom dispatchers, move the import guard
      into instrument()/adapter paths.

@marandaneto marandaneto requested a review from a team June 23, 2026 07:36
@marandaneto

Copy link
Copy Markdown
Member

some comparison with the mcp node based impl.

1. tools/list capture is weaker than TypeScript

TypeScript captures:

  • $mcp_response with the returned tools
  • $mcp_duration_ms
  • $mcp_is_error
  • error event if the list handler throws
  • special error capture if zero tools are listed

Python currently records mostly:

  • $mcp_listed_tool_names
  • $mcp_parameters
  • $mcp_is_error = False

No response, no duration, no failure capture if original(req) raises.

This is probably the biggest dashboard parity gap.

2. $mcp_initialize is not equivalent

TypeScript wraps the actual initialize handler and captures request, response, and timing.

Python emits initialize lazily from prepare_request(), but prepare_request() only runs on tool
calls. So:

  • client that initializes + lists tools but never calls a tool may not emit $mcp_initialize
  • Python initialize has no real request params
  • no response
  • no duration
  • identity is not resolved from the initialize request itself

Some limitation may be unavoidable in Python MCP SDK, but Python should at least emit initialize
on first tools/list too, and document remaining differences.

3. Injected arg stripping is inconsistent

TypeScript strips injected context/conversation_id before the tool sees them.

Python FastMCP strips both only when _tool_owns_context(server, name) is false:

  if isinstance(arguments, dict) and not _tool_owns_context(server, name):
      call_arguments = {k: v for k, v in arguments.items() if k not in _INJECTED_KEYS}

That means a tool with a real context arg can also receive injected conversation_id, which is
wrong.

For raw low-level Python, injected args are intentionally left in place. That may be necessary
because the advertised schema is also validation schema, but it is different from JS and should
be explicitly tested/documented.

4. Low-level thrown exceptions are not captured like TS

TypeScript wraps execution with try/catch and captures failed tool events before rethrowing.

Python low-level assumes the MCP handler converts failures into CallToolResult(isError=True). If
a custom/low-level handler raises directly, Python skips $mcp_tool_call/$exception.

Worth wrapping original(req) in try/except anyway.

5. Idempotency/tracking key differs

TypeScript canonicalizes high-level servers to the underlying low-level server before storing
tracking state.

Python stores tracking against whatever object was passed to instrument(). For wrappers exposing
_mcp_server, instrumenting both wrapper and underlying server can create divergent tracking
state while only one wrapped closure is active.

Not common, but TS handles this more robustly.

6. flush() still misses sync background futures

Python added McpAnalytics.flush(), but drain_pending() only awaits asyncio.Task, not the
concurrent.futures.Future created for sync hosts. PostHogMCP sync captures can still be pending.

7. PostHogMCP unnecessarily requires mcp

JS PostHogMCP is useful for custom dispatchers. Python exports PostHogMCP, but importing
posthog.mcp first requires the official mcp package. If custom dispatcher support is real, the
import guard should move into instrument()/adapters.

…NSE, test dedup

- intent: resolve the missing-capability probe through
  resolve_missing_capability_tool_name() instead of the hardcoded
  "get_more_tools", so a custom missing_capability_tool_name no longer
  misclassifies its calls as context_parameter intent.
- version: fix the comment — __version__ IS stamped as sdk_version on
  every captured event (capture.py), it is not informational-only.
- LICENSE: add the MCPCat MIT attribution block (code derived from
  MCPCat/mcpcat-typescript-sdk), mirroring the per-file headers and the
  posthog-js LICENSE.
- tests: extract the duplicated FakeClient / flush / events helpers into
  posthog/test/mcp/_helpers.py (OnceAndOnlyOnce) and import them.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
…d strip

From Manoel's PR review:

- flush: drain_pending() now also awaits the concurrent.futures.Future used on
  the sync background-loop path (PostHogMCP / sync hosts), and PostHogMCP.flush()
  /shutdown() drain those futures before tearing the client down — previously
  only asyncio.Task was awaited, so trailing sync captures could be dropped.
- conversation_id: strip each injected key independently in the FastMCP adapter.
  A tool that declares its own `context` keeps it while an SDK-injected
  `conversation_id` is still stripped (the two were coupled to context-ownership).
- tools/list parity: capture $mcp_response and $mcp_duration_ms, and wrap the
  list handler so a raised error is recorded as an errored $mcp_tools_list +
  $exception (was: names only, no failure capture).
- $mcp_initialize now also emits on the first tools/list, so a client that lists
  tools but never calls one is still counted (deduped per session).
- low-level call handler wraps original(req) in try/except: a handler wired
  straight into request_handlers (bypassing the decorator that converts raises
  to isError) is captured instead of silently dropped.
- pin mcp<2 since the adapters hook private SDK seams.

Tests in test_review_fixes.py cover each. Deferred (replied on the PR): moving
the import guard so PostHogMCP works without `mcp` installed, and canonicalizing
the idempotency tracking key (mostly covered by the per-seam wrapped guards).

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
Address the two findings deferred from the previous review pass:

- PostHogMCP (custom dispatchers) no longer requires `pip install posthog[mcp]`.
  The official MCP SDK import and the wrapping-path adapters are deferred into
  instrument() instead of guarding the whole module, so `from posthog.mcp import
  PostHogMCP` works with no SDK installed. instrument() raises a clear install
  hint when called without it.
- instrument() keys tracking state on the underlying low-level server (via
  _canonical_server), so instrumenting a high-level FastMCP and its ._mcp_server
  resolve to one state instead of two divergent ones — matching the TS SDK.

Tests: PostHogMCP imports under a blocked `mcp` (subprocess), and instrumenting
wrapper + underlying server is idempotent on shared state.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
… peer dep

The `mcp` extra was the wrong model: instrument() callers definitionally already
have the MCP SDK (you can't build the server you pass it without `mcp`/`fastmcp`),
so an extra that installs it "provides" something you already have. Mirror the TS
package, where @modelcontextprotocol/sdk is a peerDependency.

- Remove the `posthog[mcp]` optional extra. Single install path: `pip install posthog`.
- instrument() imports the SDK lazily and now version-checks it at runtime
  (advises when outside the tested mcp>=1.26,<2 range) — replaces the pin the
  extra used to carry, and catches the real case the pin couldn't (a user who
  already has an old mcp).
- Update the missing-SDK error to `pip install 'mcp>=1.26'` and refresh the
  docstring + changeset. PostHogMCP still needs nothing beyond posthog.

Nothing published yet, so dropping the extra has no back-compat cost.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@lucasheriques

Copy link
Copy Markdown
Contributor Author

thanks manoel, this was a really useful pass. fixed all of it across 0d998ab, 37280c2, and f590c8c.

flush() missing sync futures. fixed. drain_pending() waits on the concurrent.futures.Future from the sync path now too, and PostHogMCP.flush()/shutdown() drain before tearing down. without it a trailing event could still be in flight on sync hosts.

conversation_id leaking into context-owning tools. fixed. the two injected keys get stripped independently now, so a tool that declares its own context keeps it while conversation_id still gets stripped. added tests for context-only, conversation_id-only, and both. (the official FastMCP ignores extra kwargs so nothing was crashing, but it was still wrong, and it does bite the stricter fastmcp 2.0 path.)

tools/list weaker than TS. fixed. it captures $mcp_response and $mcp_duration_ms now, and records a failed $mcp_tools_list plus $exception if the list handler raises. agreed this was the biggest gap.

$mcp_initialize not on list-only sessions. fixed. it emits on the first tools/list too, deduped per session. the deeper difference stays: the Python SDK handles initialize in the session layer rather than request_handlers, so there's no real initialize request, response, or timing to capture. left a note in the adapter.

low-level raises not captured. fixed. wrapped original(req) so a handler that raises directly gets captured before re-raising, same as the TS path.

PostHogMCP requiring mcp. fixed. the SDK import and the wrapping adapters are deferred into instrument() now, so from posthog.mcp import PostHogMCP works with nothing extra installed.

idempotency tracking key. fixed. tracking keys on the underlying low-level server now, so instrumenting a high-level FastMCP and its ._mcp_server land on one state instead of two. matches the TS canonicalization.

dependency range. rather than pin via an extra, we now treat the MCP SDK as a peer dependency (you already have it if you built the server) and check the installed version at runtime, warning outside the tested >=1.26,<2 range. dropped the posthog[mcp] extra entirely, so install is just pip install posthog.

still draft until the pypi publish, but ready for a proper read whenever you have time.

@marandaneto

marandaneto commented Jun 25, 2026

Copy link
Copy Markdown
Member

@lucasheriques still a couple of things left

Key remaining findings:

  1. CI is failing

    • Ruff format fails.
    • Local uv run ruff format --check posthog/test/mcp posthog/mcp confirms 5 test files need formatting.
    • MCP tests pass locally: 63 passed, 1 skipped.
  2. FastMCP v2 still strips real context / conversation_id args

    • Official FastMCP fix was added, but jlowin FastMCP v2 path still unconditionally pops both injected keys when
      strip_injected=True.
    • This can break tools that legitimately define context or conversation_id.
    • File: posthog/mcp/instrument_lowlevel.py:140-142.
  3. tools/list empty-list parity gap remains

    • Node treats zero tools as errored $mcp_tools_list with exception.
    • Python now captures response/duration/errors, but empty lists are still successful.
    • Python: instrument_fastmcp.py:245-289, instrument_lowlevel.py:252-299.
    • Node: packages/mcp/src/extensions/instrumentation.ts:300-308.
  4. $mcp_initialize identity attribution still differs (Probably not reasonably fixable through stable Python MCP SDK hooks)

    • Python emits initialize before handle_identify, so first $mcp_initialize is anonymous even when identify resolves
      on the same first list/call.
    • Python: posthog/mcp/instrumentation.py:197-201.
    • Node identifies before building initialize.
    • Node: packages/mcp/src/extensions/instrumentation.ts:427-438.
      can improve attribution, but not true Node parity without deeper/private monkey-patching
  5. PostHogMCP cannot disable MCP exception fan-out

    • Python hard-codes enable_exception_autocapture=True.
    • Node respects this.options.enableExceptionAutocapture ?? true.
    • Python: posthog/mcp/posthog_mcp.py:283-286.
  6. Runtime MCP version warning likely won’t be visible

    • _warn_if_unsupported_mcp_version() runs before opts.logger is installed, so the warning goes to the default no-op
      logger.
    • Python: posthog/mcp/init.py:193 before set_logger at 201-202.

…entity, PostHogMCP toggle

Manoel's second pass:

- CI: ruff format the 5 test files (I'd run lint, not format).
- FastMCP v2 strip: strip injected context/conversation_id EXCEPT keys the tool
  declares itself, read from the tool's own signature. List-independent and works
  across stateless per-request servers (the prior tracking idea would have failed
  to strip when the list ran on a different instance). A v2 tool owning `context`
  now keeps its real argument.
- tools/list: zero advertised tools is flagged as an errored $mcp_tools_list +
  $exception, matching the TS SDK (both adapters).
- $mcp_initialize: run identify before emitting initialize so the first event is
  attributed instead of anonymous (not byte-parity with TS, which wraps the real
  initialize handler — documented).
- PostHogMCP: add mcp_exception_autocapture (default True) so the $exception
  fan-out can be disabled, mirroring instrument()'s option / the node SDK. Distinct
  from Client.enable_exception_autocapture (the global uncaught-error hook).
- Version advisory: install the logger before _warn_if_unsupported_mcp_version so
  the warning is visible instead of hitting the no-op default.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@lucasheriques

Copy link
Copy Markdown
Contributor Author

thanks, all six addressed in d3fbf46.

  1. ci / ruff format. my miss, i ran ruff check but not ruff format. formatted the 5 files.
  2. v2 stripping real context/conversation_id. fixed, and i switched approach partway. stripping only the keys we injected (tracked from the list) would break stateless per-request servers, where the list ran on a different instance, so nothing gets stripped and jlowin rejects the call. v2 now strips the injected keys except ones the tool declares in its own signature. list-independent and instance-independent. a v2 tool owning context keeps it. added a test.
  3. empty tools/list. matched node, zero advertised tools is now an errored $mcp_tools_list with an exception, both adapters.
  4. $mcp_initialize identity. identify runs before initialize is emitted now, so the first initialize is attributed instead of anonymous. not byte-parity with node (the python sdk handles initialize in the session layer, not request_handlers, so there's no real request/response/timing) but the attribution gap is closed.
  5. PostHogMCP exception fan-out. added mcp_exception_autocapture (default true) so it can be turned off like node. kept distinct from the inherited Client.enable_exception_autocapture, which is the global uncaught-error hook and means something different.
  6. version warning visibility. my bug, fixed. the logger is installed before the version check now, so the advisory actually shows.

71 tests pass, ruff + mypy clean. ci should be green now.

Comment thread references/public_api_snapshot.txt

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice, left a last comment here otherwise LGTM
approving to unblock

Addresses Manoel's pre-merge review: the snapshot was committing posthog.mcp to a
large accidental public API (all ~22 implementation modules exposed, 343 lines).

- Underscore-prefix the 16 pure-internal modules (_sink, _instrumentation,
  _internal, _sanitization, _truncation, _capture, _ids, _intent, _exceptions,
  _compatibility, _posthog_events, _context_parameters, _conversation_id,
  _event_types, _instrument_fastmcp, _instrument_lowlevel) so they drop off the
  public surface entirely.
- Keep the modules that hold genuinely public symbols (constants, logger, session,
  tools, types, posthog_mcp, version) but add __all__ so each exposes only its
  intended public names. Underscore-prefixing these would have hidden the public
  classes from the snapshot too (it follows alias targets), so the guard would stop
  tracking the real API — __all__ keeps them tracked.

Public surface: 343 -> 95 lines, now exactly the __init__ __all__ set plus the
public types/enums. PostHogMCP's methods are still tracked. No runtime API change.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
…ty branches

Lift coverage on the branch-heavy / robustness modules that were thin, before
merge. Adds direct unit tests:

- test_truncation.py: normalize (string caps, NaN/inf, datetime, callables,
  depth/breadth bounds, cycle detection) and truncate_event (field caps,
  exception value/frame limits, response-text caps, the 100KB size budget).
- test_units.py: intent resolution (context arg, missing-capability skip,
  sync/async/erroring/blank fallbacks), conversation_id schema injection +
  loop-back, session-id rollover (mcp-derived, no-fragment, inactivity), and the
  identity cache/merge.

posthog.mcp coverage 81% -> 89%; _truncation 63% -> 93%, _conversation_id 51% ->
98%, _intent 58% -> 95%, session 66% -> 100%. 117 tests pass.

Generated-By: PostHog Code
Task-Id: b21bc954-5de3-4512-a0d5-6bec2371f782
@lucasheriques lucasheriques merged commit 888a725 into main Jun 26, 2026
31 checks passed
@lucasheriques lucasheriques deleted the posthog-code/mcp-analytics-python-sdk branch June 26, 2026 15:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants