: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): read the mcp intent buffer in the activity summary build (#126761)
posthog[bot]8616561a0b8a
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex 99e9bba245c1..0008dee17ca2 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -199,6 +199,8 @@ 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.+When the payload also sets `mcp_render_enabled`, the activity summary build reads the buffer and renders one line per MCP session in the summary input.+A failed read gives an empty section and sets `mcp_read_error` in the build's `inputs_used`; it never fails the build.### Client IPdiff --git a/products/signals/backend/activity_summary/config.py b/products/signals/backend/activity_summary/config.pyindex 29fb75a74bdd..6ee0cab8e34f 100644--- a/products/signals/backend/activity_summary/config.py+++ b/products/signals/backend/activity_summary/config.py@@ -107,6 +107,8 @@ class ActivitySummaryConfig:mcp_calls_per_day: int = 50# Must cover the longest gap between two updates of one summary.mcp_buffer_days: int = 10+ # Renders the buffer in the input. Apart from `mcp_buffer_enabled`, so the buffer can fill before the prompt uses it.+ mcp_render_enabled: bool = FalseDISABLED = ActivitySummaryConfig()@@ -250,6 +252,7 @@ def parse_config(payload: Any) -> ActivitySummaryConfig:mcp_buffer_days=min(_positive_int(payload.get("mcp_buffer_days"), defaults.mcp_buffer_days), MAX_MCP_BUFFER_DAYS),+ mcp_render_enabled=_bool(payload.get("mcp_render_enabled"), defaults.mcp_render_enabled),)diff --git a/products/signals/backend/activity_summary/inputs.py b/products/signals/backend/activity_summary/inputs.pyindex 46d20512a9d5..36fc0520a53d 100644--- a/products/signals/backend/activity_summary/inputs.py+++ b/products/signals/backend/activity_summary/inputs.py@@ -1,14 +1,22 @@-"""Read one user's own tasks, activity log rows and views in one project, from in-region Postgres."""+"""Read one user's own tasks, activity log rows and views in one project, from in-region Postgres,+and the calls of the user's MCP agent, from the Redis MCP intent buffer."""import datetime-from collections.abc import Iterable+from collections.abc import Callable, Iterable+from django.conf import settingsfrom django.db.models.fields.json import KeyTextTransform, KeyTransform+import redis+import structlog++from posthog.dataclasses import frozenfrom posthog.models import ActivityLog, FileSystem, FileSystemViewLogfrom posthog.models.file_system.file_system import split_path+from posthog.redis import get_clientfrom products.dashboards.backend.facade.api import dashboards_by_insight+from products.signals.backend.activity_summary.mcp_buffer import count_key, parse_record, records_key, window_daysfrom products.signals.backend.activity_summary.render import (MAX_ACTIVITY_ROWS_PER_PERSON,MAX_TASKS_PER_PERSON,@@ -18,6 +26,7 @@ from products.signals.backend.activity_summary.render import (SCENE_VIEW_TYPE,SCOUT_CLIENT_PREFIX,ActivityItem,+ McpItem,Parent,ParentLookup,TaskItem,@@ -28,6 +37,10 @@ from products.tasks.backend.facade.user_task_summaries import list_user_task_sum# Tasks a person started: in PostHog AI, in Slack, or by hand in the web or desktop app. Scouts,# reports and workflows start tasks under a person's name too, and those are not the person's intent.TASK_ORIGIN_PRODUCTS = ("posthog_ai", "slack", "user_created")+# The build runs on a worker, not a request, so it can wait longer than the writer's `REDIS_TIMEOUT_SECONDS`.+MCP_READ_TIMEOUT_SECONDS = 1.0++logger = structlog.get_logger(__name__)def user_tasks(team_id: int, user_id: int, start: datetime.datetime, end: datetime.datetime) -> list[TaskItem]:@@ -139,3 +152,61 @@ def user_views(team_id: int, user_id: int, start: datetime.datetime, end: dateti))return items+++@frozen+class McpRead:+ """The buffered MCP calls of one user in one project, oldest first, and what the read saw."""++ records: tuple[McpItem, ...] = ()+ # Days whose count is above the length of the stored list: the buffer kept only their latest calls.+ truncated_days: int = 0+ read_error: bool = False+++def _mcp_redis_client() -> redis.Redis:+ return get_client(+ settings.ACTIVITY_SUMMARY_MCP_BUFFER_REDIS_URL or None,+ socket_timeout=MCP_READ_TIMEOUT_SECONDS,+ socket_connect_timeout=MCP_READ_TIMEOUT_SECONDS,+ )+++def user_mcp_records(+ team_id: int,+ user_id: int,+ start: datetime.datetime,+ end: datetime.datetime,+ *,+ max_days: int,+ redis_client: Callable[[], redis.Redis] = _mcp_redis_client,+) -> McpRead:+ """The user's buffered MCP calls in [start, end), from the newest `max_days` UTC days, in one pipeline.++ The buffer is optional context, so this never raises: a failed read returns no records and sets+ `read_error`, and the build goes on with the other sources."""+ if end <= start:+ return McpRead()+ days = window_days(start, end, max_days)+ try:+ pipeline = redis_client().pipeline(transaction=False)+ for day in days:+ pipeline.lrange(records_key(team_id, user_id, day), 0, -1)+ pipeline.mget([count_key(team_id, user_id, day) for day in days])+ *lists, counts = pipeline.execute()+ except Exception:+ logger.warning("activity_summary.mcp_buffer_read_failed", team_id=team_id, user_id=user_id, exc_info=True)+ return McpRead(read_error=True)+ records: list[McpItem] = []+ truncated_days = 0+ for values, count in zip(lists, counts):+ try:+ total = int(count or 0)+ except ValueError:+ total = 0+ truncated_days += total > len(values)+ for value in values:+ record = parse_record(value)+ if record is not None and start <= record.at < end:+ records.append(record)+ return McpRead(records=tuple(records), truncated_days=truncated_days)diff --git a/products/signals/backend/activity_summary/logic.py b/products/signals/backend/activity_summary/logic.pyindex 295d7480974e..6a671b70a7bb 100644--- a/products/signals/backend/activity_summary/logic.py+++ b/products/signals/backend/activity_summary/logic.py@@ -17,12 +17,20 @@ from posthog.dataclasses import frozenfrom posthog.models import Teamfrom products.signals.backend.activity_summary.computed import compute_fields-from products.signals.backend.activity_summary.inputs import activity_parents, user_activity, user_tasks, user_views+from products.signals.backend.activity_summary.inputs import (+ McpRead,+ activity_parents,+ user_activity,+ user_mcp_records,+ user_tasks,+ user_views,+)from products.signals.backend.activity_summary.prompt import PROMPT_VERSION, summary_textfrom products.signals.backend.activity_summary.render import (DEFAULT_LIMITS,RENDER_VERSION,ActivityItem,+ McpItem,Product,RenderedInput,RenderLimits,@@ -140,13 +148,29 @@ class _WindowInputs:tasks: list[TaskItem]activity: list[ActivityItem]views: list[ViewItem]+ mcp: McpRead | None = None++ @property+ def mcp_records(self) -> tuple[McpItem, ...]:+ return self.mcp.records if self.mcp is not None else ()-def _read_inputs(team_id: int, user_id: int, start: datetime.datetime, end: datetime.datetime) -> _WindowInputs:+def _read_inputs(+ team_id: int,+ user_id: int,+ start: datetime.datetime,+ end: datetime.datetime,+ mcp_buffer_days: int | None = None,+) -> _WindowInputs:return _WindowInputs(tasks=user_tasks(team_id, user_id, start, end),activity=user_activity(team_id, user_id, start, end),views=user_views(team_id, user_id, start, end),+ mcp=(+ user_mcp_records(team_id, user_id, start, end, max_days=mcp_buffer_days)+ if mcp_buffer_days is not None+ else None+ ),)@@ -159,6 +183,7 @@ def _render(*,as_of: datetime.datetime,limits: RenderLimits,+ mcp: tuple[McpItem, ...] = (),) -> RenderedInput | None:return build_input(tasks,@@ -168,11 +193,12 @@ def _render(views=views,limits=limits,parents=activity_parents(team_id, activity),+ mcp=mcp,)-def _inputs_used(rendered: RenderedInput, limits: RenderLimits) -> dict[str, Any]:- return {+def _inputs_used(rendered: RenderedInput, limits: RenderLimits, mcp: McpRead | None = None) -> dict[str, Any]:+ used: dict[str, Any] = {"tasks": rendered.n_tasks,"activity_lines": rendered.n_activity_lines,"view_lines": rendered.n_view_lines,@@ -182,6 +208,18 @@ def _inputs_used(rendered: RenderedInput, limits: RenderLimits) -> dict[str, Any"drops": rendered.drops,"limits": dataclasses.asdict(limits),}+ if mcp is not None:+ used.update(+ {+ "mcp_sessions": rendered.mcp_pool,+ "mcp_lines": rendered.n_mcp_lines,+ "mcp_chars": rendered.mcp_chars,+ "mcp_records": len(mcp.records),+ "mcp_truncated_days": mcp.truncated_days,+ "mcp_read_error": mcp.read_error,+ }+ )+ return useddef _call_model(@@ -336,6 +374,7 @@ def update_activity_summary(rebuild_before: datetime.datetime | None = None,max_versions: int = MAX_VERSIONS,max_skip_backoff: datetime.timedelta = MAX_SKIP_BACKOFF,+ mcp_buffer_days: int | None = None,) -> ActivitySummaryUpdate:"""Update the stored activity summary of one user in one project.@@ -347,6 +386,7 @@ def update_activity_summary(empty first profile sets it to `skip_backoff` from now, which doubles with each skip until a good updateresets it. An empty first profile keeps the cost of its model call.A successful update also appends a `UserActivitySummaryVersion` and keeps the latest `max_versions`.+ With `mcp_buffer_days`, the update also reads up to that many UTC days of the MCP intent buffer."""team = Team.objects.select_related("organization").get(id=team_id)if team.organization.is_ai_data_processing_approved is not True:@@ -360,9 +400,9 @@ def update_activity_summary(rebuild = is_stale(stored, rebuild_before)window_start = _input_start(None, now, limits.window_days)start = _input_start(stored.input_watermark if stored and not rebuild else None, now, limits.window_days)- window = _read_inputs(team_id, user_id, start, now)+ window = _read_inputs(team_id, user_id, start, now, mcp_buffer_days)tasks, activity, views = window.tasks, window.activity, window.views- rendered = _render(team_id, user_id, tasks, activity, views, as_of=now, limits=limits)+ rendered = _render(team_id, user_id, tasks, activity, views, as_of=now, limits=limits, mcp=window.mcp_records)if rendered is None or rendered.units < min_units:if not dry_run:_back_off(team_id, user_id, stored, now, max_skip_backoff)@@ -372,8 +412,13 @@ def update_activity_summary(inputs_used={"drops": rendered.drops} if rendered else None,)- inputs_used = _inputs_used(rendered, limits)- watermark = max([task.at for task in tasks] + [item.at for item in activity] + [view.at for view in views])+ inputs_used = _inputs_used(rendered, limits, window.mcp)+ watermark = max(+ [task.at for task in tasks]+ + [item.at for item in activity]+ + [view.at for view in views]+ + [record.at for record in window.mcp_records]+ )# An incremental update reads only the rows after the watermark, so the computed fields read the full window.if start == window_start:computed = compute_fields(tasks, activity, views).as_json()@@ -480,18 +525,19 @@ def render_as_of(*,limits: RenderLimits = DEFAULT_LIMITS,exclude_products: frozenset[Product] = frozenset(),+ mcp_buffer_days: int | None = None,) -> AsOfInput | None:"""The rendered input and computed fields of `[as_of - limits.window_days, as_of)`, or None when nothing renders.Views come from the latest view of each object, so an object opened again after `as_of` is missing."""- window = _read_inputs(team_id, user_id, as_of - datetime.timedelta(days=limits.window_days), as_of)+ window = _read_inputs(team_id, user_id, as_of - datetime.timedelta(days=limits.window_days), as_of, mcp_buffer_days)tasks, activity, views = window.tasks, window.activity, window.viewsexcluded: Counter[str] = Counter()activity, views = without_products(activity, views, exclude_products, excluded)- rendered = _render(team_id, user_id, tasks, activity, views, as_of=as_of, limits=limits)+ rendered = _render(team_id, user_id, tasks, activity, views, as_of=as_of, limits=limits, mcp=window.mcp_records)if rendered is None:return None- inputs_used = _inputs_used(rendered, limits)+ inputs_used = _inputs_used(rendered, limits, window.mcp)inputs_used["drops"] = {**rendered.drops, **excluded}return AsOfInput(rendered=rendered, computed=compute_fields(tasks, activity, views).as_json(), inputs_used=inputs_used@@ -507,11 +553,14 @@ def build_summary_as_of(min_units: int = MIN_UNITS,exclude_products: frozenset[Product] = frozenset(),trace_variant: str | None = None,+ mcp_buffer_days: int | None = None,) -> ActivitySummaryUpdate:"""A summary of one user in one project as of `as_of`, from the inputs before it only.The model gets no previous summary, and the sample seed comes from the `as_of` date. Nothing is written."""- built = render_as_of(team_id, user_id, as_of, limits=limits, exclude_products=exclude_products)+ built = render_as_of(+ team_id, user_id, as_of, limits=limits, exclude_products=exclude_products, mcp_buffer_days=mcp_buffer_days+ )if built is None or built.rendered.units < min_units:return ActivitySummaryUpdate(status=UpdateStatus.SKIPPED_TOO_FEW_UNITS,diff --git a/products/signals/backend/activity_summary/mcp_buffer.py b/products/signals/backend/activity_summary/mcp_buffer.pyindex e53c5c62b274..95d0311277fa 100644--- a/products/signals/backend/activity_summary/mcp_buffer.py+++ b/products/signals/backend/activity_summary/mcp_buffer.py@@ -16,6 +16,7 @@ Redis keys, each with a TTL of `mcp_buffer_days`:- `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.+`inputs.user_mcp_records` reads the buffer through the key and record helpers of this module."""import os@@ -36,10 +37,12 @@ from prometheus_client import Counter, Histogramfrom posthog.dataclasses import frozenfrom posthog.redis import get_client+from products.signals.backend.activity_summary.render import MCP_INTENT_CHARS, McpItem+logger = structlog.get_logger(__name__)QUEUE_SIZE = 10_000-INTENT_MAX_CHARS = 200+INTENT_MAX_CHARS = MCP_INTENT_CHARS# Session ids and route names are much shorter. The cap only bounds a caller-asserted header._FIELD_MAX_CHARS = 100FLUSH_INTERVAL_SECONDS = 1.0@@ -69,6 +72,32 @@ def count_key(team_id: int, user_id: int, day: str) -> str:return f"as:mcp:n:{team_id}:{user_id}:{day}"+def record_day(at: datetime.datetime) -> str:+ """The UTC day of a record, as its keys name it."""+ return at.astimezone(datetime.UTC).strftime("%Y%m%d")+++def window_days(start: datetime.datetime, end: datetime.datetime, max_days: int) -> list[str]:+ """The UTC days that hold the records of [start, end), the newest `max_days` only, oldest first."""+ last = (end - datetime.timedelta(microseconds=1)).astimezone(datetime.UTC).date()+ first = max(start.astimezone(datetime.UTC).date(), last - datetime.timedelta(days=max_days - 1))+ return [(first + datetime.timedelta(days=offset)).strftime("%Y%m%d") for offset in range((last - first).days + 1)]+++def parse_record(value: bytes | str) -> McpItem | None:+ """The record that `build_record` wrote, or None when the value is not one."""+ text = value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value+ parts = text.split("|", 3)+ if len(parts) != 4:+ return None+ ts, session_id, route_name, intent = parts+ try:+ at = datetime.datetime.fromtimestamp(int(ts), tz=datetime.UTC)+ except (ValueError, OverflowError, OSError):+ return None+ return McpItem(at=at, session_id=session_id, route_name=route_name, intent=intent)++@frozenclass McpIntentRecord:team_id: int@@ -100,9 +129,7 @@ def build_record(_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- )+ return McpIntentRecord(team_id=team_id, user_id=user_id, day=record_day(at), value=value)def load_settings() -> BufferSettings:diff --git a/products/signals/backend/activity_summary/prompt.py b/products/signals/backend/activity_summary/prompt.pyindex dc2aef863cc2..3041ba1db87b 100644--- a/products/signals/backend/activity_summary/prompt.py+++ b/products/signals/backend/activity_summary/prompt.py@@ -14,7 +14,7 @@ from django.db import modelsfrom products.signals.backend.activity_summary.render import PRODUCT_LABELS, PROFILE_MAX_CHARS, Product, cap_line-PROMPT_VERSION = 6+PROMPT_VERSION = 7MAX_THEMES = 6# Per-field caps, so one runaway field cannot make the stored summary large. A cut ends at a word boundary.@@ -49,10 +49,11 @@ The input has these parts:- Objects and pages: a list that code computed from the last weeks of activity. Each line starts with a ref. An "o" ref is an object. An object they edited shows the number of days with edits, and "created" when they made it. An object they only opened shows the number of days they opened it, and "not theirs" when someone else made it. A "p" ref is the pages of one product. The list ends with the products they work in and the products they only visit.- Tasks: work the person gave to PostHog AI or the Slack agent. Each line has the day, the tags in brackets and the goal. "(xN)" is the number of runs.- Things they created or changed in PostHog: each line has the day, the action, the type and the name of the object. "(xN)" is the number of changes. "agent" is the reason their coding agent gave for the change.+- What their AI agent looked into over MCP: one line per agent session, with the day, the number of calls and the intents the agent stated, in order. The agent looked these up for the person, and changed nothing. Treat them as the person's interests and open questions. Never write that the person built or changed something because of them.- Things they opened in PostHog: one line per object, or per product for its pages, with the number of days they opened it and the last day.- The previous summary, when there is one.-The tasks and the lines of changes and opens cover only the time since the previous summary. Keep what the previous summary says unless the new activity changes it.+The tasks and the lines of changes, MCP sessions and opens cover only the time since the previous summary. Keep what the previous summary says unless the new activity changes it.How to write:- Be concrete. Name the dashboards, insights, flags, experiments, accounts, features and goals that matter. Use the names that the input uses.@@ -72,7 +73,7 @@ Return JSON:- `profile`: markdown, at most {profile_max_chars} characters, with these sections in this order:- `## Working on`: the threads they build or change, with the objects by name.- `## Keeps an eye on`: what they open again and again but do not change.- - `## Recently asked about`: what they asked PostHog AI or the Slack agent. Only when there are tasks.+ - `## Recently asked about`: what they asked PostHog AI or the Slack agent, and what their agent looked into over MCP. Only when there are tasks or MCP sessions.- `## Earlier context`: what the previous summary says that the new activity does not repeat. Only when there is a previous summary.Leave out a section that has nothing to say. Do not add other sections, such as one for page visits or for evidence.- `recent_shift`: one sentence about what changed since the previous summary, or null when there is no previous summary or no real change."""diff --git a/products/signals/backend/activity_summary/render.py b/products/signals/backend/activity_summary/render.pyindex 999ecb6baac4..71565971c36a 100644--- a/products/signals/backend/activity_summary/render.py+++ b/products/signals/backend/activity_summary/render.py@@ -24,7 +24,7 @@ from posthog.dataclasses import frozen# Bump on any code change to the filters, the default caps, the sampling or the rendered layout, so summaries# stay comparable. Limits from the flag payload go into `inputs_used` instead.-RENDER_VERSION = 8+RENDER_VERSION = 9WINDOW_DAYS = 28RECENCY_HALF_LIFE_DAYS = 7@@ -57,6 +57,13 @@ ACTIVITY_INTENT_CHARS = 160# Distinct agent intents one collapsed line keeps, newest first. They share ACTIVITY_INTENT_CHARS.ACTIVITY_MAX_INTENTS = 2VIEW_LINE_CHARS = 160+MCP_LINES = 10+MCP_LINE_CHARS = 400+MCP_CHAIN_MAX_INTENTS = 6+# The MCP intent buffer cuts an intent to this many characters.+MCP_INTENT_CHARS = 200+# An intent on a long chain keeps at least this many characters, even when the line cap then cuts the chain.+MIN_MCP_INTENT_CHARS = 30SECTIONS_MAX_CHARS = 8000# Hidden reasoning tokens count against the cap too, so a cap near the answer size truncates answers.MAX_COMPLETION_TOKENS = 4000@@ -73,6 +80,8 @@ MIN_BARE_TITLE_WORDS = 8TASKS_HEADER = "Tasks the person gave to PostHog AI or the Slack agent ([tags] goal):"ACTIVITY_HEADER = "Things the person created or changed in PostHog (agent: why their coding agent did it):"VIEWS_HEADER = "Things the person opened in PostHog, by type (days: distinct days in the window; not theirs: someone else made it):"+MCP_HEADER = "What the person's AI agent looked into for them over MCP (one line per session; intents in order):"+MCP_CHAIN_SEPARATOR = " --> "# Helper tasks that a task spawns for itself, such as repository selection, carry the parent's origin.SANDBOX_PROMPT_TITLE_PREFIX = "[sandbox_prompt:"@@ -120,6 +129,20 @@ MIN_BULK_OBJECTS = 10BULK_WINDOW = datetime.timedelta(hours=1)# A task goal seen on this many distinct days is a scheduled job, not a question the person asked.MIN_REPEATED_TASK_DAYS = 4+# The MCP routes an agent calls to orient itself: the current user, project and organization, and skills.+MCP_PLUMBING_ROUTES: frozenset[str] = frozenset(+ {+ "users-detail",+ "projects-detail",+ "projects-list",+ "project_environments-detail",+ "organizations-detail",+ "organizations-list",+ }+)+MCP_PLUMBING_ROUTE_PREFIXES: tuple[str, ...] = ("project_llm_skills-", "project_community_skills-")+# The same chain of intents in this many sessions of the window is a scheduled job, not a person.+MIN_REPEATED_MCP_CHAINS = 4_DIGITS = re.compile(r"\d+")_CAMEL_WORD = re.compile(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+")@@ -242,6 +265,9 @@ class RenderLimits:activity_max_intents: int = _limit(ACTIVITY_MAX_INTENTS, max_value=10)profile_max_chars: int = _limit(PROFILE_MAX_CHARS, max_value=20000)max_completion_tokens: int = _limit(MAX_COMPLETION_TOKENS, max_value=16000)+ mcp_lines: int = _limit(MCP_LINES, max_value=50)+ mcp_line_chars: int = _limit(MCP_LINE_CHARS, max_value=1000)+ mcp_chain_max_intents: int = _limit(MCP_CHAIN_MAX_INTENTS, max_value=20)DEFAULT_LIMITS = RenderLimits()@@ -271,6 +297,10 @@ class Drop(StrEnum):SAMPLE_CAP = "sample_cap"SECTIONS_BUDGET = "sections_budget"EXCLUDED_PRODUCT = "excluded_product"+ MCP_PLUMBING_ROUTE = "mcp_plumbing_route"+ MCP_IN_ACTIVITY = "mcp_in_activity"+ MCP_THIN_SESSION = "mcp_thin_session"+ MCP_REPEATED_CHAIN = "mcp_repeated_chain"@frozen@@ -327,6 +357,18 @@ class ViewItem:not_theirs: bool = False+@frozen+class McpItem:+ """One MCP call of the person's agent, with the intent the agent stated, from the MCP intent buffer.++ `session_id` and `route_name` can be empty."""++ at: datetime.datetime+ session_id: str+ route_name: str+ intent: str++@frozenclass Unit:"""One rendered line, dated by its latest activity."""@@ -335,6 +377,7 @@ class Unit:text: str# Characters of agent intent on the line.intent_chars: int = 0+ intent_keys: frozenset[str] = frozenset()@frozen@@ -346,6 +389,7 @@ class _ActivityLine:created: boolrows: intintent_chars: int = 0+ intent_keys: frozenset[str] = frozenset()@frozen@@ -366,10 +410,14 @@ class RenderedInput:# Activity lines that carry at least one agent intent, and the intent characters on them.intent_lines: int = 0intent_chars: int = 0+ n_mcp_lines: int = 0+ mcp_chars: int = 0+ # MCP sessions that passed the named filters, before the caps.+ mcp_pool: int = 0@propertydef units(self) -> int:- return self.n_tasks + self.n_activity_lines + self.n_view_lines+ return self.n_tasks + self.n_activity_lines + self.n_view_lines + self.n_mcp_linesdef _mask_token(match: re.Match[str]) -> str:@@ -419,6 +467,11 @@ def cap_line(text: str, max_chars: int) -> str:return (cut.rsplit(" ", 1)[0] if " " in cut else cut) + "…"+def intent_key(intent: str) -> str:+ """An agent intent as both sources compare it. The activity log and the MCP buffer cut it at different lengths."""+ return clean_text(intent, MCP_INTENT_CHARS).casefold()++def _day(at: datetime.datetime) -> datetime.date:return at.astimezone(datetime.UTC).date()@@ -501,24 +554,27 @@ def task_units(tasks: Iterable[TaskItem], drops: Counter[str], limits: RenderLimObjectKey = tuple[str, str, str]-def _intent_text(rows: Iterable[ActivityItem], limits: RenderLimits) -> str:- """Up to `limits.activity_max_intents` distinct intents of the rows, newest first, in one shared budget.+def _intent_text(rows: Iterable[ActivityItem], limits: RenderLimits) -> tuple[str, frozenset[str]]:+ """Up to `limits.activity_max_intents` distinct intents of the rows, newest first, in one shared budget,+ and the `intent_key` of each.The budget is at most half the line, so the head of the line always keeps some room."""max_chars = min(limits.activity_intent_chars, limits.activity_line_chars // 2)distinct: dict[str, str] = {}+ keys: set[str] = set()for row in sorted(rows, key=lambda row: row.at, reverse=True):if len(distinct) >= limits.activity_max_intents:breaktext = clean_text(row.intent or "", max_chars * 2)if text:distinct.setdefault(text.casefold(), text)- return cap_line("; ".join(distinct.values()), max_chars)+ keys.add(intent_key(row.intent or ""))+ return cap_line("; ".join(distinct.values()), max_chars), frozenset(keys)def _activity_line(head: str, rows: Sequence[ActivityItem], limits: RenderLimits, *, created: bool) -> _ActivityLine:"""The head cut to the room that the agent intents leave, so a long name cannot push the intents out."""- intent = _intent_text(rows, limits)+ intent, keys = _intent_text(rows, limits)suffix = f" (agent: {intent})" if intent else ""head = cap_line(head, max(limits.activity_line_chars - len(suffix), 1))return _ActivityLine(@@ -527,6 +583,7 @@ def _activity_line(head: str, rows: Sequence[ActivityItem], limits: RenderLimitscreated=created,rows=len(rows),intent_chars=len(intent),+ intent_keys=keys,)@@ -596,7 +653,7 @@ def _group_line(activities = sorted({key[1] for key in children}, key=lambda activity: (activity != "created", activity))head = f"{' and '.join(activities)} {child_text} on {parent_text}: "head = f"- {_day(latest).isoformat()} {head}"- intent = _intent_text(rows, limits)+ intent, _ = _intent_text(rows, limits)suffix_chars = len(f" (agent: {intent})") if intent else 0line = head + _quoted_names(names, limits.activity_line_chars - len(head) - suffix_chars)return _activity_line(line, rows, limits, created=any(row.activity == "created" for row in rows))@@ -839,7 +896,10 @@ def activity_units(ranked = sorted(lines, key=lambda line: (not line.created, -line.rows, -line.at.timestamp(), line.text))kept_lines = _spread_across_days(ranked, drops, limits)return sorted(- (Unit(at=line.at, text=line.text, intent_chars=line.intent_chars) for line in kept_lines),+ (+ Unit(at=line.at, text=line.text, intent_chars=line.intent_chars, intent_keys=line.intent_keys)+ for line in kept_lines+ ),key=lambda unit: (unit.at, unit.text),)@@ -952,6 +1012,83 @@ def view_units(return sorted(units, key=lambda unit: (unit.at, unit.text))+def _is_plumbing_route(route_name: str) -> bool:+ return route_name in MCP_PLUMBING_ROUTES or route_name.startswith(MCP_PLUMBING_ROUTE_PREFIXES)+++@frozen+class _McpSession:+ """The intents of one MCP session, in order, dated by its latest call."""++ at: datetime.datetime+ calls: int+ chain: tuple[str, ...]+++def _mcp_sessions(records: Iterable[McpItem], shown_intents: frozenset[str], drops: Counter[str]) -> list[_McpSession]:+ """The records grouped by session, without plumbing routes and the intents that `shown_intents` holds.++ A record without a session id is its own session. Consecutive equal intents collapse to one."""+ grouped: dict[tuple[str, int], list[McpItem]] = {}+ for index, record in enumerate(records):+ if _is_plumbing_route(record.route_name):+ drops[Drop.MCP_PLUMBING_ROUTE] += 1+ continue+ grouped.setdefault((record.session_id, -1) if record.session_id else ("", index), []).append(record)+ sessions: list[_McpSession] = []+ for calls in grouped.values():+ calls.sort(key=lambda call: call.at)+ chain: list[str] = []+ for call in calls:+ text = clean_text(call.intent, MCP_INTENT_CHARS)+ if not text:+ continue+ if intent_key(call.intent) in shown_intents:+ drops[Drop.MCP_IN_ACTIVITY] += 1+ continue+ if not chain or chain[-1].casefold() != text.casefold():+ chain.append(text)+ if not chain:+ drops[Drop.MCP_THIN_SESSION] += 1+ continue+ sessions.append(_McpSession(at=calls[-1].at, calls=len(calls), chain=tuple(chain)))+ return sessions+++def _mcp_line(session: _McpSession, limits: RenderLimits) -> str:+ """The session's intents in order. A long chain keeps its first intents and its last one, with "…" between."""+ chain = list(session.chain)+ if len(chain) > limits.mcp_chain_max_intents:+ chain = [*chain[: limits.mcp_chain_max_intents - 1], "…", chain[-1]]+ calls = "1 call" if session.calls == 1 else f"{session.calls} calls"+ head = f"- {_day(session.at).isoformat()}, {calls}: "+ # Each intent gets an equal share of the line, so a long first intent cannot push the last one out.+ room = max((limits.mcp_line_chars - len(head)) // len(chain) - len(MCP_CHAIN_SEPARATOR), MIN_MCP_INTENT_CHARS)+ return cap_line(head + MCP_CHAIN_SEPARATOR.join(cap_line(intent, room) for intent in chain), limits.mcp_line_chars)+++def mcp_units(+ records: Iterable[McpItem],+ activity_lines: Iterable[Unit],+ drops: Counter[str],+ limits: RenderLimits = DEFAULT_LIMITS,+) -> list[Unit]:+ """One line per MCP session of the person's agent, with the intents it stated in order.++ An intent that an activity line already shows goes, so a write does not show twice. A chain that+ repeats in `MIN_REPEATED_MCP_CHAINS` or more sessions is a scheduled job, and all its sessions go."""+ shown = frozenset(key for unit in activity_lines for key in unit.intent_keys)+ sessions = _mcp_sessions(records, shown, drops)+ chains = Counter(tuple(_goal_key(intent) for intent in session.chain) for session in sessions)+ units: list[Unit] = []+ for session in sessions:+ if chains[tuple(_goal_key(intent) for intent in session.chain)] >= MIN_REPEATED_MCP_CHAINS:+ drops[Drop.MCP_REPEATED_CHAIN] += 1+ continue+ units.append(Unit(at=session.at, text=_mcp_line(session, limits)))+ return sorted(units, key=lambda unit: (unit.at, unit.text))++def dedupe_latest(units: Iterable[Unit], drops: Counter[str]) -> list[Unit]:"""One unit per distinct text, the latest one, in chronological order."""latest: dict[str, Unit] = {}@@ -1030,13 +1167,15 @@ def build_input(views: Iterable[ViewItem] = (),limits: RenderLimits = DEFAULT_LIMITS,parents: ParentLookup | None = None,+ mcp: Iterable[McpItem] = (),) -> RenderedInput | None:"""The rendered input of one (project, person) pair, or None when nothing survives the filters.Order: the named filters, then the burst cap, then the recency-weighted sample, then the hardbudget, so the sample is drawn from clean units only. `parents` groups activity lines under theobjects that hold them. The views section shows its lines grouped by type after the budget,- because the budget drops the oldest unit of a section first."""+ because the budget drops the oldest unit of a section first. `mcp` holds the calls of the+ person's agent from the MCP intent buffer, and gets its own section after the activity."""drops: Counter[str] = Counter()activity = list(activity)task_pool = burst_cap(dedupe_latest(task_units(tasks, drops, limits), drops), drops, limits.max_units_per_day)@@ -1045,23 +1184,33 @@ def build_input(# Lines that `activity_units` dropped for its line cap or its per-day cap.activity_pool = len(activity_lines) + drops[Drop.SAMPLE_CAP] + drops[Drop.BURST_CAP] - capped_beforeview_lines = view_units(views, activity, drops, limits)- if not task_pool and not activity_lines and not view_lines:+ mcp_pool = burst_cap(+ dedupe_latest(mcp_units(mcp, activity_lines, drops, limits), drops), drops, limits.max_units_per_day+ )+ if not task_pool and not activity_lines and not view_lines and not mcp_pool:return Nonechosen_tasks = sample_units(task_pool, limit=limits.task_lines, as_of=as_of, seed=seed)drops[Drop.SAMPLE_CAP] += len(task_pool) - len(chosen_tasks)- sections = [(TASKS_HEADER, chosen_tasks), (ACTIVITY_HEADER, activity_lines), (VIEWS_HEADER, view_lines)]+ chosen_mcp = sample_units(mcp_pool, limit=limits.mcp_lines, as_of=as_of, seed=seed)+ drops[Drop.SAMPLE_CAP] += len(mcp_pool) - len(chosen_mcp)+ sections = [+ (TASKS_HEADER, chosen_tasks),+ (ACTIVITY_HEADER, activity_lines),+ (MCP_HEADER, chosen_mcp),+ (VIEWS_HEADER, view_lines),+ ]enforce_budget(sections, drops, limits.sections_max_chars)- sections[2] = (VIEWS_HEADER, sorted(sections[2][1], key=lambda unit: unit.text))+ sections[3] = (VIEWS_HEADER, sorted(sections[3][1], key=lambda unit: unit.text))rendered = [_section(header, units) for header, units in sections]text = "\n\n".join(part for part in rendered if part)return RenderedInput(text=text,n_tasks=len(sections[0][1]),n_activity_lines=len(sections[1][1]),- n_view_lines=len(sections[2][1]),+ n_view_lines=len(sections[3][1]),task_chars=len(rendered[0]),activity_chars=len(rendered[1]),- view_chars=len(rendered[2]),+ view_chars=len(rendered[3]),input_chars=len(text),input_tokens_estimate=estimate_tokens(len(text)),drops={str(reason): count for reason, count in sorted(drops.items()) if count},@@ -1069,4 +1218,7 @@ def build_input(activity_pool=activity_pool,intent_lines=sum(1 for unit in sections[1][1] if unit.intent_chars),intent_chars=sum(unit.intent_chars for unit in sections[1][1]),+ n_mcp_lines=len(sections[2][1]),+ mcp_chars=len(rendered[2]),+ mcp_pool=len(mcp_pool),)diff --git a/products/signals/backend/activity_summary/tick.py b/products/signals/backend/activity_summary/tick.pyindex 90c19e40bee7..33406c607cb8 100644--- a/products/signals/backend/activity_summary/tick.py+++ b/products/signals/backend/activity_summary/tick.py@@ -124,6 +124,8 @@ class ActivitySummaryTickPlan:enrollment: EnrollmentCounts = dataclasses.field(default_factory=EnrollmentCounts)view_update_interval_hours: float = VIEW_UPDATE_INTERVAL.total_seconds() / 3600due_by_trigger: dict[str, int] = dataclasses.field(default_factory=dict)+ # The days of the MCP intent buffer each update reads. None when `mcp_render_enabled` is off.+ mcp_buffer_days: int | None = None@frozen@@ -143,6 +145,7 @@ class ActivitySummaryPairInput:# Why the queue picked the pair. A view trigger waits `view_update_interval_hours` after a good update.trigger: str | None = Noneview_update_interval_hours: float | None = None+ mcp_buffer_days: int | None = None@frozen@@ -229,6 +232,7 @@ def plan_tick(limit: int | None, now: datetime.datetime) -> ActivitySummaryTickPstop_reason=stop_reason,rebuild_before=config.rebuild_before,max_versions=config.max_versions,+ mcp_buffer_days=config.mcp_buffer_days if config.mcp_render_enabled else None,)@@ -281,6 +285,7 @@ def capture_generated(team_id: int, user_id: int, update: ActivitySummaryUpdate, trigger: str | None, *, source: str = SOURCE_LIVE) -> None:team = Team.objects.only("uuid", "organization_id").get(id=team_id)+ inputs_used = update.inputs_used or {}# Counts and accounting only. The summary and the rendered input are user content.ph_background_capture()(distinct_id=PIPELINE_DISTINCT_ID,@@ -299,6 +304,10 @@ def capture_generated("cost_usd": update.cost_usd,"latency_ms": update.latency_ms,"inputs_used": update.inputs_used,+ # Top level, so the MCP rollout can be measured without reading Redis. None while the section is off.+ "mcp_sessions": inputs_used.get("mcp_sessions"),+ "mcp_lines": inputs_used.get("mcp_lines"),+ "mcp_read_error": inputs_used.get("mcp_read_error"),"rebuilt": update.rebuilt,"trigger": trigger,"source": source,@@ -331,6 +340,7 @@ def run_pair(input: ActivitySummaryPairInput, *, last_attempt: bool = True) -> Arebuild_before=input.rebuild_before,max_versions=input.max_versions,max_skip_backoff=datetime.timedelta(hours=input.max_skip_backoff_hours),+ mcp_buffer_days=input.mcp_buffer_days,)called_model = update.status in CALLED_MODEL_STATUSESexcept Exception as error:@@ -482,6 +492,7 @@ class ActivitySummaryTickWorkflow:max_skip_backoff_hours=plan.max_skip_backoff_hours,trigger=pair.trigger,view_update_interval_hours=plan.view_update_interval_hours,+ mcp_buffer_days=plan.mcp_buffer_days,),start_to_close_timeout=_PAIR_TIMEOUT,heartbeat_timeout=_PAIR_HEARTBEAT_TIMEOUT,diff --git a/products/signals/backend/management/commands/run_activity_summary.py b/products/signals/backend/management/commands/run_activity_summary.pyindex 6fffd03cb490..8951ff2c560d 100644--- a/products/signals/backend/management/commands/run_activity_summary.py+++ b/products/signals/backend/management/commands/run_activity_summary.py@@ -25,6 +25,12 @@ class Command(BaseCommand):default=None,help="Render limits as JSON, with the clamps of the flag payload, e.g. '{\"max_completion_tokens\": 2000}'.",)+ parser.add_argument(+ "--mcp-buffer-days",+ type=int,+ default=None,+ help="Read this many days of the MCP intent buffer into the input. Off by default.",+ )def handle(self, *args, **options):result = update_activity_summary(@@ -33,6 +39,7 @@ class Command(BaseCommand):dry_run=options["dry_run"],force=options["force"],limits=parse_limits(options["limits"]),+ mcp_buffer_days=options["mcp_buffer_days"],)self.stdout.write(f"status: {result.status}")if result.rendered_input is not None:diff --git a/products/signals/backend/test/test_activity_summary_mcp_buffer.py b/products/signals/backend/test/test_activity_summary_mcp_buffer.pyindex 2e0c1038a973..fae9f68ee2f8 100644--- a/products/signals/backend/test/test_activity_summary_mcp_buffer.py+++ b/products/signals/backend/test/test_activity_summary_mcp_buffer.py@@ -18,6 +18,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.signals.backend.activity_summary import mcp_buffer+from products.signals.backend.activity_summary.inputs import McpRead, user_mcp_recordsfrom products.signals.backend.activity_summary.mcp_buffer import (CIRCUIT_OPEN_SECONDS,DIRTY_KEY,@@ -103,6 +104,66 @@ class TestMcpIntentBuffer(SimpleTestCase):]+class TestUserMcpRecords(SimpleTestCase):+ def setUp(self) -> None:+ self.redis = fakeredis.FakeRedis()++ def _write(self, at: datetime.datetime, session_id: str, intent: str) -> None:+ buffer = McpIntentBuffer(start_thread=False, redis_client=lambda: self.redis)+ buffer.buffer_settings = BufferSettings(team_ids=frozenset({TEAM_ID}), calls_per_day=2, buffer_days=10)+ with time_machine.travel(at, tick=False):+ buffer.append(+ team_id=TEAM_ID, user_id=USER_ID, session_id=session_id, route_name="insight-list", intent=intent+ )+ buffer.flush()++ def test_reads_what_the_writer_wrote_inside_the_window_and_counts_trimmed_days(self) -> None:+ older = NOW - datetime.timedelta(days=2)+ for minutes, intent in ((0, "trimmed"), (1, "before the window"), (2, "kept")):+ self._write(older + datetime.timedelta(minutes=minutes), "s|1", intent)+ self._write(NOW - datetime.timedelta(days=1), "", "kept too")+ self._write(NOW, "s2", "at the end of the window")+ start = older + datetime.timedelta(minutes=1, seconds=30)++ read = user_mcp_records(TEAM_ID, USER_ID, start, NOW, max_days=10, redis_client=lambda: self.redis)+ newest_days = user_mcp_records(TEAM_ID, USER_ID, start, NOW, max_days=2, redis_client=lambda: self.redis)++ assert [(record.session_id, record.route_name, record.intent) for record in read.records] == [+ ("s 1", "insight-list", "kept"),+ ("", "insight-list", "kept too"),+ ]+ assert read.records[0].at == older + datetime.timedelta(minutes=2)+ assert (read.truncated_days, read.read_error) == (1, False)+ assert [record.intent for record in newest_days.records] == ["kept too"]+ assert newest_days.truncated_days == 0++ @parameterized.expand(+ [+ ("missing keys are an empty read", None, McpRead()),+ (+ "a timeout is an empty read with the error set",+ redis.TimeoutError("timed out"),+ McpRead(read_error=True),+ ),+ (+ "a refused connection is an empty read with the error set",+ redis.ConnectionError(),+ McpRead(read_error=True),+ ),+ ]+ )+ def test_a_missing_or_failed_read_never_raises(+ self, _name: str, error: Exception | None, expected: McpRead+ ) -> None:+ client = MagicMock(side_effect=error, return_value=self.redis)++ read = user_mcp_records(+ TEAM_ID, USER_ID, NOW - datetime.timedelta(days=3), NOW, max_days=10, redis_client=client+ )++ assert read == expected++@time_machine.travel(NOW, tick=False)class TestMcpIntentCapture(APIBaseTest):def setUp(self) -> None:diff --git a/products/signals/backend/test/test_activity_summary_render.py b/products/signals/backend/test/test_activity_summary_render.pyindex 6fc01ee5b092..ab0b4c46c6cc 100644--- a/products/signals/backend/test/test_activity_summary_render.py+++ b/products/signals/backend/test/test_activity_summary_render.py@@ -27,11 +27,13 @@ from products.signals.backend.activity_summary.render import (MAX_ACTIVITY_LINES_PER_DAY,MAX_COMPLETION_TOKENS,MAX_UNITS_PER_DAY,+ MCP_HEADER,TASK_LINES,TASKS_HEADER,VIEWS_HEADER,ActivityItem,Drop,+ McpItem,Parent,Product,RenderLimits,@@ -42,6 +44,7 @@ from products.signals.backend.activity_summary.render import (build_input,burst_cap,clean_text,+ mcp_units,sample_units,sampling_seed,task_units,@@ -90,6 +93,10 @@ QUALITY = Parent(scope="Dashboard", item_id="10", name="Quality review")GROWTH = Parent(scope="Dashboard", item_id="11", name="Growth overview")+def _mcp(session_id: str, intent: str, days_ago: float = 1, minutes: int = 0, route: str = "insight-list") -> McpItem:+ return McpItem(at=_at(days_ago, minutes), session_id=session_id, route_name=route, intent=intent)++def _view(view_type: str, ref: str, name: str | None = None, days: int = 1, days_ago: float = 1, not_theirs: bool = False) -> ViewItem:@@ -559,7 +566,7 @@ def test_sampling_is_deterministic_and_favors_recent_units() -> None:assert sum(1 for age in picked_ages if age < 7) > sum(1 for age in picked_ages if age >= 21)-def test_build_input_renders_the_three_sections_in_order() -> None:+def test_build_input_renders_the_four_sections_in_order() -> None:rendered = build_input([_task("why", summary="Asked: why did signups drop?", tags=("growth",), days_ago=3)],[_change("Dashboard", "created", "Growth overview", days_ago=1)],@@ -569,6 +576,7 @@ def test_build_input_renders_the_three_sections_in_order() -> None:_view("insight", "abc", "Weekly signups", days_ago=1),_view("dashboard", "9", "Growth overview", days=3, days_ago=2),],+ mcp=[_mcp("s1", "signups by country", days_ago=2)],)assert rendered is not None@@ -580,17 +588,95 @@ def test_build_input_renders_the_three_sections_in_order() -> None:ACTIVITY_HEADER,'- 2026-10-18 created Dashboard "Growth overview"',"",+ MCP_HEADER,+ "- 2026-10-17, 1 call: signups by country",+ "",VIEWS_HEADER,'- Dashboard "Growth overview": opened 3 days, last 2026-10-17, edited 1 day','- Insight "Weekly signups": opened 1 day, last 2026-10-18',])- assert (rendered.n_tasks, rendered.n_activity_lines, rendered.n_view_lines, rendered.units) == (1, 1, 2, 4)+ assert (rendered.n_tasks, rendered.n_activity_lines, rendered.n_mcp_lines, rendered.n_view_lines) == (1, 1, 1, 2)+ assert rendered.units == 5assert rendered.input_chars == len(rendered.text)assert build_input([_task("root cause")], [], as_of=AS_OF, seed=1) is Noneassert build_input([], [], as_of=AS_OF, seed=1, views=[_view("scene", "Settings")]) is None+def test_mcp_units_assemble_each_session_in_order_and_cap_a_long_chain() -> None:+ records = [+ _mcp("s1", "signups by country", days_ago=0, minutes=5),+ _mcp("s1", "why signups dropped", days_ago=0, minutes=-10),+ _mcp("s2", "check error rates", days_ago=0, minutes=-8),+ _mcp("s1", "Why signups dropped", days_ago=0, minutes=-5),+ *(_mcp("s3", f"step {n}", days_ago=2, minutes=n) for n in range(1, 9)),+ ]+ drops: Counter[str] = Counter()++ units = mcp_units(records, [], drops, RenderLimits(mcp_chain_max_intents=3))++ assert [unit.text for unit in units] == [+ "- 2026-10-17, 8 calls: step 1 --> step 2 --> … --> step 8",+ "- 2026-10-18, 1 call: check error rates",+ "- 2026-10-19, 3 calls: why signups dropped --> signups by country",+ ]+ assert drops == Counter()+++KEEPER = _mcp("k", "why signups dropped", days_ago=3)+++ [+ (+ "a plumbing route says nothing about the work",+ [+ _mcp("s1", "who am I", route="users-detail"),+ _mcp("s1", "load the skill", route="project_llm_skills-list"),+ ],+ [],+ [],+ {Drop.MCP_PLUMBING_ROUTE: 2},+ ),+ (+ "an intent an activity line shows is not shown twice",+ [_mcp("s1", "Split the funnel by plan"), _mcp("s1", "check the split", minutes=1)],+ [_change("Insight", "updated", "Signup funnel", intent="split the funnel by plan")],+ ["- 2026-10-18, 2 calls: check the split"],+ {Drop.MCP_IN_ACTIVITY: 1},+ ),+ (+ "a session left with no intent goes",+ [_mcp("s1", "Split the funnel by plan")],+ [_change("Insight", "updated", "Signup funnel", intent="Split the funnel by plan")],+ [],+ {Drop.MCP_IN_ACTIVITY: 1, Drop.MCP_THIN_SESSION: 1},+ ),+ (+ "a chain repeated in many sessions is a scheduled job",+ [_mcp(f"s{n}", f"refresh digest {n}", days_ago=n) for n in range(1, 5)],+ [],+ [],+ {Drop.MCP_REPEATED_CHAIN: 4},+ ),+ ]+)+def test_mcp_units_drop_rules(+ _name: str,+ records: list[McpItem],+ activity: list[ActivityItem],+ expected: list[str],+ expected_drops: dict[str, int],+) -> None:+ drops: Counter[str] = Counter()+ activity_lines = activity_units(activity, Counter())++ units = mcp_units([*records, KEEPER], activity_lines, drops)++ assert [unit.text for unit in units] == ["- 2026-10-16, 1 call: why signups dropped", *expected]+ assert dict(drops) == expected_drops++def test_view_units_name_products_count_edits_and_drop_what_says_nothing() -> None:drops: Counter[str] = Counter()views = [diff --git a/products/signals/backend/test/test_activity_summary_tick.py b/products/signals/backend/test/test_activity_summary_tick.pyindex c9084015ee31..b44c85cd7412 100644--- a/products/signals/backend/test/test_activity_summary_tick.py+++ b/products/signals/backend/test/test_activity_summary_tick.py@@ -131,6 +131,7 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = ["view_update_interval_hours": -5,"cold_start_min_active_days": 2.5,"mcp_buffer_enabled": "yes",+ "mcp_render_enabled": 1,"mcp_calls_per_day": 0,"mcp_buffer_days": 10_000,},@@ -165,6 +166,7 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = ["mcp_buffer_organization_ids": ["org-a"],"mcp_calls_per_day": 20,"mcp_buffer_days": 14,+ "mcp_render_enabled": True,},ActivitySummaryConfig(enabled=True,@@ -188,6 +190,7 @@ _CONFIG_CASES: list[tuple[str, Any, ActivitySummaryConfig]] = [mcp_buffer_organization_ids=("org-a",),mcp_calls_per_day=20,mcp_buffer_days=14,+ mcp_render_enabled=True,),),(@@ -934,6 +937,7 @@ def _plan(pairs: int, **overrides: Any) -> ActivitySummaryTickPlan:"enrollment": EnrollmentCounts(qualifying_organizations=3, enrolled_organizations=2, enrolled_teams=4),"due_by_trigger": {"activity": 1, "views": pairs - 1},"stop_reason": None,+ "mcp_buffer_days": 10,}return ActivitySummaryTickPlan(**{**fields, **overrides})@@ -1006,7 +1010,9 @@ async def test_the_tick_bounds_concurrency_and_stops_at_the_daily_caps_and_the_eresult, peak, captured, pair_inputs = await _run_tick(plan, pair_cost, pair_status)assert peak <= plan.max_concurrency- assert {(pair.trigger, pair.view_update_interval_hours) for pair in pair_inputs} == {("views", 168.0)}+ assert {(pair.trigger, pair.view_update_interval_hours, pair.mcp_buffer_days) for pair in pair_inputs} == {+ ("views", 168.0, 10)+ }assert result.due_by_trigger == plan.due_by_triggerassert (result.picked, result.statuses, result.stop_reason) == (picked, {pair_status: picked}, stop_reason)assert result.tiers == plan.tiersdiff --git a/products/signals/backend/test/test_activity_summary_update.py b/products/signals/backend/test/test_activity_summary_update.pyindex d584629e4018..4732038f4a4e 100644--- a/products/signals/backend/test/test_activity_summary_update.py+++ b/products/signals/backend/test/test_activity_summary_update.py@@ -13,6 +13,7 @@ from posthog.models import ActivityLog, FileSystem, FileSystemViewLog, Userfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.facade.models import Insight+from products.signals.backend.activity_summary import mcp_bufferfrom products.signals.backend.activity_summary.inputs import user_activityfrom products.signals.backend.activity_summary.logic import (ActivitySummaryUpdate,@@ -21,7 +22,7 @@ from products.signals.backend.activity_summary.logic import (update_activity_summary,)from products.signals.backend.activity_summary.prompt import PROMPT_VERSION-from products.signals.backend.activity_summary.render import RENDER_VERSION, Product, RenderLimits+from products.signals.backend.activity_summary.render import MCP_HEADER, RENDER_VERSION, Product, RenderLimitsfrom products.signals.backend.models import UserActivitySummary, UserActivitySummaryVersionfrom products.signals.backend.test.test_activity_summary_render import FakeLLM@@ -188,6 +189,48 @@ class TestUpdateActivitySummary(BaseTest):]assert result.inputs_used["drops"] == {"grouped_into_parent": 2}+ def test_the_mcp_buffer_reaches_the_input_only_when_enabled_and_moves_the_watermark(self) -> None:+ client = mcp_buffer._redis_client()+ self.addCleanup(lambda: [client.delete(key) for key in client.keys("as:mcp:*")])+ buffer = mcp_buffer.McpIntentBuffer(start_thread=False)+ buffer.buffer_settings = mcp_buffer.BufferSettings(team_ids=frozenset({self.team.id}))+ newest = NOW - datetime.timedelta(days=1) + datetime.timedelta(minutes=1)+ for at, intent in (+ (newest - datetime.timedelta(minutes=1), "why signups dropped"),+ (newest, "signups by country"),+ ):+ with time_machine.travel(at, tick=False):+ buffer.append(+ team_id=self.team.id, user_id=self.user.id, session_id="s1", route_name=None, intent=intent+ )+ buffer.flush()+ self._changes(3, days_ago=2)++ off = self._update(FakeLLM([ANSWER]), dry_run=True)+ on = self._update(FakeLLM([ANSWER]), mcp_buffer_days=10)++ assert off.rendered_input is not None and MCP_HEADER not in off.rendered_input+ assert off.inputs_used is not None and "mcp_records" not in off.inputs_used+ assert on.status == UpdateStatus.OK and on.rendered_input is not None+ section = f"{MCP_HEADER}\n- 2026-10-18, 2 calls: why signups dropped --> signups by country"+ assert section in on.rendered_input+ assert on.inputs_used is not None+ assert {key: value for key, value in on.inputs_used.items() if key.startswith("mcp_")} == {+ "mcp_sessions": 1,+ "mcp_lines": 1,+ "mcp_chars": len(section),+ "mcp_records": 2,+ "mcp_truncated_days": 0,+ "mcp_read_error": False,+ }+ stored = self._stored()+ assert stored is not None and stored.input_watermark == newest++ self._changes(3, days_ago=0.5)+ with time_machine.travel(NOW + datetime.timedelta(days=2), tick=False):+ later = self._update(FakeLLM([ANSWER]), mcp_buffer_days=10)+ assert later.inputs_used is not None and later.inputs_used["mcp_records"] == 0+@parameterized.expand([("an older prompt version", {"prompt_version": PROMPT_VERSION - 1}, {}, True),