Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): buffer mcp read intents for activity summaries (#126699)

posthog[bot]f68532337afc
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index adc0c38c0549..99e9bba245c1 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -195,6 +195,11 @@ A task link appears only when the token has a server-set task binding, so intent
The `X-PostHog-Task-Id` header cannot supply that binding, and the authenticated user remains the actor on the audit row.
This applies to new activity rows; it does not recover intent that was discarded before the change.
+An MCP read writes no activity row, so its intent never reaches the audit log.
+When `ACTIVITY_SUMMARY_MCP_BUFFER_ENABLED` is on, `ActivityLoggingMiddleware` also hands the intent of a successful MCP request to a best-effort Redis buffer for the activity summary (`products/signals/backend/activity_summary/mcp_buffer.py`).
+It does this only for a personal API key or an OAuth token without a sandbox task binding or impersonation, and only for a team that the `activity-summary` flag payload enrolls with `mcp_buffer_enabled`.
+The request thread only appends to an in-process queue; a background thread writes to Redis, so the buffer can drop records but cannot slow down or fail the request.
+
### Client IP
`ActivityLoggingMiddleware` stores the request's client IP, and `log_activity` writes it to `ActivityLog.ip_address`.
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 1516ce297d5c..f0aae2c0514b 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -57,6 +57,7 @@ from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_mat
from posthog.models import Organization, Team, User
from posthog.models.activity_logging.utils import (
ACTIVITY_LOG_CLIENT_HEADER,
+ ACTIVITY_LOG_INTENT_HEADER,
ActivityCredential,
activity_storage,
client_from_header,
@@ -75,6 +76,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.facade.models import Insight
+from products.signals.backend.facade.mcp_intents import buffer_mcp_intent
from .auth import PersonalAPIKeyAuthentication
@@ -1448,6 +1450,63 @@ def _session_credential(request: HttpRequest, session_user_pk: object) -> Activi
return session_activity_credential(request, get_original_user_id_from_session(request))
+# Credentials a person holds. A server-minted sandbox token is OAuth too, but it binds a task.
+_MCP_INTENT_CREDENTIAL_TYPES = frozenset({"oauth", "personal_api_key"})
+
+
+def _resolved_team_id(response: HttpResponse) -> int | None:
+ """The team that a DRF view resolved for the request, read without a query.
+
+ Reads only the cached values, because a view that never resolved a team has no team to report.
+ """
+ renderer_context = getattr(response, "renderer_context", None) or {}
+ cached = getattr(renderer_context.get("view"), "__dict__", {})
+ team = cached.get("team")
+ if isinstance(team, Team):
+ return team.id
+ team_id = cached.get("team_id")
+ return team_id if isinstance(team_id, int) else None
+
+
+def _buffer_mcp_intent(request: HttpRequest, response: HttpResponse) -> None:
+ """Keep the intent of an MCP read for the activity summary, which sees only the calls that write.
+
+ Runs after the view, because bearer authentication sets the user inside it. The buffer is
+ optional context, so a failure here must not fail the request.
+ """
+ if not settings.ACTIVITY_SUMMARY_MCP_BUFFER_ENABLED:
+ return
+ try:
+ if request.headers.get(ACTIVITY_LOG_CLIENT_HEADER, "").strip().lower() != "mcp" or response.status_code >= 400:
+ return
+ intent = request.headers.get(ACTIVITY_LOG_INTENT_HEADER, "").strip()
+ if not intent:
+ return
+ credential = activity_storage.get_credential()
+ if (
+ credential is None
+ or credential.type not in _MCP_INTENT_CREDENTIAL_TYPES
+ or credential.impersonated_by_id is not None
+ or activity_storage.get_agent_task_id() is not None
+ ):
+ return
+ user = activity_storage.get_user()
+ team_id = _resolved_team_id(response)
+ if user is None or team_id is None:
+ return
+ resolver_match = request.resolver_match
+ buffer_mcp_intent(
+ team_id=team_id,
+ user_id=user.pk,
+ session_id=sanitize_header_value(request.headers.get("X-Posthog-Mcp-Session-Id"))
+ or sanitize_header_value(request.headers.get("X-Posthog-Mcp-Conversation-Id")),
+ route_name=resolver_match.view_name if resolver_match else None,
+ intent=intent,
+ )
+ except Exception:
+ logger.warning("activity_summary.mcp_intent_buffer_failed", exc_info=True)
+
+
class ActivityLoggingMiddleware:
"""
Middleware that sets the current user and impersonation status in activity storage
@@ -1478,6 +1537,7 @@ class ActivityLoggingMiddleware:
try:
response = self.get_response(request)
+ _buffer_mcp_intent(request, response)
finally:
# Clean up activity storage after request
activity_storage.clear_all()
diff --git a/posthog/settings/signals.py b/posthog/settings/signals.py
index 3612d4547725..b8f652d88d48 100644
--- a/posthog/settings/signals.py
+++ b/posthog/settings/signals.py
@@ -1,7 +1,7 @@
import os
from posthog.settings.base_variables import CLOUD_DEPLOYMENT, DEBUG, TEST
-from posthog.settings.utils import get_list, get_set
+from posthog.settings.utils import get_from_env, get_list, get_set, str_to_bool
SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE = os.getenv("SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE", "false").lower() == "true"
@@ -56,3 +56,11 @@ def _parse_team_ids(raw: str) -> set[int]:
SIGNALS_LIGHTHOUSE_TEAM_IDS: set[int] = _parse_team_ids(
os.getenv("SIGNALS_LIGHTHOUSE_TEAM_IDS", _DEFAULT_LIGHTHOUSE_TEAM_IDS)
)
+
+# Turns on the buffer of MCP intents for activity summaries. The `activity-summary` flag payload
+# picks the teams and limits; this switch turns the request hook off without a deploy of new code.
+ACTIVITY_SUMMARY_MCP_BUFFER_ENABLED: bool = get_from_env(
+ "ACTIVITY_SUMMARY_MCP_BUFFER_ENABLED", False, type_cast=str_to_bool
+)
+# The buffer needs a TTL-aware eviction policy (`volatile-ttl` or `noeviction`). Unset uses `REDIS_URL`.
+ACTIVITY_SUMMARY_MCP_BUFFER_REDIS_URL: str = os.getenv("ACTIVITY_SUMMARY_MCP_BUFFER_REDIS_URL", "")
diff --git a/products/signals/backend/activity_summary/config.py b/products/signals/backend/activity_summary/config.py
index d2f4752d3602..29fb75a74bdd 100644
--- a/products/signals/backend/activity_summary/config.py
+++ b/products/signals/backend/activity_summary/config.py
@@ -31,6 +31,8 @@ ACTIVITY_SUMMARY_FLAG = "activity-summary"
ACTIVITY_SUMMARY_FLAG_DISTINCT_ID = "signals_activity_summary"
# One unit of a source never adds more than this to the pending score.
MAX_SOURCE_WEIGHT = 10.0
+MAX_MCP_CALLS_PER_DAY = 500
+MAX_MCP_BUFFER_DAYS = 30
@frozen
@@ -98,6 +100,13 @@ class ActivitySummaryConfig:
rebuild_before: datetime.datetime | None = None
# The largest share of a tick that rebuilds of stale summaries can take. Other updates get the rest.
rebuild_budget_share: float = 0.3
+ mcp_buffer_enabled: bool = False
+ # Limits the buffer to the enrolled teams of these organizations. Empty means every enrolled team.
+ mcp_buffer_organization_ids: tuple[str, ...] = ()
+ # The buffer keeps the latest calls of each user, team and day. A separate counter keeps the full count.
+ mcp_calls_per_day: int = 50
+ # Must cover the longest gap between two updates of one summary.
+ mcp_buffer_days: int = 10
DISABLED = ActivitySummaryConfig()
@@ -233,6 +242,14 @@ def parse_config(payload: Any) -> ActivitySummaryConfig:
limits=parse_limits(payload.get("limits")),
rebuild_before=_timestamp(payload.get("rebuild_before")),
rebuild_budget_share=_fraction(payload.get("rebuild_budget_share"), defaults.rebuild_budget_share),
+ mcp_buffer_enabled=_bool(payload.get("mcp_buffer_enabled"), defaults.mcp_buffer_enabled),
+ mcp_buffer_organization_ids=_organization_ids(payload.get("mcp_buffer_organization_ids")),
+ mcp_calls_per_day=min(
+ _positive_int(payload.get("mcp_calls_per_day"), defaults.mcp_calls_per_day), MAX_MCP_CALLS_PER_DAY
+ ),
+ mcp_buffer_days=min(
+ _positive_int(payload.get("mcp_buffer_days"), defaults.mcp_buffer_days), MAX_MCP_BUFFER_DAYS
+ ),
)
diff --git a/products/signals/backend/activity_summary/mcp_buffer.py b/products/signals/backend/activity_summary/mcp_buffer.py
new file mode 100644
index 000000000000..e53c5c62b274
--- /dev/null
+++ b/products/signals/backend/activity_summary/mcp_buffer.py
@@ -0,0 +1,270 @@
+"""A best-effort Redis buffer of the intents that MCP agents state on their PostHog API calls.
+
+`record_agent_intent` keeps an intent only when its request writes an activity log row, and most MCP
+calls are reads. This buffer keeps a short list of the intents of each user, team and day, so the
+activity summary can see what MCP users investigate.
+
+The buffer is optional context. It can lose records, but it must never slow down or fail a request.
+So the request thread does no network I/O: it only appends to a bounded in-process queue. A daemon
+thread writes the queue to Redis about once a second, with short timeouts and a circuit breaker, and
+refreshes the enrolled teams in the background.
+
+Redis keys, each with a TTL of `mcp_buffer_days`:
+
+- `as:mcp:{team_id}:{user_id}:{yyyymmdd}`: a list of the latest `mcp_calls_per_day` records.
+- `as:mcp:n:{team_id}:{user_id}:{yyyymmdd}`: the count of all records of the day, trimmed or not.
+- `as:mcp:dirty`: a set of `{team_id}:{user_id}` members that have new records.
+
+A record is `ts|session_or_conversation_id|route_name|intent`, with `ts` in Unix seconds.
+"""
+
+import os
+import queue
+import datetime
+import threading
+from collections import defaultdict
+from collections.abc import Callable
+from time import monotonic, perf_counter, sleep
+
+from django.conf import settings
+from django.db import connections
+
+import redis
+import structlog
+from prometheus_client import Counter, Histogram
+
+from posthog.dataclasses import frozen
+from posthog.redis import get_client
+
+logger = structlog.get_logger(__name__)
+
+QUEUE_SIZE = 10_000
+INTENT_MAX_CHARS = 200
+# Session ids and route names are much shorter. The cap only bounds a caller-asserted header.
+_FIELD_MAX_CHARS = 100
+FLUSH_INTERVAL_SECONDS = 1.0
+CIRCUIT_OPEN_SECONDS = 30.0
+SETTINGS_REFRESH_SECONDS = 300.0
+# The default client timeouts can stall the flush thread for seconds.
+REDIS_TIMEOUT_SECONDS = 0.05
+DIRTY_KEY = "as:mcp:dirty"
+
+RECORDS = Counter(
+ "activity_summary_mcp_intent_records",
+ "MCP intent records by outcome: enqueued, flushed, or dropped and why.",
+ ["outcome"],
+)
+FLUSH_SECONDS = Histogram(
+ "activity_summary_mcp_intent_flush_seconds",
+ "Wall-clock time of one Redis flush of the MCP intent buffer.",
+ buckets=(0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1),
+)
+
+
+def records_key(team_id: int, user_id: int, day: str) -> str:
+ return f"as:mcp:{team_id}:{user_id}:{day}"
+
+
+def count_key(team_id: int, user_id: int, day: str) -> str:
+ return f"as:mcp:n:{team_id}:{user_id}:{day}"
+
+
+@frozen
+class McpIntentRecord:
+ team_id: int
+ user_id: int
+ day: str
+ value: str
+
+
+@frozen
+class BufferSettings:
+ team_ids: frozenset[int] = frozenset()
+ calls_per_day: int = 50
+ buffer_days: int = 10
+
+
+def _field(value: str | None, max_chars: int) -> str:
+ # `|` separates the fields, and a record is one line.
+ return " ".join((value or "").replace("|", " ").split())[:max_chars]
+
+
+def build_record(
+ *, team_id: int, user_id: int, session_id: str | None, route_name: str | None, intent: str, at: datetime.datetime
+) -> McpIntentRecord:
+ value = "|".join(
+ (
+ str(int(at.timestamp())),
+ _field(session_id, _FIELD_MAX_CHARS),
+ _field(route_name, _FIELD_MAX_CHARS),
+ _field(intent, INTENT_MAX_CHARS),
+ )
+ )
+ return McpIntentRecord(
+ team_id=team_id, user_id=user_id, day=at.astimezone(datetime.UTC).strftime("%Y%m%d"), value=value
+ )
+
+
+def load_settings() -> BufferSettings:
+ """The enrolled teams and the buffer limits, from the `activity-summary` flag payload and Postgres."""
+ from products.signals.backend.activity_summary.config import ( # noqa: PLC0415 — keeps heavy deps off the middleware import path
+ ACTIVITY_SUMMARY_FLAG,
+ ACTIVITY_SUMMARY_FLAG_DISTINCT_ID,
+ parse_config,
+ )
+ from products.signals.backend.activity_summary.queue import ( # noqa: PLC0415 — keeps heavy deps off the middleware import path
+ mcp_buffer_team_ids,
+ )
+ from products.signals.backend.scout_harness.team_limits import ( # noqa: PLC0415 — keeps heavy deps off the middleware import path
+ read_flag_payload,
+ )
+
+ # Not `read_config`, which logs on every read: each web process refreshes every few minutes.
+ config = parse_config(read_flag_payload(ACTIVITY_SUMMARY_FLAG, ACTIVITY_SUMMARY_FLAG_DISTINCT_ID))
+ return BufferSettings(
+ team_ids=frozenset(mcp_buffer_team_ids(config)),
+ calls_per_day=config.mcp_calls_per_day,
+ buffer_days=config.mcp_buffer_days,
+ )
+
+
+def _redis_client() -> redis.Redis:
+ return get_client(
+ settings.ACTIVITY_SUMMARY_MCP_BUFFER_REDIS_URL or None,
+ socket_timeout=REDIS_TIMEOUT_SECONDS,
+ socket_connect_timeout=REDIS_TIMEOUT_SECONDS,
+ )
+
+
+class McpIntentBuffer:
+ def __init__(
+ self,
+ *,
+ queue_size: int = QUEUE_SIZE,
+ redis_client: Callable[[], redis.Redis] = _redis_client,
+ clock: Callable[[], float] = monotonic,
+ start_thread: bool = True,
+ ) -> None:
+ self._queue_size = queue_size
+ self._redis_client = redis_client
+ self._clock = clock
+ self._start_thread = start_thread
+ self._lock = threading.Lock()
+ self.buffer_settings = BufferSettings()
+ self._circuit_open_until = 0.0
+ self._reset()
+
+ def _reset(self) -> None:
+ # A forked process inherits the queue but not the thread that drains it.
+ self._pid = os.getpid()
+ self._queue: queue.Queue[McpIntentRecord] = queue.Queue(maxsize=self._queue_size)
+ self._thread: threading.Thread | None = None
+
+ def append(
+ self, *, team_id: int, user_id: int, session_id: str | None, route_name: str | None, intent: str
+ ) -> None:
+ """Queue one record for the next flush. Runs on the request thread, so it does no network I/O."""
+ self._ensure_thread()
+ if team_id not in self.buffer_settings.team_ids:
+ return
+ record = build_record(
+ team_id=team_id,
+ user_id=user_id,
+ session_id=session_id,
+ route_name=route_name,
+ intent=intent,
+ at=datetime.datetime.now(datetime.UTC),
+ )
+ try:
+ self._queue.put_nowait(record)
+ except queue.Full:
+ RECORDS.labels(outcome="dropped_queue_full").inc()
+ return
+ RECORDS.labels(outcome="enqueued").inc()
+
+ def _ensure_thread(self) -> None:
+ thread = self._thread
+ if self._pid == os.getpid() and thread is not None and thread.is_alive():
+ return
+ if not self._start_thread:
+ return
+ with self._lock:
+ if self._pid != os.getpid():
+ self._reset()
+ if self._thread is not None:
+ if self._thread.is_alive():
+ return
+ logger.warning("activity_summary.mcp_buffer_thread_restarted")
+ self._thread = threading.Thread(target=self._run, name="activity-summary-mcp-buffer", daemon=True)
+ self._thread.start()
+
+ def _run(self) -> None:
+ next_refresh_at = 0.0
+ while True:
+ try:
+ if self._clock() >= next_refresh_at:
+ next_refresh_at = self._clock() + SETTINGS_REFRESH_SECONDS
+ try:
+ self.refresh_settings()
+ finally:
+ # This thread owns its own connection, and an idle one would stay open between refreshes.
+ connections.close_all()
+ self.flush()
+ except Exception:
+ logger.exception("activity_summary.mcp_buffer_loop_failed")
+ sleep(FLUSH_INTERVAL_SECONDS)
+
+ def refresh_settings(self) -> None:
+ try:
+ self.buffer_settings = load_settings()
+ except Exception:
+ logger.warning("activity_summary.mcp_buffer_settings_failed", exc_info=True)
+
+ def _drain(self) -> list[McpIntentRecord]:
+ records: list[McpIntentRecord] = []
+ while True:
+ try:
+ records.append(self._queue.get_nowait())
+ except queue.Empty:
+ return records
+
+ def flush(self) -> None:
+ """Write the queued records to Redis in one pipeline, or drop them while the circuit is open."""
+ records = self._drain()
+ if not records:
+ return
+ if self._clock() < self._circuit_open_until:
+ RECORDS.labels(outcome="dropped_circuit_open").inc(len(records))
+ return
+ started = perf_counter()
+ try:
+ self._write(records, self.buffer_settings)
+ except Exception:
+ self._circuit_open_until = self._clock() + CIRCUIT_OPEN_SECONDS
+ RECORDS.labels(outcome="dropped_flush_error").inc(len(records))
+ logger.warning("activity_summary.mcp_buffer_flush_failed", records=len(records), exc_info=True)
+ return
+ finally:
+ FLUSH_SECONDS.observe(perf_counter() - started)
+ RECORDS.labels(outcome="flushed").inc(len(records))
+
+ def _write(self, records: list[McpIntentRecord], buffer_settings: BufferSettings) -> None:
+ ttl = int(datetime.timedelta(days=buffer_settings.buffer_days).total_seconds())
+ grouped: dict[tuple[int, int, str], list[str]] = defaultdict(list)
+ for record in records:
+ grouped[(record.team_id, record.user_id, record.day)].append(record.value)
+ pipeline = self._redis_client().pipeline(transaction=False)
+ for (team_id, user_id, day), values in grouped.items():
+ key = records_key(team_id, user_id, day)
+ pipeline.rpush(key, *values)
+ pipeline.ltrim(key, -buffer_settings.calls_per_day, -1)
+ pipeline.expire(key, ttl)
+ pipeline.incrby(count_key(team_id, user_id, day), len(values))
+ pipeline.expire(count_key(team_id, user_id, day), ttl)
+ pipeline.sadd(DIRTY_KEY, f"{team_id}:{user_id}")
+ # Without a TTL the set would outlive a disabled buffer.
+ pipeline.expire(DIRTY_KEY, ttl)
+ pipeline.execute()
+
+
+BUFFER = McpIntentBuffer()
diff --git a/products/signals/backend/activity_summary/queue.py b/products/signals/backend/activity_summary/queue.py
index 6e146a0ca165..8af0b986c720 100644
--- a/products/signals/backend/activity_summary/queue.py
+++ b/products/signals/backend/activity_summary/queue.py
@@ -261,6 +261,19 @@ def enrolled_team_ids(config: ActivitySummaryConfig) -> list[int]:
return enrollment(config).team_ids
+def mcp_buffer_team_ids(config: ActivitySummaryConfig) -> list[int]:
+ """The enrolled teams whose MCP intents the buffer keeps."""
+ if not config.mcp_buffer_enabled:
+ return []
+ if not config.mcp_buffer_organization_ids:
+ return enrolled_team_ids(config)
+ # Every web process refreshes this list, so check only the listed organizations' teams, not the full enrollment.
+ teams = Team.objects.filter(
+ organization_id__in=_parse_organization_ids(config.mcp_buffer_organization_ids)
+ ).select_related("organization")
+ return sorted(team.id for team in teams if is_team_enrolled_for_generation(config, team))
+
+
def is_team_enrolled_for_generation(config: ActivitySummaryConfig, team: Team) -> bool:
"""The tick may generate summaries for the team. The single-team form of `enrolled_team_ids`.
diff --git a/products/signals/backend/facade/mcp_intents.py b/products/signals/backend/facade/mcp_intents.py
new file mode 100644
index 000000000000..72448c24d2fd
--- /dev/null
+++ b/products/signals/backend/facade/mcp_intents.py
@@ -0,0 +1,14 @@
+"""Buffer the intents that MCP agents state on API calls, for the activity summary.
+
+`ActivityLoggingMiddleware` calls this on MCP requests, so it does no network I/O.
+"""
+
+from products.signals.backend.activity_summary import mcp_buffer
+
+
+def buffer_mcp_intent(
+ *, team_id: int, user_id: int, session_id: str | None, route_name: str | None, intent: str
+) -> None:
+ mcp_buffer.BUFFER.append(
+ team_id=team_id, user_id=user_id, session_id=session_id, route_name=route_name, intent=intent
+ )
diff --git a/products/signals/backend/test/test_activity_summary_mcp_buffer.py b/products/signals/backend/test/test_activity_summary_mcp_buffer.py
new file mode 100644
index 000000000000..2e0c1038a973
--- /dev/null
+++ b/products/signals/backend/test/test_activity_summary_mcp_buffer.py
@@ -0,0 +1,189 @@
+import datetime
+from uuid import UUID
+
+import time_machine
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+import redis
+import fakeredis
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.signals.backend.activity_summary import mcp_buffer
+from products.signals.backend.activity_summary.mcp_buffer import (
+ CIRCUIT_OPEN_SECONDS,
+ DIRTY_KEY,
+ BufferSettings,
+ McpIntentBuffer,
+ count_key,
+ records_key,
+)
+
+NOW = datetime.datetime(2026, 10, 20, 12, tzinfo=datetime.UTC)
+DAY = "20261020"
+TEAM_ID = 1
+USER_ID = 7
+
+
+def _dropped(reason: str) -> float:
+ return REGISTRY.get_sample_value("activity_summary_mcp_intent_records_total", {"outcome": reason}) or 0.0
+
+
+@time_machine.travel(NOW, tick=False)
+class TestMcpIntentBuffer(SimpleTestCase):
+ def setUp(self) -> None:
+ self.redis = fakeredis.FakeRedis(decode_responses=True)
+ self.now = 1000.0
+
+ def _buffer(self, **kwargs) -> McpIntentBuffer:
+ buffer = McpIntentBuffer(start_thread=False, clock=lambda: self.now, **kwargs)
+ buffer.buffer_settings = BufferSettings(team_ids=frozenset({TEAM_ID}), calls_per_day=2, buffer_days=10)
+ return buffer
+
+ def _append(self, buffer: McpIntentBuffer, intent: str, team_id: int = TEAM_ID) -> None:
+ buffer.append(team_id=team_id, user_id=USER_ID, session_id="s|1", route_name="insight-list", intent=intent)
+
+ def test_flush_writes_the_trimmed_list_the_count_the_ttl_and_the_dirty_member(self) -> None:
+ buffer = self._buffer(redis_client=lambda: self.redis)
+ for intent in ("first", "second", "third"):
+ self._append(buffer, intent)
+ self._append(buffer, "not enrolled", team_id=2)
+
+ buffer.flush()
+
+ key = records_key(TEAM_ID, USER_ID, DAY)
+ assert [record.split("|")[1:] for record in self.redis.lrange(key, 0, -1)] == [
+ ["s 1", "insight-list", "second"],
+ ["s 1", "insight-list", "third"],
+ ]
+ assert self.redis.get(count_key(TEAM_ID, USER_ID, DAY)) == "3"
+ assert 0 < self.redis.ttl(key) <= 10 * 24 * 3600
+ assert 0 < self.redis.ttl(count_key(TEAM_ID, USER_ID, DAY)) <= 10 * 24 * 3600
+ assert self.redis.smembers(DIRTY_KEY) == {f"{TEAM_ID}:{USER_ID}"}
+ assert self.redis.keys("as:mcp:2:*") == []
+
+ def test_a_full_queue_drops_the_record(self) -> None:
+ buffer = self._buffer(queue_size=1, redis_client=lambda: self.redis)
+ dropped = _dropped("dropped_queue_full")
+
+ self._append(buffer, "kept")
+ self._append(buffer, "dropped")
+ buffer.flush()
+
+ assert _dropped("dropped_queue_full") == dropped + 1
+ assert self.redis.get(count_key(TEAM_ID, USER_ID, DAY)) == "1"
+
+ def test_a_failed_flush_opens_the_circuit_until_the_cool_down_ends(self) -> None:
+ client = MagicMock(side_effect=redis.TimeoutError("timed out"))
+ buffer = self._buffer(redis_client=client)
+ self._append(buffer, "lost to the error")
+ buffer.flush()
+ client.side_effect = None
+ client.return_value = self.redis
+
+ self.now += CIRCUIT_OPEN_SECONDS - 1
+ self._append(buffer, "lost to the open circuit")
+ buffer.flush()
+ assert client.call_count == 1
+ assert self.redis.keys("as:mcp:*") == []
+
+ self.now += 2
+ self._append(buffer, "written")
+ buffer.flush()
+ assert [record.split("|")[3] for record in self.redis.lrange(records_key(TEAM_ID, USER_ID, DAY), 0, -1)] == [
+ "written"
+ ]
+
+
+@time_machine.travel(NOW, tick=False)
+class TestMcpIntentCapture(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.redis = fakeredis.FakeRedis(decode_responses=True)
+ self.redis_client = MagicMock(side_effect=redis.ConnectionError("unreachable"))
+ self.buffer = McpIntentBuffer(start_thread=False, redis_client=self.redis_client)
+ self.buffer.buffer_settings = BufferSettings(team_ids=frozenset({self.team.id}))
+ patcher = patch.object(mcp_buffer, "BUFFER", self.buffer)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.client.logout()
+
+ def _personal_api_key(self) -> str:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="MCP", user=self.user, secure_value=hash_key_value(value), scopes=["dashboard:read"]
+ )
+ return value
+
+ def _oauth_token(self, sandbox_task_id: UUID | None) -> str:
+ application = OAuthApplication.objects.create(
+ name="MCP",
+ client_id="mcp-client",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ return OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_mcp_test_token",
+ scope="dashboard:read",
+ expires=timezone.now() + datetime.timedelta(hours=1),
+ scoped_teams=[self.team.id],
+ sandbox_task_id=sandbox_task_id,
+ ).token
+
+ @parameterized.expand(
+ [
+ ("personal api key", "personal_api_key", {}, True),
+ ("own oauth token", "oauth", {}, True),
+ ("sandbox oauth token", "sandbox", {}, False),
+ ("no mcp client header", "personal_api_key", {"HTTP_X_POSTHOG_CLIENT": "posthog-js"}, False),
+ ("no intent", "personal_api_key", {"HTTP_X_POSTHOG_INTENT": ""}, False),
+ ("team not enrolled", "personal_api_key", {"enrolled": False}, False),
+ ("setting off", "personal_api_key", {"setting": False}, False),
+ ]
+ )
+ def test_buffers_only_a_person_s_own_mcp_reads(
+ self, _name: str, credential: str, overrides: dict, buffered: bool
+ ) -> None:
+ if credential == "personal_api_key":
+ token = self._personal_api_key()
+ else:
+ token = self._oauth_token(UUID("019f4c2a-0000-7000-8000-0000000000aa") if credential == "sandbox" else None)
+ if overrides.pop("enrolled", True) is False:
+ self.buffer.buffer_settings = BufferSettings()
+ headers = {
+ "HTTP_AUTHORIZATION": f"Bearer {token}",
+ "HTTP_X_POSTHOG_CLIENT": "mcp",
+ "HTTP_X_POSTHOG_INTENT": "Checking why weekly signups dropped",
+ "HTTP_X_POSTHOG_MCP_SESSION_ID": "session-1",
+ **{key: value for key, value in overrides.items() if key.startswith("HTTP_")},
+ }
+
+ with self.settings(ACTIVITY_SUMMARY_MCP_BUFFER_ENABLED=overrides.get("setting", True)):
+ response = self.client.get(f"/api/environments/{self.team.id}/dashboards/", **headers)
+
+ assert response.status_code == 200, response.content
+ self.redis_client.assert_not_called()
+ self.redis_client.side_effect = None
+ self.redis_client.return_value = self.redis
+ self.buffer.flush()
+ records = self.redis.lrange(records_key(self.team.id, self.user.id, DAY), 0, -1)
+ if buffered:
+ assert [record.split("|")[1:] for record in records] == [
+ ["session-1", "project_dashboards-list", "Checking why weekly signups dropped"]
+ ]
+ else:
+ assert records == []
diff --git a/products/signals/backend/test/test_activity_summary_tick.py b/products/signals/backend/test/test_activity_summary_tick.py
index 72f6a0e25844..c9084015ee31 100644
--- a/products/signals/backend/test/test_activity_summary_tick.py
+++ b/products/signals/backend/test/test_activity_summary_tick.py
@@ -50,6 +50,7 @@ from products.signals.backend.activity_summary.queue import (
is_team_enrolled_for_read,
max_input_chars,
max_update_cost_usd,
+ mcp_buffer_team_ids,
organization_rollout_bucket,
seed_queue,
select_pairs,
@@ -129,8 +130,11 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = [
"min_score": 0,
"view_update_interval_hours": -5,
"cold_start_min_active_days": 2.5,
+ "mcp_buffer_enabled": "yes",
+ "mcp_calls_per_day": 0,
+ "mcp_buffer_days": 10_000,
},
- ActivitySummaryConfig(enabled=True, organization_ids=("org-a",), skip_team_ids=(3,)),
+ ActivitySummaryConfig(enabled=True, organization_ids=("org-a",), skip_team_ids=(3,), mcp_buffer_days=30),
),
(
"a boolean percentage falls back to the default",
@@ -157,6 +161,10 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = [
"min_score": 4.5,
"view_update_interval_hours": 72,
"cold_start_min_active_days": 5,
+ "mcp_buffer_enabled": True,
+ "mcp_buffer_organization_ids": ["org-a"],
+ "mcp_calls_per_day": 20,
+ "mcp_buffer_days": 14,
},
ActivitySummaryConfig(
enabled=True,
@@ -176,6 +184,10 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = [
min_score=4.5,
view_update_interval_hours=72.0,
cold_start_min_active_days=5,
+ mcp_buffer_enabled=True,
+ mcp_buffer_organization_ids=("org-a",),
+ mcp_calls_per_day=20,
+ mcp_buffer_days=14,
),
),
(
@@ -407,6 +419,30 @@ class TestActivitySummaryQueue(BaseTest):
assert sorted(self._select(config)) == sorted([(self.team.id, user.id), (approved.id, user.id)])
+ @parameterized.expand(
+ [
+ ("every_enrolled_team", "none", True, {"own", "other"}),
+ ("listed_organizations", "own", True, {"own"}),
+ ("listed_but_not_enrolled", "own", False, set()),
+ ("invalid_listed_id", "invalid", True, set()),
+ ]
+ )
+ def test_mcp_buffer_team_ids(self, _name: str, listed: str, approved: bool, expected: set[str]) -> None:
+ other = Team.objects.create(organization=Organization.objects.create(name="Other"), name="Other")
+ self.organization.is_ai_data_processing_approved = approved
+ self.organization.save()
+ listed_ids = {"none": (), "own": (str(self.organization.id),), "invalid": ("not-a-uuid",)}[listed]
+ config = ActivitySummaryConfig(
+ enabled=True,
+ enroll_all_approved=True,
+ mcp_buffer_enabled=True,
+ mcp_buffer_organization_ids=listed_ids,
+ )
+ team_ids = {"own": self.team.id, "other": other.id}
+
+ assert mcp_buffer_team_ids(dataclasses.replace(config, mcp_buffer_enabled=False)) == []
+ assert set(mcp_buffer_team_ids(config)) == {team_ids[name] for name in expected}
+
def test_selects_nothing_without_ai_data_processing_approval(self) -> None:
self.organization.is_ai_data_processing_approved = False
self.organization.save()