NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #472 most downloaded on PyPI
Integrate PostHog into any python application.
Latest stable
8.0.2
Last release today
18 Nov 2026
Ships on a steady schedule
a new release about every 8 days
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
7 years old
390 releases · first in 2020
Drag across the ruler to compare, or tap a release to open it.
b0ab12c feat(mcp): support MCP Python SDK v2 and bring posthog.mcp to parity with the TypeScript SDK (@posthog/mcp). Most of this reaches SDK 1.x serv
b0ab12c feat(mcp): support MCP Python SDK v2 and bring posthog.mcp to parity with the TypeScript SDK (@posthog/mcp). Most of this reaches SDK 1.x servers too — the parity work is not v2-only.
MCP SDK v2 / spec 2026-07-28. instrument() now wraps mcp.server.mcpserver.MCPServer (the renamed FastMCP) and the v2 low-level Server (constructor-injected handlers, string-keyed registry, late add_request_handler registrations included), capturing tool calls, tools/list, errors, intent, client identity, and $mcp_protocol_version on both protocol eras — the legacy handshake and the stateless 2026-07-28 envelope, decided per request. Previously instrument() raised ImportError on mcp>=2 and took the host application down with it; it now degrades to a logged no-op on any unsupported or unrecognized SDK.
Cross-SDK parity (SDK 1.x and 2.x alike). Conversation-anchored sessions land as the cross-pod correlation the stateless era needs: with enable_conversation_id, $session_id derives deterministically from the agent-echoed conversation_id (new export derive_session_id_from_conversation, byte-compatible with @posthog/mcp). Only a handle the SDK could have minted (a uuidv7) anchors a session, so two callers inventing the same id can no longer be merged. The handle is delivered over both channels a tool result has — a content text block carrying it as plain JSON data on the minting response (an imperative server sentence inside a tool result is prompt-injection-shaped, and a client that strips it silently breaks the feature), and an _mcp_instructions key declared on the tool's output schema and mirrored into structuredContent on every response. That second channel is what makes the feature work at all for tools with structured output: clients that read structuredContent never render content, so the agent had no handle to echo (0% echo rate measured against Claude Code before the mirror). The prompt-back now rides errored results too, so a failure on a conversation's first call doesn't split the retry into a new session. The session is resolved only once the handle's fate is known, so the call that mints a handle joins the same session as the calls that echo it — while a handle that could not be delivered anchors nothing, rather than stranding events in a conversation nobody holds. Host callbacks (identify, intent_fallback, event_properties) receive the SDK's own per-request context as extra["ctx"] identically on both majors, with a new exported get_request_headers(extra) to read HTTP headers off it — the underlying shape differs per major, and a hand-rolled read that works on one silently returns nothing on the other, sending every event out anonymous.
Fixes affecting existing SDK 1.x users. Analytics could break a tool call in three ways, each now fixed and regression-tested: the SDK's tool cache is rebuilt from an internal listing pass we skipped injecting on, so after any call to an unlisted tool name a strict schema rejected either the analytics parameters we advertise (Input validation error) or the conversation key we write (Output validation error); the conversation handle was written into the caller's result object in place, so a tool returning a shared or cached result served one conversation's handle to every later caller; and on jlowin's FastMCP the advertised schema marked context required while the adapter strips it before validation, failing every call under strict_input_validation=True. Two behavioural changes come with the parity work: an invented (non-uuidv7) conversation_id echo is replaced with a fresh handle rather than trusted, and minted prompt-backs are now appended to errored results. — Thanks @gesh!
Your coding agent can read these notes before it upgrades. Set up the MCP server →
1adf542 Drop events when before_send callbacks raise exceptions — Thanks @marandaneto!
6fc55b6 Normalize SDK event timestamps to UTC, including datetime values and parseable ISO timestamp strings, and correct UTC serialization for except
…flag (old private flags kept as deprecated aliases). — Thanks @carlos-marchal-ph!
capture_ai: AI events on the dedicated AI endpoint with the event UUID returned; new enable_full_ai_capture flag (old private flags kept as deprecated aliases). — Thanks @carlos-marchal-ph!9beed86 fix: preserve event delivery when gevent monkey-patches queue.Queue, including in preloaded gunicorn workers — Thanks @marandaneto!
queue.Queue, including in preloaded gunicorn workers — Thanks @marandaneto!9c4fd84 Fix async OpenAI streaming captures to include token usage and other generation properties emitted by synchronous streams. — Thanks @ckarnell
f38790c Fix local evaluation for negated, missing, and malformed cohort definitions — Thanks @marandaneto!
bd5cff4 fix: declare Gemini's cache accounting model on generations with cache reads, so ingestion prices cached tokens from $ai_cache_reporting_exclu
$ai_cache_reporting_exclusive instead of inferring it from the token counts. — Thanks @fivestarspicy!100f993 group_identify() now validates the group identity before enqueuing. Previously group_identify("company", None) (or an empty-string group_type
group_identify() now validates the group identity before enqueuing. Previously group_identify("company", None) (or an empty-string group_type / group_key) sent a $groupidentify event with a null/empty $group_type or $group_key, which cannot address a group profile and just adds an unusable event to the project. Missing values are now dropped with a warning instead, matching the sdk-specs group-identify contract. Valid values, including non-string group keys, are passed through unchanged. — Thanks @posthog[bot]!55370ee fix: prevent client lifecycle deadlocks when error callbacks, concurrent join()/shutdown() calls, or forked sync-mode clients interact with qu
join()/shutdown() calls, or forked sync-mode clients interact with queue and worker teardown. — Thanks @marandaneto!77821ce feat: FeatureFlagEvaluations.is_enabled() accepts a default_value returned when the flag has no value in the evaluation — the key was not part
FeatureFlagEvaluations.is_enabled() accepts a default_value returned when the flag has no value in the evaluation — the key was not part of the evaluated set, or the evaluation came back empty (failed /flags request, quota limit, no resolvable distinct_id). A flag that has a value still wins, so a disabled flag returns False even with default_value=True. The default is False, so existing calls behave exactly as before. — Thanks @posthog[bot]!evaluate_flags() now JSON-decodes payloads for locally-evaluated flags, the same way it already did for flags resolved remotely. Previously get_flag_payload() returned a parsed value ({"copy": "new"}) when the flag came back from /flags but the raw JSON string ('{"copy": "new"}') when the poller evaluated it locally, so the payload's type depended on where the flag happened to resolve. The $feature_flag_payload property on $feature_flag_called events is decoded for locally-evaluated flags too. Payload strings that aren't valid JSON are still passed through unchanged. — Thanks @posthog[bot]!$feature_flag_called dedupe tracker now evicts its oldest entry when it reaches capacity instead of clearing every entry. Previously, each time a client accumulated 50,000 distinct IDs the whole tracker was wiped, so the next flag read for every previously seen distinct ID re-emitted a $feature_flag_called event it had already deduped. — Thanks @posthog[bot]!c5f4e8f Normalize Gemini tool calls and tool responses in captured input so they render in traces and reach evaluations — Thanks @marco-g-pm!
ae26014 fix: flush() no longer waits out flush_interval before delivering a partial batch. A consumer holding fewer than flush_at events now sends the
flush() no longer waits out flush_interval before delivering a partial batch. A consumer holding fewer than flush_at events now sends them as soon as flush() (or shutdown()) asks it to, instead of blocking the caller for the rest of the batching window — which previously made flush() deliver nothing at all when flush_interval was longer than the flush timeout. Timer-based batching without an explicit flush is unchanged. — Thanks @posthog[bot]!6397d78 alias() now validates both identities before enqueuing. Previously alias(None, "user-123") (or an empty-string previous_id) sent a $create_ali
alias() now validates both identities before enqueuing. Previously alias(None, "user-123") (or an empty-string previous_id) sent a $create_alias event with a null/empty distinct_id, which cannot link anything and just adds an unusable event to the project. Missing identities are now dropped with a warning instead, matching the sdk-specs alias contract. The drop that already happened when no alias target could be resolved now logs a warning too, and a non-string previous_id such as 0 is stringified consistently in both distinct_id and properties.distinct_id. — Thanks @posthog[bot]!5ed7d0d Prevent stale feature flag definition publication — Thanks @marandaneto!
b16ec74 Isolate MCP pending capture tasks by owner and loop — Thanks @marandaneto!
38a09b8 Preserve typed feature flag results in Redis fallback — Thanks @marandaneto!
c5d01c9 Support the starts_with, not_starts_with, ends_with, and not_ends_with property filter operators in feature flag local evaluation. Matching is
starts_with, not_starts_with, ends_with, and not_ends_with property filter operators in feature flag local evaluation. Matching is case-insensitive and mirrors icontains, so flags using these operators no longer fall back to remote evaluation. — Thanks @haacked!f805e5b posthog.ai.openai.OpenAI / AsyncOpenAI now accept a per-call posthog_provider_override argument. The wrapper is commonly pointed at OpenAI-com
posthog.ai.openai.OpenAI / AsyncOpenAI now accept a per-call posthog_provider_override argument. The wrapper is commonly pointed at OpenAI-compatible endpoints (DeepSeek, Groq, Mistral, Together, Fireworks, xAI, Perplexity, Ollama, Cerebras, and various gateways) via a custom base_url, but always reported $ai_provider: "openai", which breaks PostHog's cost attribution for those calls. Passing posthog_provider_override="deepseek" (for example) sets $ai_provider on the emitted event without changing how the OpenAI-shaped response is parsed. Omitting it leaves $ai_provider as "openai", exactly as before. Covers chat completions, the Responses API, .parse(), and embeddings, across sync, async, and streaming calls. — Thanks @marco-g-pm!340eb2a Reset PostHog context after fork. Forked children no longer retain the parent process's active lexical context; they start without inherited c
60a3e9c Reset the client registry lock after fork — Thanks @marandaneto!
0b353a7 Keep consumers alive after malformed before_send results — Thanks @marandaneto!
aa00432 Restore exception hooks safely — Thanks @marandaneto!
bfec2b1 Reset MCP background capture state after fork — Thanks @marandaneto!
4bf123e The OpenAI Agents SDK group_id now also maps to $ai_session_id on $ai_trace and span events, so grouped runs show up as sessions in PostHog AI
group_id now also maps to $ai_session_id on $ai_trace and span events, so grouped runs show up as sessions in PostHog AI observability. $ai_group_id is still emitted alongside it. — Thanks @marco-g-pm for your first contribution 🎉!3c9aa59 feat(ai): Prompts.get(..., with_metadata=True) results now include config, the JSON object of model parameters or agent configuration stored w
Prompts.get(..., with_metadata=True) results now include config, the JSON object of model parameters or agent configuration stored with the prompt version in PostHog prompt management (None when the version has none). Config is carried through the client-side cache and the stale-cache fallback. The hardcoded fallback string has no config, so use defensive access like (result.config or {}).get("temperature", 0). — Thanks @jurajmajerik!170f4e2 feat(mcp): emit $mcp_protocol_version on MCP analytics events — the MCP spec version, recovered from the session token across stateless pods (
$mcp_protocol_version on MCP analytics events — the MCP spec version, recovered from the session token across stateless pods (parity with the TypeScript SDK). PostHogMCP capture methods gain a protocol_version argument. — Thanks @gesh for your first contribution 🎉!cdc0825 Preserve Anthropic cache-write TTL breakdowns across Python SDK AI integrations. — Thanks @gouveags!
13de879 Fix module-level settings propagation to the default client — Thanks @marandaneto!
5535ecd fix(errors): emit $exception_list in canonical order — index 0 is the caught/outermost exception, causes follow in unwrap order, and the root
$exception_list in canonical order — index 0 is the caught/outermost exception, causes follow in unwrap order, and the root cause is last (previously the list was reversed with the root cause first). This aligns posthog-python with the cross-SDK exception ordering spec. Frame order within each stacktrace is unchanged. — Thanks @cat-ph!4c8a85a AI capture now records multimodal and structured content (thinking blocks, tool calls, media, and Responses API output items) faithfully acros
37aafd3 feat(mcp): stateless and multi-pod server support — carry $session_id and the client identity (harness) across pods via a self-encoded Mcp-Ses
$session_id and the client identity (harness) across pods via a self-encoded Mcp-Session-Id token minted at initialize and replayed on every request. Auto-wired on the instrument() FastMCP path (stateless_http=True); custom PostHogMCP dispatchers add PostHogMcpStatelessSessionMiddleware and read get_mcp_session(). — Thanks @gesh!f9a163c Refactored capture internals to support multiple delivery lanes per client. Added an internal test lane for heavy AI events.
f9a163c Refactored capture internals to support multiple delivery lanes per client. Added an internal test lane for heavy AI events.
Events captured after shutdown() are now dropped with a warning instead of being silently queued with no consumer to deliver them. — Thanks @carlos-marchal-ph!
2d7f8cc The client.metrics config can now be set through module-level settings: assign posthog.metrics = {"service_name": ..., ...} alongside posthog.
client.metrics config can now be set through module-level settings: assign posthog.metrics = {"service_name": ..., ...} alongside posthog.api_key and the dict is applied when setup() builds the global client. Previously module-configured apps had no way to pass the metrics config, so every series recorded through the global client shipped service.name='unknown_service'. Late assignment (e.g. a Django ready() hook running after an early setup()) still applies on the next setup() call, as long as the metrics API hasn't been used yet. — Thanks @DanielVisca!6766309 Harden the alpha posthog.metrics client based on review follow-ups.
count()/gauge()/histogram() can no longer rewrite an already-recorded series' attributes on the wire.metrics client config (non-dict config or resource_attributes, non-numeric flush_interval, non-integer max_series_per_flush, non-callable before_send) now degrades to defaults with a warning instead of raising from the first client.metrics.count() call, matching the client's no-throw contract. — Thanks @DanielVisca!ca5e883 Clarify the queue-full warning to say the event is being dropped, instead of only reporting that the queue is full. — Thanks @emmayusufu for y
5ef2c23 $feature_flag_called events are now minimized for non-experiment flags when the server enables it. When the /flags v2 response (minimalFlagCal
5ef2c23 $feature_flag_called events are now minimized for non-experiment flags when the server enables it. When the /flags v2 response (minimalFlagCalledEvents) or the local-evaluation payload (minimal_flag_called_events) reports the gate as enabled and the evaluated flag has no linked experiment (has_experiment is false), the event's properties are reduced to a strict allowlist ($feature_flag, $feature_flag_response, $feature_flag_has_experiment, the $feature_flag_* debug scalars, locally_evaluated, $groups, $process_person_profile, $session_id, $lib, $lib_version, $is_server, $geoip_disable, $os, $os_version, $os_distro, $python_runtime, $python_version). Everything else — including super properties and custom event properties — is stripped from those events.
If the server does not report the gate, if the flag's has_experiment signal is missing, or if the flag is linked to an experiment, the full property set is sent unchanged. There is no SDK-side configuration; the gate is controlled per-team by the server. For evaluate_flags() snapshots, the gate is pinned when the snapshot is created, so deferred flag accesses are shaped by the evaluation that produced them.
Custom flag_definition_cache providers now receive an additional minimal_flag_called_events key in the definitions payload, so the gate survives external cache round-trips.
When the server reports has_experiment for a flag, every $feature_flag_called event also carries a $feature_flag_has_experiment boolean property. — Thanks @haacked!
1653bcb Add a label option to Prompts.get() to fetch the prompt version a label (e.g. production) currently points to. Labeled fetches are cached sepa
label option to Prompts.get() to fetch the prompt version a label (e.g. production) currently points to. Labeled fetches are cached separately, and PromptResult carries the resolved label. Requires a PostHog version with prompt labels; older servers ignore the parameter and return the latest version. — Thanks @jurajmajerik!5ab6318 Add the active OpenTelemetry span's $trace_id and $span_id to events captured with capture_exception. — Thanks @hpouillot!
$trace_id and $span_id to events captured with capture_exception. — Thanks @hpouillot!556c134 $feature_flag_called events now carry a $feature_flag_has_experiment boolean property when the server reports whether the flag is linked to an
$feature_flag_called events now carry a $feature_flag_has_experiment boolean property when the server reports whether the flag is linked to an experiment. When the server does not report the signal (older deployments), the property is omitted. — Thanks @haacked!5e42b1e Add the posthog.metrics API (count, gauge, histogram) — alpha.
5e42b1e Add the posthog.metrics API (count, gauge, histogram) — alpha.
Backend services can now record metrics through the same statsd-style pre-aggregating client the browser SDK ships, with no OpenTelemetry setup:
client = Posthog("<ph_project_api_key>", metrics={"service_name": "billing-worker"})
client.metrics.count("invoices.processed", 1, attributes={"plan": "pro"})
client.metrics.gauge("queue.depth", 42)
client.metrics.histogram("job.duration", 187, unit="ms")
Samples aggregate in memory and flush as OTLP/JSON to /i/v1/metrics (one data point per series per window, delta temporality). Pending metrics are flushed on shutdown(); buffered windows are retried on transient failures and dropped loudly after 3 consecutive failed flushes. The metrics client option accepts service_name, service_version, environment, resource_attributes, flush_interval (seconds), max_series_per_flush (cardinality guardrail, default 1000), and a before_send hook. — Thanks @DanielVisca!
eb025c8 Django middleware also sends the request user agent as $raw_user_agent, the standardized property PostHog's server-side classification (e.g. b
$raw_user_agent, the standardized property PostHog's server-side classification (e.g. bot detection) reads — Thanks @lricoy!ae3c4e5 Malformed flag-dependency conditions (missing key, null value, or wrong operator) now evaluate locally as no-match (false), matching the serve
/flags endpoint on every evaluation. 7.22.1 made these conditions fall back to the server, which could massively increase billable /flags request volume for flag definitions containing legacy/malformed dependency conditions. — Thanks @patricio-posthog!4d61b18 Capture pre-calculated total cost from OpenAI Agents Responses API usage. — Thanks @fuchengwarrenzhu for your first contribution 🎉!
650d107 Fix local evaluation of flag dependencies with a flag_evaluates_to: false condition: such conditions never matched, forcing the dependent flag
flag_evaluates_to: false condition: such conditions never matched, forcing the dependent flag to false for every locally-evaluated user. — Thanks @matheus-vb!d459b57 Add an opt-in capture_mode for the Capture V1 ingestion protocol (POST /i/v1/analytics/events). Set capture_mode="v1" on the client (or the PO
d459b57 Add an opt-in capture_mode for the Capture V1 ingestion protocol (POST /i/v1/analytics/events). Set capture_mode="v1" on the client (or the POSTHOG_CAPTURE_MODE=v1 environment variable) to use Bearer auth, per-event results, and partial retry. Defaults to "v0" (the legacy /batch/ endpoint), so existing setups are unaffected.
When using capture_mode="v1", request bodies can be compressed via capture_compression (or POSTHOG_CAPTURE_COMPRESSION): "gzip", "deflate", "zstd" (requires the optional posthog[zstd] extra), or "none" (default). The legacy gzip=True flag is honored as a fallback.
Per-event server verdicts are surfaced through the existing on_error handler: events the backend explicitly drops, or fails to accept after retries, raise a CaptureV1Error carrying the affected event UUIDs — so a rejection is never silently lost, even when the HTTP request itself succeeded. — Thanks @eli-r-ph for your first contribution 🎉!
30c184f Stop duplicating distinct_id inside /flags person properties — Thanks @marandaneto!
c6350b6 Testing release workflow. — Thanks @marandaneto!
cd86110 Fall back to uncompressed uploads when gzip compression fails — Thanks @marandaneto!
888a725 Add posthog.mcp, a Python SDK for PostHog MCP analytics (just pip install posthog; the MCP SDK is a peer dependency of instrument(), not bundl
posthog.mcp, a Python SDK for PostHog MCP analytics (just pip install posthog; the MCP SDK is a peer dependency of instrument(), not bundled). instrument(server, posthog_client) wraps a FastMCP or low-level mcp.server.Server so every tool call, agent intent, tools/list, initialize, and failure is captured to PostHog as a $mcp_* event. Also adds PostHogMCP, a Client subclass for custom dispatchers (needs nothing beyond posthog), plus opt-in context intent capture, identify, report_missing (get_more_tools), and conversation_id. Beta. — Thanks @lucasheriques for your first contribution 🎉!cdd878c Clear feature flag called cache on shutdown — Thanks @marandaneto!
89adb2f Fix internal imports for posthoganalytics mirror — Thanks @hpouillot!
42ff4ca Detect and redact high-entropy secrets (API keys, tokens, passwords) in exception code variables. Adds the code_variables_detect_secrets optio
code_variables_detect_secrets option (default True). — Thanks @ablaszkiewicz!c359f93 Mask sensitive data held inside objects and in URL/DSN credentials when capturing exception code variables. Custom objects are now traversed s
password are redacted by attribute name instead of leaking via repr(), and credentials embedded in connection strings are scrubbed. Adds the code_variables_mask_url_credentials option (default True). — Thanks @ablaszkiewicz!09c8fba Warn on duplicate async PostHog clients and document client lifecycle guidance — Thanks @marandaneto!
bc8e531 Add a default timeout for flushing queued events. — Thanks @marandaneto!
98a305a Increase the default background flush interval to 5 seconds — Thanks @marandaneto!
8d416ae Add missing return type annotations to improve typing coverage without changing runtime behavior. — Thanks @miachillgood for your first contri
b9f3208 Add opt-in client-side rate limiting for exception autocapture, using the same token bucket algorithm as the posthog-js and posthog-node SDKs:
enable_exception_autocapture_rate_limiting client option and tune via exception_autocapture_bucket_size (default 50), exception_autocapture_refill_rate (default 10), and exception_autocapture_refill_interval_seconds (default 10). — Thanks @hpouillot!ee6a3c8 Warn when an AI wrapper's base_url points at the PostHog AI Gateway. The gateway emits its own $ai_generation, so each call would be captured
base_url points at the PostHog AI Gateway. The gateway emits its own $ai_generation, so each call would be captured (and billed) twice. The wrapper only warns and never drops the event. Detection covers the wrapper funnels (OpenAI, Anthropic, LangChain) and the OTel span path. — Thanks @richardsolomou!fe76fc9 Improve mypy coverage for core SDK modules without changing runtime behavior. — Thanks @Kshitijmishradev for your first contribution 🎉!
One column per quarter.