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.

chore(mcp-analytics): remove dormant session backfill and intent-summary jobs (#60039)

Georgis Andonisb42fa273cd03
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index d23e5c1be075..d93e98b427d5 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -84,14 +84,6 @@ from posthog.temporal.llm_analytics import (
TAGGER_WORKFLOWS as LLM_ANALYTICS_TAGGER_WORKFLOWS,
WORKFLOWS as LLM_ANALYTICS_WORKFLOWS,
)
-from posthog.temporal.mcp_analytics.backfill_sessions import (
- MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES,
- MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS,
-)
-from posthog.temporal.mcp_analytics.summarize_session_intents import (
- MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES,
- MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS,
-)
from posthog.temporal.messaging import (
ACTIVITIES as MESSAGING_ACTIVITIES,
WORKFLOWS as MESSAGING_WORKFLOWS,
@@ -238,9 +230,7 @@ _task_queue_specs = [
+ EXPERIMENTS_WORKFLOWS
+ CLEANUP_PROPDEFS_WORKFLOWS
+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS
- + WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS
- + MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS
- + MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS,
+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,
PROXY_SERVICE_ACTIVITIES
+ DELETE_PERSONS_ACTIVITIES
+ QUOTA_LIMITING_ACTIVITIES
@@ -252,9 +242,7 @@ _task_queue_specs = [
+ EXPERIMENTS_ACTIVITIES
+ CLEANUP_PROPDEFS_ACTIVITIES
+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES
- + WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES
- + MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES
- + MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES,
+ + WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,
),
(
settings.HEALTH_CHECK_TASK_QUEUE,
diff --git a/posthog/temporal/mcp_analytics/__init__.py b/posthog/temporal/mcp_analytics/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py b/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py
deleted file mode 100644
index 747298a14f8d..000000000000
--- a/posthog/temporal/mcp_analytics/backfill_sessions/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
-from posthog.temporal.mcp_analytics.backfill_sessions.workflow import BackfillMCPSessionsWorkflow
-
-MCP_ANALYTICS_BACKFILL_SESSIONS_WORKFLOWS = [
- BackfillMCPSessionsWorkflow,
-]
-
-MCP_ANALYTICS_BACKFILL_SESSIONS_ACTIVITIES = [aggregate_and_upsert_mcp_sessions]
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/activities.py b/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
deleted file mode 100644
index baa83422dc33..000000000000
--- a/posthog/temporal/mcp_analytics/backfill_sessions/activities.py
+++ /dev/null
@@ -1,107 +0,0 @@
-from datetime import UTC, datetime
-from typing import Any
-
-from temporalio import activity
-
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.sync import database_sync_to_async
-from posthog.temporal.common.clickhouse import get_client
-from posthog.temporal.common.logger import get_write_only_logger
-from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
-
-from products.mcp_analytics.backend.models import MCPSession
-
-LOGGER = get_write_only_logger()
-
-
-# Two-pass aggregate:
-# 1. Inner subquery (cheap) — list session ids that received any mcp_tool_call event
-# in the last lookback_hours. These are the only sessions whose Postgres row could be
-# stale.
-# 2. Outer query — re-aggregate the FULL history of each active session id (bounded
-# only by the retention window) so the upsert reflects the complete picture, not just
-# what landed in the lookback. Avoids the corruption that a naive lookback-window
-# aggregate would cause when a long-lived session gets a fresh event late.
-# The grouping key is $mcp_session_id, which the MCP SDK stamps onto every event in
-# the same session. We persist it as MCPSession.session_id since that is the
-# product-facing identifier of an MCP session.
-_AGGREGATE_QUERY = """
-SELECT
- team_id,
- JSONExtractString(properties, '$mcp_session_id') AS session_id,
- toString(min(timestamp)) AS session_start,
- toString(max(timestamp)) AS session_end,
- count() AS tool_call_count,
- groupUniqArrayIf(JSONExtractString(properties, '$mcp_tool_name'), JSONExtractString(properties, '$mcp_tool_name') != '') AS tools_used,
- argMax(distinct_id, timestamp) AS distinct_id,
- argMax(JSONExtractString(properties, '$mcp_client_name'), timestamp) AS mcp_client_name
-FROM events
-WHERE event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_session_id') IN (
- SELECT DISTINCT JSONExtractString(properties, '$mcp_session_id')
- FROM events
- WHERE event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_session_id') != ''
- AND timestamp >= now() - INTERVAL %(lookback_hours)s HOUR
- )
- AND timestamp >= now() - INTERVAL %(retention_days)s DAY
-GROUP BY team_id, session_id
-LIMIT 100000
-FORMAT JSONEachRow
-"""
-
-# How far back we'll look when re-aggregating an active session. Bounded so the outer query
-# can prune events partitions; anything older than this is effectively frozen anyway.
-_RETENTION_DAYS = 7
-
-
-def _parse_clickhouse_ts(value: str) -> datetime:
- parsed = datetime.fromisoformat(value)
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=UTC)
- return parsed
-
-
-@database_sync_to_async
-def _upsert_session(row: dict[str, Any]) -> None:
- session_start = _parse_clickhouse_ts(row["session_start"])
- session_end = _parse_clickhouse_ts(row["session_end"])
-
- # Cross-team activity — backfills sessions for every team in a single ClickHouse pass.
- MCPSession.objects.unscoped().update_or_create(
- team_id=int(row["team_id"]),
- session_id=row["session_id"],
- defaults={
- "session_start": session_start,
- "session_end": session_end,
- "duration_seconds": max(0, int((session_end - session_start).total_seconds())),
- "tool_call_count": int(row.get("tool_call_count") or 0),
- "tools_used": [tool for tool in (row.get("tools_used") or []) if tool],
- "distinct_id": row.get("distinct_id") or "",
- "mcp_client_name": row.get("mcp_client_name") or "",
- },
- )
-
-
[email protected](name="aggregate-and-upsert-mcp-sessions")
-async def aggregate_and_upsert_mcp_sessions(input: BackfillMCPSessionsInput) -> None:
- logger = LOGGER.bind(activity="aggregate-and-upsert-mcp-sessions")
- logger.info("Aggregating MCP sessions from ClickHouse", lookback_hours=input.lookback_hours)
-
- tag_queries(product=Product.MCP, feature=Feature.QUERY, name="mcp_sessions_backfill")
-
- async with get_client() as client:
- rows = await client.read_query_as_jsonl(
- _AGGREGATE_QUERY,
- query_parameters={
- "lookback_hours": int(input.lookback_hours),
- "retention_days": _RETENTION_DAYS,
- },
- )
-
- upserted = 0
- for row in rows:
- await _upsert_session(row)
- upserted += 1
-
- logger.info("MCP session backfill complete", rows_seen=len(rows), upserted=upserted)
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/types.py b/posthog/temporal/mcp_analytics/backfill_sessions/types.py
deleted file mode 100644
index 9b341faa0d33..000000000000
--- a/posthog/temporal/mcp_analytics/backfill_sessions/types.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True)
-class BackfillMCPSessionsInput:
- # How far back to look for *active* mcp_tool_call events on each run. Sessions
- # that received any event in this window get re-aggregated from their full
- # history, so this only needs to span the longest plausible "still-mutating"
- # gap between events on a live session.
- lookback_hours: int = 1
diff --git a/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py b/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py
deleted file mode 100644
index e6370f481506..000000000000
--- a/posthog/temporal/mcp_analytics/backfill_sessions/workflow.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from datetime import timedelta
-
-from temporalio import common, workflow
-
-from posthog.temporal.common.base import PostHogWorkflow
-from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
-from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
-
-
[email protected](name="backfill-mcp-sessions")
-class BackfillMCPSessionsWorkflow(PostHogWorkflow):
- inputs_cls = BackfillMCPSessionsInput
- inputs_optional = True
-
- @workflow.run
- async def run(self, input: BackfillMCPSessionsInput) -> None:
- await workflow.execute_activity(
- aggregate_and_upsert_mcp_sessions,
- input,
- start_to_close_timeout=timedelta(minutes=10),
- retry_policy=common.RetryPolicy(
- maximum_attempts=3,
- initial_interval=timedelta(seconds=30),
- ),
- )
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py b/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py
deleted file mode 100644
index da1137b5e304..000000000000
--- a/posthog/temporal/mcp_analytics/summarize_session_intents/__init__.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
-from posthog.temporal.mcp_analytics.summarize_session_intents.workflow import SummarizeMCPSessionIntentsWorkflow
-
-MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_WORKFLOWS = [
- SummarizeMCPSessionIntentsWorkflow,
-]
-
-MCP_ANALYTICS_SUMMARIZE_SESSION_INTENTS_ACTIVITIES = [summarize_mcp_session_intents]
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py b/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
deleted file mode 100644
index cd2e432b3ddf..000000000000
--- a/posthog/temporal/mcp_analytics/summarize_session_intents/activities.py
+++ /dev/null
@@ -1,198 +0,0 @@
-import os
-import asyncio
-from datetime import timedelta
-
-from django.db import connection
-from django.utils import timezone
-
-import structlog
-from temporalio import activity
-
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from posthog.sync import database_sync_to_async
-from posthog.temporal.common.clickhouse import get_client
-from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
-
-from products.mcp_analytics.backend.models import MCPSession
-
-logger = structlog.get_logger(__name__)
-
-# PostHog's own team — summarised ahead of everyone else so internal dogfooding
-# is never starved by external traffic.
-_PRIORITY_TEAM_ID = 2
-
-# Per-team cap for non-priority teams in a single batch. Stops one team from
-# monopolising the global LLM budget by emitting many unique session ids.
-_PER_TEAM_CAP = 10
-
-# Placeholder written when an MCP session has no recordable tool-call intents.
-# Exported so downstream consumers (e.g. intent clustering) can filter it out
-# of their corpus — clustering an "empty" placeholder produces a meaningless
-# pseudo-cluster in real data.
-NO_INTENT_RECORDED_FALLBACK = "No agent intent was recorded for this session."
-
-SYSTEM_PROMPT = (
- "You summarise what an AI agent was trying to accomplish during a single MCP session. "
- "You are given the per-tool-call intents the agent recorded, in chronological order. "
- "Reply with at most two sentences in third person. "
- "Be concrete: name the actual product, metric, person, or workflow involved — not generic phrases "
- "like 'analytics question' or 'enhance user experience'. "
- "If the intents span unrelated tasks, lead with the dominant one. "
- "Do not list individual tools, do not echo the input verbatim, and do not pad with filler."
-)
-
-_TOOL_CALL_INTENTS_QUERY = """
-SELECT JSONExtractString(properties, '$mcp_intent') AS intent
-FROM events
-WHERE team_id = %(team_id)s
- AND event = 'mcp_tool_call'
- AND JSONExtractString(properties, '$mcp_session_id') = %(session_id)s
- AND JSONExtractString(properties, '$mcp_intent') != ''
-ORDER BY timestamp ASC
-LIMIT 200
-FORMAT JSONEachRow
-"""
-
-
-def _build_user_prompt(intents: list[str]) -> str:
- numbered = "\n".join(f"{i + 1}. {intent}" for i, intent in enumerate(intents))
- return f"Per-tool-call intents (chronological):\n{numbered}\n\nSummarise the agent's overall goal in 2-3 sentences."
-
-
-def _summarize_intents_sync(intents: list[str]) -> str | None:
- """Blocking OpenAI call; callers wrap in asyncio.to_thread for concurrency."""
- if not os.environ.get("OPENAI_API_KEY"):
- logger.warning("openai_api_key_not_set", count=len(intents))
- return None
-
- # Local import keeps the activity importable without the optional dep when the
- # key is unset; we only need OpenAI at the point of an actual summarisation.
- from posthoganalytics.ai.openai import OpenAI
-
- client = OpenAI(max_retries=2)
- response = client.chat.completions.create(
- model="gpt-4o-mini",
- temperature=0.2,
- max_tokens=120,
- timeout=30,
- messages=[
- {"role": "system", "content": SYSTEM_PROMPT},
- {"role": "user", "content": _build_user_prompt(intents)},
- ],
- )
- content = response.choices[0].message.content if response.choices else None
- if not content:
- return None
- return content.strip()
-
-
-_PENDING_SESSIONS_SQL = """
-WITH ranked AS (
- SELECT
- team_id,
- session_id,
- session_end,
- ROW_NUMBER() OVER (PARTITION BY team_id ORDER BY session_end DESC) AS rn,
- (team_id = %(priority_team_id)s) AS is_priority
- FROM posthog_mcp_session
- WHERE intent IS NULL AND session_end < %(cutoff)s
-)
-SELECT team_id, session_id
-FROM ranked
-WHERE is_priority OR rn <= %(per_team_cap)s
-ORDER BY is_priority DESC, session_end DESC
-LIMIT %(batch_size)s
-"""
-
-
-@database_sync_to_async
-def _take_pending_sessions(batch_size: int, idle_minutes: int) -> list[tuple[int, str]]:
- """Pick sessions that are eligible for summarisation.
-
- Eligible = intent is unset AND last event landed more than idle_minutes ago,
- so we don't summarise sessions that may still be receiving tool calls.
- Priority team rows come first; other teams are capped per batch so one noisy
- team can't monopolise the LLM budget.
- """
- cutoff = timezone.now() - timedelta(minutes=idle_minutes)
- with connection.cursor() as cursor:
- cursor.execute(
- _PENDING_SESSIONS_SQL,
- {
- "priority_team_id": _PRIORITY_TEAM_ID,
- "cutoff": cutoff,
- "per_team_cap": _PER_TEAM_CAP,
- "batch_size": batch_size,
- },
- )
- return [(int(team_id), session_id) for team_id, session_id in cursor.fetchall()]
-
-
-@database_sync_to_async
-def _save_intent(team_id: int, session_id: str, intent: str) -> None:
- # Cross-team activity — picks pending rows across all teams in one pass.
- MCPSession.objects.unscoped().filter(team_id=team_id, session_id=session_id).update(intent=intent)
-
-
-async def _fetch_tool_call_intents(team_id: int, session_id: str) -> list[str]:
- async with get_client() as client:
- rows = await client.read_query_as_jsonl(
- _TOOL_CALL_INTENTS_QUERY,
- query_parameters={"team_id": team_id, "session_id": session_id},
- )
- return [row["intent"] for row in rows if row.get("intent")]
-
-
-async def _summarise_one(
- team_id: int,
- session_id: str,
- semaphore: asyncio.Semaphore,
-) -> str:
- """Process one session: fetch intents, call LLM, save. Returns outcome label."""
- async with semaphore:
- intents = await _fetch_tool_call_intents(team_id, session_id)
- if not intents:
- await _save_intent(team_id, session_id, NO_INTENT_RECORDED_FALLBACK)
- return "no_intents"
-
- summary = await asyncio.to_thread(_summarize_intents_sync, intents)
- if not summary:
- return "llm_skipped"
-
- await _save_intent(team_id, session_id, summary)
- return "summarised"
-
-
[email protected](name="summarize-mcp-session-intents")
-async def summarize_mcp_session_intents(input: SummarizeMCPSessionIntentsInput) -> None:
- log = logger.bind(activity="summarize-mcp-session-intents")
- tag_queries(product=Product.MCP, feature=Feature.QUERY, name="mcp_session_intent_summary")
-
- pending = await _take_pending_sessions(input.batch_size, input.idle_minutes)
- log.info(
- "Found sessions awaiting intent summary",
- count=len(pending),
- idle_minutes=input.idle_minutes,
- concurrency=input.concurrency,
- )
-
- if not pending:
- log.info("MCP session intent summary complete", summarised=0, skipped=0)
- return
-
- semaphore = asyncio.Semaphore(max(1, input.concurrency))
- outcomes = await asyncio.gather(
- *(_summarise_one(team_id, session_id, semaphore) for team_id, session_id in pending),
- return_exceptions=False,
- )
-
- summarised = sum(1 for o in outcomes if o == "summarised")
- no_intents = sum(1 for o in outcomes if o == "no_intents")
- llm_skipped = sum(1 for o in outcomes if o == "llm_skipped")
-
- log.info(
- "MCP session intent summary complete",
- summarised=summarised,
- no_intents=no_intents,
- llm_skipped=llm_skipped,
- )
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/types.py b/posthog/temporal/mcp_analytics/summarize_session_intents/types.py
deleted file mode 100644
index 2962e72a776b..000000000000
--- a/posthog/temporal/mcp_analytics/summarize_session_intents/types.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True)
-class SummarizeMCPSessionIntentsInput:
- # How many sessions to summarize per workflow run. The activity dispatches
- # OpenAI calls in parallel up to `concurrency`, so this cap mostly controls
- # OpenAI spend per tick.
- batch_size: int = 100
-
- # Maximum concurrent OpenAI requests in flight inside the activity. Higher
- # values trade memory + risk of OpenAI rate limits for shorter wall-clock.
- concurrency: int = 8
-
- # Skip sessions whose last event is too recent — they may still be active and
- # would have to be re-summarised. Only candidate sessions whose session_end is
- # older than this many minutes are eligible.
- idle_minutes: int = 30
diff --git a/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py b/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py
deleted file mode 100644
index 57e8cbefe9c8..000000000000
--- a/posthog/temporal/mcp_analytics/summarize_session_intents/workflow.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from datetime import timedelta
-
-from temporalio import common, workflow
-
-from posthog.temporal.common.base import PostHogWorkflow
-from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
-from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
-
-
[email protected](name="summarize-mcp-session-intents")
-class SummarizeMCPSessionIntentsWorkflow(PostHogWorkflow):
- inputs_cls = SummarizeMCPSessionIntentsInput
- inputs_optional = True
-
- @workflow.run
- async def run(self, input: SummarizeMCPSessionIntentsInput) -> None:
- await workflow.execute_activity(
- summarize_mcp_session_intents,
- input,
- start_to_close_timeout=timedelta(minutes=10),
- retry_policy=common.RetryPolicy(
- maximum_attempts=2,
- initial_interval=timedelta(seconds=30),
- ),
- )
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 2695147c5a88..3be29e2d8b11 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -57,8 +57,6 @@ from posthog.temporal.llm_analytics.trace_summarization.schedule import (
create_batch_trace_summarization_schedule,
)
from posthog.temporal.logs_alerting.schedule import create_logs_alert_check_schedule
-from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
-from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
from posthog.temporal.messaging.schedule import create_all_realtime_cohort_calculation_schedules
from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputs
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputs
@@ -489,74 +487,6 @@ async def create_replay_count_metrics_schedule(client: Client):
)
-async def create_mcp_sessions_backfill_schedule(client: Client):
- """Create or update the schedule that backfills the MCPSession Postgres table.
-
- Runs every 5 minutes; each run aggregates mcp_tool_call events seen in the last
- 24 hours and upserts one row per (team, session_id) into Postgres so the
- sessions list endpoint can read from Postgres instead of ClickHouse.
- """
- mcp_sessions_backfill_schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- "backfill-mcp-sessions",
- BackfillMCPSessionsInput(),
- id="backfill-mcp-sessions-schedule",
- task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
- retry_policy=common.RetryPolicy(
- maximum_attempts=3,
- ),
- ),
- spec=ScheduleSpec(
- intervals=[ScheduleIntervalSpec(every=timedelta(minutes=5))],
- ),
- )
-
- if await a_schedule_exists(client, "backfill-mcp-sessions-schedule"):
- await a_update_schedule(client, "backfill-mcp-sessions-schedule", mcp_sessions_backfill_schedule)
- else:
- await a_create_schedule(
- client,
- "backfill-mcp-sessions-schedule",
- mcp_sessions_backfill_schedule,
- trigger_immediately=False,
- )
-
-
-async def create_mcp_session_intent_summary_schedule(client: Client):
- """Create or update the schedule that backfills MCPSession.intent with an LLM summary.
-
- Runs every 5 minutes (matches the backfill cadence so new sessions become
- 'complete' quickly). Each run picks up to 100 MCPSession rows whose intent is
- unset and whose last event is older than 30 minutes (so we don't summarise
- sessions that may still be receiving tool calls), then dispatches the LLM
- calls in parallel inside the activity.
- """
- summary_schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- "summarize-mcp-session-intents",
- SummarizeMCPSessionIntentsInput(),
- id="summarize-mcp-session-intents-schedule",
- task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
- retry_policy=common.RetryPolicy(
- maximum_attempts=2,
- ),
- ),
- spec=ScheduleSpec(
- intervals=[ScheduleIntervalSpec(every=timedelta(minutes=5))],
- ),
- )
-
- if await a_schedule_exists(client, "summarize-mcp-session-intents-schedule"):
- await a_update_schedule(client, "summarize-mcp-session-intents-schedule", summary_schedule)
- else:
- await a_create_schedule(
- client,
- "summarize-mcp-session-intents-schedule",
- summary_schedule,
- trigger_immediately=False,
- )
-
-
async def cleanup_legacy_session_summarization_schedules(client: Client):
"""Delete legacy schedules. Any in-flight runs die on their own execution_timeout."""
legacy_schedule_ids = [
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.py
index 18e77e9b03dd..9650c058dc48 100644
--- a/products/mcp_analytics/backend/intent_clustering.py
+++ b/products/mcp_analytics/backend/intent_clustering.py
@@ -33,7 +33,6 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.embedding_worker import EmbeddingResponse, async_generate_embedding
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.team.team import Team
-from posthog.temporal.mcp_analytics.summarize_session_intents.activities import NO_INTENT_RECORDED_FALLBACK
from products.mcp_analytics.backend.models import MCPSession
@@ -45,6 +44,11 @@ DEFAULT_TOP_N_INTENTS = 500
DEFAULT_DISTANCE_THRESHOLD = 0.2
MAX_SAMPLE_INTENTS_PER_CLUSTER = 3
+# Placeholder previously written by the (now-removed) summariser job for sessions with no
+# recordable tool-call intents. Still filtered out of the corpus so it doesn't form a
+# meaningless pseudo-cluster of "empty" sessions.
+NO_INTENT_RECORDED_FALLBACK = "No agent intent was recorded for this session."
+
# How many tool-call steps to show in the per-cluster Sankey before the
# outcome column. Sessions with fewer steps pad with None so the column
# count stays fixed; the UI renders those as an "Ended" node.
diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.py
index baaf97bf6f6e..473774ec2620 100644
--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py
+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py
@@ -15,10 +15,9 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flus
import numpy as np
from parameterized import parameterized
-from posthog.temporal.mcp_analytics.summarize_session_intents.activities import NO_INTENT_RECORDED_FALLBACK
-
from products.mcp_analytics.backend.intent_clustering import (
DEFAULT_DISTANCE_THRESHOLD,
+ NO_INTENT_RECORDED_FALLBACK,
IntentRecord,
_medoid_index,
_routing_entropy,
diff --git a/scripts/drain_mcp_intent_summary.py b/scripts/drain_mcp_intent_summary.py
deleted file mode 100644
index 7d2812cb013d..000000000000
--- a/scripts/drain_mcp_intent_summary.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Drain all NULL-intent MCPSession rows by repeatedly invoking the summary activity.
-
-Loops the activity until no rows are pending, capped at MAX_ITERATIONS for safety.
-
-Usage:
- flox activate -- python scripts/drain_mcp_intent_summary.py
-"""
-
-import os
-import sys
-import asyncio
-
-import django
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
-django.setup()
-
-MAX_ITERATIONS = 10
-BATCH_SIZE = 25
-
-
-async def main() -> None:
- from asgiref.sync import sync_to_async
-
- from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
- from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
-
- from products.mcp_analytics.backend.models import MCPSession
-
- pending_count = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
- sys.stdout.write(f"Sessions pending intent: {pending_count}\n")
-
- for iteration in range(MAX_ITERATIONS):
- if pending_count == 0:
- break
- sys.stdout.write(f"\nIteration {iteration + 1}: summarising up to {BATCH_SIZE} sessions...\n")
- await summarize_mcp_session_intents(SummarizeMCPSessionIntentsInput(batch_size=BATCH_SIZE))
- new_pending = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
- sys.stdout.write(f" pending after: {new_pending}\n")
- if new_pending >= pending_count:
- sys.stdout.write(" No progress made; stopping to avoid infinite loop.\n")
- break
- pending_count = new_pending
-
- final_pending = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
- total = await sync_to_async(MCPSession.objects.unscoped().count)()
- sys.stdout.write(f"\nDone. pending={final_pending} total={total}\n")
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/scripts/validate_mcp_backfill.py b/scripts/validate_mcp_backfill.py
deleted file mode 100644
index 7bebb8e77341..000000000000
--- a/scripts/validate_mcp_backfill.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Quick local validation for the MCP sessions backfill activity.
-
-Runs the same code path the Temporal activity uses, end-to-end:
- ClickHouse aggregate -> Postgres upsert.
-
-Usage:
- flox activate -- python scripts/validate_mcp_backfill.py
-"""
-
-import os
-import sys
-import asyncio
-
-import django
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
-django.setup()
-
-
-async def main() -> None:
- from asgiref.sync import sync_to_async
-
- from posthog.temporal.mcp_analytics.backfill_sessions.activities import aggregate_and_upsert_mcp_sessions
- from posthog.temporal.mcp_analytics.backfill_sessions.types import BackfillMCPSessionsInput
-
- from products.mcp_analytics.backend.models import MCPSession
-
- before = await sync_to_async(MCPSession.objects.unscoped().count)()
- sys.stdout.write(f"MCPSession rows BEFORE: {before}\n")
-
- await aggregate_and_upsert_mcp_sessions(BackfillMCPSessionsInput(lookback_hours=72))
-
- after = await sync_to_async(MCPSession.objects.unscoped().count)()
- sys.stdout.write(f"MCPSession rows AFTER: {after}\n")
- sys.stdout.write(f"Delta: {after - before}\n")
-
- sys.stdout.write("\nFirst 5 rows:\n")
- rows = await sync_to_async(lambda: list(MCPSession.objects.unscoped().order_by("-session_end")[:5]))()
- for row in rows:
- sys.stdout.write(
- f" team={row.team_id} session_id={row.session_id} "
- f"duration={row.duration_seconds}s tools={row.tools_used} "
- f"distinct_id={row.distinct_id!r} client={row.mcp_client_name!r}\n"
- )
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/scripts/validate_mcp_intent_summary.py b/scripts/validate_mcp_intent_summary.py
deleted file mode 100644
index 84e0c6e5dc0a..000000000000
--- a/scripts/validate_mcp_intent_summary.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""End-to-end smoke test for the MCP session intent summary activity.
-
-Runs the same code path the Temporal activity uses:
- Postgres pick -> ClickHouse fetch -> OpenAI -> Postgres update.
-
-Requires OPENAI_API_KEY to be set in the environment.
-
-Usage:
- flox activate -- python scripts/validate_mcp_intent_summary.py
-"""
-
-import os
-import sys
-import asyncio
-
-import django
-
-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
-django.setup()
-
-
-async def main() -> None:
- from asgiref.sync import sync_to_async
-
- from posthog.temporal.mcp_analytics.summarize_session_intents.activities import summarize_mcp_session_intents
- from posthog.temporal.mcp_analytics.summarize_session_intents.types import SummarizeMCPSessionIntentsInput
-
- from products.mcp_analytics.backend.models import MCPSession
-
- pending_before = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
- sys.stdout.write(f"Sessions awaiting intent BEFORE: {pending_before}\n")
-
- if not os.environ.get("OPENAI_API_KEY"):
- sys.stdout.write("OPENAI_API_KEY is not set; activity will mark sessions without intents only.\n")
-
- await summarize_mcp_session_intents(SummarizeMCPSessionIntentsInput(batch_size=5))
-
- pending_after = await sync_to_async(MCPSession.objects.unscoped().filter(intent__isnull=True).count)()
- sys.stdout.write(f"Sessions awaiting intent AFTER: {pending_after}\n")
-
- sys.stdout.write("\nMost recent summaries:\n")
- rows = await sync_to_async(
- lambda: list(MCPSession.objects.unscoped().filter(intent__isnull=False).order_by("-updated_at")[:5])
- )()
- for row in rows:
- sys.stdout.write(f" {row.session_id[:24]}\n {row.intent}\n")
-
-
-if __name__ == "__main__":
- asyncio.run(main())