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(mcp-analytics): generate session intent on demand (#60066)

Georgis Andonis8eb1e99cf404
diff --git a/products/mcp_analytics/backend/facade/api.py b/products/mcp_analytics/backend/facade/api.py
index 2dbd93fe3e55..81cd3fd67254 100644
--- a/products/mcp_analytics/backend/facade/api.py
+++ b/products/mcp_analytics/backend/facade/api.py
@@ -58,6 +58,15 @@ def list_mcp_tool_calls(team: Team, session_id: str) -> list[contracts.MCPToolCa
return logic.list_mcp_tool_calls(team, session_id=session_id)
+def generate_session_intent(team: Team, session_id: str) -> str:
+ """Generate (or return the cached) intent summary for an MCP session.
+
+ Shared entry point for the UI's on-demand button and any future caller
+ (e.g. clustering). Persists the result to ``MCPSession.intent``.
+ """
+ return logic.generate_session_intent(team, session_id=session_id)
+
+
def get_intent_cluster_snapshot(team: Team) -> contracts.IntentClusterSnapshot:
return logic.get_intent_cluster_snapshot(team)
diff --git a/products/mcp_analytics/backend/facade/contracts.py b/products/mcp_analytics/backend/facade/contracts.py
index 847f4d4e37dc..73245d14bfdf 100644
--- a/products/mcp_analytics/backend/facade/contracts.py
+++ b/products/mcp_analytics/backend/facade/contracts.py
@@ -5,6 +5,14 @@ from uuid import UUID
from .enums import SubmissionKind
+class IntentGenerationUnavailable(RuntimeError):
+ """Raised when session-intent generation can't complete (LLM unconfigured or request failed).
+
+ Part of the facade contract: callers (e.g. the presentation layer) catch this to surface a
+ clean error instead of a 500.
+ """
+
+
@dataclass(frozen=True)
class Submission:
id: UUID
diff --git a/products/mcp_analytics/backend/intent_generation.py b/products/mcp_analytics/backend/intent_generation.py
new file mode 100644
index 000000000000..03f7301e7e9d
--- /dev/null
+++ b/products/mcp_analytics/backend/intent_generation.py
@@ -0,0 +1,104 @@
+"""On-demand session-intent summarisation.
+
+Given an MCP session, fetch its per-tool-call ``$mcp_intent``s from ClickHouse
+and condense them into a short natural-language summary via an LLM. Pure
+generation only — caching and persistence live in ``logic.generate_session_intent``.
+"""
+
+from django.conf import settings
+
+import openai
+import posthoganalytics
+from posthoganalytics.ai.openai import OpenAI
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+
+from products.mcp_analytics.backend.facade.contracts import IntentGenerationUnavailable
+
+MCP_TOOL_CALL_EVENT = "mcp_tool_call"
+INTENT_MODEL = "gpt-4.1-mini"
+MAX_INTENTS = 500
+# Persisted (and returned) when a session has no recorded intents, so callers
+# get a definitive answer and we don't re-query ClickHouse on the next request.
+NO_INTENT_MESSAGE = "No agent intent was recorded for this session."
+
+SYSTEM_PROMPT = (
+ "You are given the per-tool-call intents an AI agent recorded during one MCP session, in "
+ "chronological order. Summarise the agent's overall goal in at most two sentences — aim for "
+ "under 20 words total. "
+ "State the goal directly; do NOT start with 'The agent', 'The user', 'This session', or similar. "
+ "Be concrete: name the actual product, metric, person, or workflow involved — never generic "
+ "phrases like 'analytics question' or 'data exploration'. "
+ "If the intents span unrelated tasks, describe only the dominant one. "
+ "Do not list tools, echo the input, or add filler. "
+ "Example: 'Investigating why signup funnel conversion dropped last week.'"
+)
+
+_SESSION_INTENTS_SQL = """
+SELECT toString(properties.$mcp_intent) AS intent
+FROM events
+WHERE event = {event}
+ AND properties.$mcp_session_id = {session_id}
+ AND coalesce(properties.$mcp_intent, '') != ''
+ORDER BY timestamp ASC
+LIMIT {limit}
+"""
+
+
+def fetch_session_intents(team: Team, session_id: str) -> list[str]:
+ """Return the session's recorded ``$mcp_intent``s in chronological order."""
+ query = parse_select(
+ _SESSION_INTENTS_SQL,
+ placeholders={
+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
+ "session_id": ast.Constant(value=session_id),
+ "limit": ast.Constant(value=MAX_INTENTS),
+ },
+ )
+ with tags_context(
+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_session_intent"
+ ):
+ response = execute_hogql_query(query=query, team=team)
+ return [str(row[0]) for row in (response.results or []) if row[0]]
+
+
+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 at most two short, concrete sentences."
+
+
+def summarize_intents(intents: list[str], team: Team) -> str:
+ """Condense the intents via the LLM. Blocking — the endpoint runs it inline.
+
+ Raises ``IntentGenerationUnavailable`` when the LLM is unconfigured or the request fails,
+ so the endpoint can answer with a clean 503 rather than a 500.
+ """
+ if not settings.OPENAI_API_KEY:
+ raise IntentGenerationUnavailable("OPENAI_API_KEY is not configured")
+
+ client = OpenAI(posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL)
+ try:
+ response = client.chat.completions.create( # type: ignore
+ model=INTENT_MODEL,
+ temperature=0,
+ max_tokens=90,
+ timeout=30,
+ messages=[
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": _build_user_prompt(intents)},
+ ],
+ user=f"team/{team.id}/mcp-analytics-session-intent",
+ posthog_properties={"ai_product": "mcp_analytics", "ai_feature": "session-intent-generation"},
+ )
+ except openai.OpenAIError as e:
+ raise IntentGenerationUnavailable("LLM request failed") from e
+ content = response.choices[0].message.content if response.choices else None
+ summary = (content or "").strip()
+ if not summary:
+ raise IntentGenerationUnavailable("LLM returned an empty summary")
+ return summary
diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.py
index afd486385ed7..20973d33350c 100644
--- a/products/mcp_analytics/backend/logic.py
+++ b/products/mcp_analytics/backend/logic.py
@@ -16,8 +16,9 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.utils import generate_cache_key
+from products.mcp_analytics.backend import intent_generation
from products.mcp_analytics.backend.facade import contracts, enums
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
MCP_TOOL_CALL_EVENT = "mcp_tool_call"
@@ -229,12 +230,37 @@ def _row_to_session_dict(row: tuple[Any, ...]) -> dict[str, Any]:
def _attach_intents(team: Team, session_ids: list[str]) -> dict[str, str]:
"""Look up persisted session intents keyed by session_id.
- Inert for now: the ad-hoc summary endpoint (separate PR) will persist intents
- in a dedicated MCPSessionIntent table, and this becomes a single indexed
- lookup over the page's session_ids. Kept as a seam so wiring intent in later
- is a pure addition rather than a listing rewrite.
+ A single indexed read over the page's session_ids against MCPSession; sessions
+ whose intent hasn't been generated yet are simply absent. Intents are produced
+ on demand via ``generate_session_intent``.
"""
- return {}
+ if not session_ids:
+ return {}
+ rows = MCPSession.objects.filter(team=team, session_id__in=session_ids).values_list("session_id", "intent")
+ return {session_id: intent for session_id, intent in rows if intent}
+
+
+def generate_session_intent(team: Team, session_id: str) -> str:
+ """Return the session's intent summary, generating and persisting it on first request.
+
+ Cache-on-empty: an existing non-empty ``MCPSession.intent`` is returned as-is. Otherwise the
+ session's recorded ``$mcp_intent``s are summarised by an LLM and persisted (one row per
+ ``(team, session_id)``). A session with no recorded intents returns ``NO_INTENT_MESSAGE``
+ without an LLM call and without persisting anything, so it stays retryable and the listing
+ doesn't surface a non-intent as an intent.
+ Raises ``contracts.IntentGenerationUnavailable`` if the LLM is unreachable.
+ """
+ existing = MCPSession.objects.filter(team=team, session_id=session_id).values_list("intent", flat=True).first()
+ if existing:
+ return existing
+
+ intents = intent_generation.fetch_session_intents(team, session_id)
+ if not intents:
+ return intent_generation.NO_INTENT_MESSAGE
+
+ summary = intent_generation.summarize_intents(intents, team)
+ MCPSession.objects.update_or_create(team=team, session_id=session_id, defaults={"intent": summary})
+ return summary
def _resolve_persons(team_id: int, distinct_ids: list[str]) -> dict[str, Person]:
diff --git a/products/mcp_analytics/backend/presentation/serializers.py b/products/mcp_analytics/backend/presentation/serializers.py
index 26298305e6de..00232f724c8b 100644
--- a/products/mcp_analytics/backend/presentation/serializers.py
+++ b/products/mcp_analytics/backend/presentation/serializers.py
@@ -177,7 +177,17 @@ class MCPSessionSerializer(serializers.Serializer):
)
intent = serializers.CharField(
read_only=True,
- help_text="LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs.",
+ help_text="LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until generated on demand via the generate_intent endpoint.",
+ )
+
+
+class MCPSessionIntentSerializer(serializers.Serializer):
+ session_id = serializers.CharField(
+ read_only=True, help_text="$mcp_session_id the intent summary was generated for."
+ )
+ intent = serializers.CharField(
+ read_only=True,
+ help_text="LLM-generated summary (at most two sentences) of the agent's overall goal for the session.",
)
diff --git a/products/mcp_analytics/backend/presentation/views.py b/products/mcp_analytics/backend/presentation/views.py
index 51c29f4b2076..9f1598bbccba 100644
--- a/products/mcp_analytics/backend/presentation/views.py
+++ b/products/mcp_analytics/backend/presentation/views.py
@@ -26,6 +26,7 @@ from .serializers import (
MCPFeedbackCreateSerializer,
MCPIntentClusterSnapshotSerializer,
MCPMissingCapabilityCreateSerializer,
+ MCPSessionIntentSerializer,
MCPSessionSerializer,
MCPToolCallSerializer,
)
@@ -200,6 +201,31 @@ class MCPSessionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# The field exists because the viewset's paginator shapes the response schema.
return Response({"results": serializer.data, "has_next": False})
+ @extend_schema(
+ operation_id="mcp_analytics_sessions_generate_intent",
+ description=(
+ "Generate (or return the cached) LLM summary of the agent's goal for a session, derived from its "
+ "recorded $mcp_intents. The first call summarises and persists the result; subsequent calls return "
+ "the stored summary."
+ ),
+ request=None,
+ responses={200: MCPSessionIntentSerializer},
+ )
+ @action(detail=True, methods=["post"], url_path="generate_intent")
+ def generate_intent(self, request: Request, pk: str | None = None, *args: Any, **kwargs: Any) -> Response:
+ session_id = str(pk or "")
+ if not session_id:
+ return Response({"detail": "session_id is required."}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ intent = api.generate_session_intent(self.team, session_id=session_id)
+ except contracts.IntentGenerationUnavailable:
+ return Response(
+ {"detail": "Intent generation is unavailable (LLM not configured)."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ serializer = MCPSessionIntentSerializer({"session_id": session_id, "intent": intent})
+ return Response(serializer.data)
+
@extend_schema(tags=["mcp_analytics"])
class MCPIntentClusterViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
diff --git a/products/mcp_analytics/backend/tests/test_api.py b/products/mcp_analytics/backend/tests/test_api.py
index 4b559a85106f..0e42a60f94df 100644
--- a/products/mcp_analytics/backend/tests/test_api.py
+++ b/products/mcp_analytics/backend/tests/test_api.py
@@ -1,13 +1,16 @@
from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
+from unittest.mock import patch
from django.core.cache import cache
from posthog.models.utils import uuid7
+from products.mcp_analytics.backend import intent_generation
from products.mcp_analytics.backend.facade import api, contracts, enums
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPSession
+from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
def _sorted_uuid7s(n: int) -> list[str]:
@@ -73,7 +76,7 @@ class TestMCPAnalyticsFacade(APIBaseTest):
assert submissions[0].kind == enums.SubmissionKind.MISSING_CAPABILITY
-class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
+class TestListMCPSessions(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
# Listing results are cached briefly; clear so each test sees fresh data.
@@ -288,3 +291,87 @@ class TestListMCPSessions(ClickhouseTestMixin, APIBaseTest):
# order — the two pages cover every session in id-ASC order, no skips/dupes.
paged = [s.session_id for s in first.results] + [s.session_id for s in second.results]
assert paged == ids
+
+
+class TestGenerateSessionIntent(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _seed_intent_event(self, session_id: str, intent: str, tool: str = "query_run") -> None:
+ _create_event(
+ team=self.team,
+ event="mcp_tool_call",
+ distinct_id="seed",
+ timestamp=datetime.now(tz=UTC),
+ properties={"$mcp_session_id": session_id, "$mcp_tool_name": tool, "$mcp_intent": intent},
+ )
+
+ def test_returns_cached_intent_without_calling_llm(self) -> None:
+ session_id = str(uuid7())
+ MCPSession.objects.create(team=self.team, session_id=session_id, intent="already summarised")
+
+ with patch.object(intent_generation, "summarize_intents") as mock_summarize:
+ result = api.generate_session_intent(self.team, session_id=session_id)
+
+ assert result == "already summarised"
+ mock_summarize.assert_not_called()
+
+ def test_generates_persists_and_returns_summary(self) -> None:
+ session_id = str(uuid7())
+ self._seed_intent_event(session_id, "check the signups funnel")
+ self._seed_intent_event(session_id, "compare to last week")
+
+ with patch.object(
+ intent_generation, "summarize_intents", return_value="Investigating signup funnel trends."
+ ) as mock:
+ result = api.generate_session_intent(self.team, session_id=session_id)
+
+ assert result == "Investigating signup funnel trends."
+ mock.assert_called_once()
+ assert (
+ MCPSession.objects.get(team=self.team, session_id=session_id).intent
+ == "Investigating signup funnel trends."
+ )
+
+ def test_second_call_returns_persisted_without_regenerating(self) -> None:
+ session_id = str(uuid7())
+ self._seed_intent_event(session_id, "check the signups funnel")
+
+ with patch.object(intent_generation, "summarize_intents", return_value="First summary.") as mock:
+ api.generate_session_intent(self.team, session_id=session_id)
+ again = api.generate_session_intent(self.team, session_id=session_id)
+
+ assert again == "First summary."
+ mock.assert_called_once()
+
+ def test_no_recorded_intents_returns_message_without_calling_llm_or_persisting(self) -> None:
+ session_id = str(uuid7())
+ # mcp_tool_call event without a $mcp_intent property.
+ _create_event(
+ team=self.team,
+ event="mcp_tool_call",
+ distinct_id="seed",
+ timestamp=datetime.now(tz=UTC),
+ properties={"$mcp_session_id": session_id, "$mcp_tool_name": "query_run"},
+ )
+
+ with patch.object(intent_generation, "summarize_intents") as mock_summarize:
+ result = api.generate_session_intent(self.team, session_id=session_id)
+
+ assert result == intent_generation.NO_INTENT_MESSAGE
+ mock_summarize.assert_not_called()
+ # Not persisted — the session stays retryable and the listing doesn't show a non-intent.
+ assert not MCPSession.objects.filter(team=self.team, session_id=session_id).exists()
+
+ def test_list_attaches_persisted_intent(self) -> None:
+ session_id = str(uuid7())
+ self._seed_intent_event(session_id, "raw per-call intent")
+ MCPSession.objects.create(team=self.team, session_id=session_id, intent="Persisted summary.")
+
+ sessions = [
+ s for s in api.list_mcp_sessions(self.team, limit=50, offset=0).results if s.session_id == session_id
+ ]
+
+ assert len(sessions) == 1
+ assert sessions[0].intent == "Persisted summary."
diff --git a/products/mcp_analytics/backend/tests/test_presentation.py b/products/mcp_analytics/backend/tests/test_presentation.py
index 594cbc657fc1..dc21e9619113 100644
--- a/products/mcp_analytics/backend/tests/test_presentation.py
+++ b/products/mcp_analytics/backend/tests/test_presentation.py
@@ -4,7 +4,8 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
-from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot
+from products.mcp_analytics.backend import intent_generation
+from products.mcp_analytics.backend.models import MCPAnalyticsSubmission, MCPIntentClusterSnapshot, MCPSession
from products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin
@@ -265,3 +266,56 @@ class TestMCPAnalyticsPresentation(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest
assert data["count"] == 101
assert len(data["results"]) == 100
assert data["next"] is not None
+
+
+class TestMCPSessionIntentEndpoint(_MCPAnalyticsTeamScopedTestMixin, APIBaseTest):
+ def _url(self, session_id: str) -> str:
+ return f"/api/environments/{self.team.id}/mcp_analytics/sessions/{session_id}/generate_intent/"
+
+ def test_requires_authentication(self) -> None:
+ self.client.logout()
+ response = self.client.post(self._url("abc"))
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_staff_only_in_cloud(self) -> None:
+ with self.is_cloud(True):
+ response = self.client.post(self._url("abc"))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_returns_cached_intent_in_response_shape(self) -> None:
+ session_id = "session-123"
+ MCPSession.objects.create(team=self.team, session_id=session_id, intent="A persisted summary.")
+
+ response = self.client.post(self._url(session_id))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"session_id": session_id, "intent": "A persisted summary."}
+
+ def test_generates_and_persists_when_empty(self) -> None:
+ session_id = "session-fresh"
+ # Mock the two primitives so the endpoint path runs without ClickHouse or a real LLM call.
+ with (
+ patch.object(intent_generation, "fetch_session_intents", return_value=["check the funnel"]),
+ patch.object(intent_generation, "summarize_intents", return_value="Generated summary."),
+ ):
+ response = self.client.post(self._url(session_id))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"session_id": session_id, "intent": "Generated summary."}
+ assert MCPSession.objects.get(team=self.team, session_id=session_id).intent == "Generated summary."
+
+ def test_returns_503_when_generation_unavailable(self) -> None:
+ session_id = "session-unavailable"
+ with (
+ patch.object(intent_generation, "fetch_session_intents", return_value=["check the funnel"]),
+ patch.object(
+ intent_generation,
+ "summarize_intents",
+ side_effect=intent_generation.IntentGenerationUnavailable("LLM down"),
+ ),
+ ):
+ response = self.client.post(self._url(session_id))
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ # Nothing persisted when generation fails.
+ assert not MCPSession.objects.filter(team=self.team, session_id=session_id).exists()
diff --git a/products/mcp_analytics/frontend/generated/api.schemas.ts b/products/mcp_analytics/frontend/generated/api.schemas.ts
index 9ed09b735f21..b2e35dcc2c74 100644
--- a/products/mcp_analytics/frontend/generated/api.schemas.ts
+++ b/products/mcp_analytics/frontend/generated/api.schemas.ts
@@ -329,7 +329,7 @@ export interface MCPSessionApi {
readonly person_email: string
/** name property of the Person resolved from distinct_id; empty when no Person is mapped. */
readonly person_name: string
- /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs. */
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until generated on demand via the generate_intent endpoint. */
readonly intent: string
}
@@ -339,6 +339,13 @@ export interface PaginatedMCPSessionListApi {
has_next: boolean
}
+export interface MCPSessionIntentApi {
+ /** $mcp_session_id the intent summary was generated for. */
+ readonly session_id: string
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. */
+ readonly intent: string
+}
+
export interface MCPToolCallApi {
/** ClickHouse uuid of the mcp_tool_call event. */
readonly event_id: string
diff --git a/products/mcp_analytics/frontend/generated/api.ts b/products/mcp_analytics/frontend/generated/api.ts
index d169fdc63e92..9ebae0fddc53 100644
--- a/products/mcp_analytics/frontend/generated/api.ts
+++ b/products/mcp_analytics/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
MCPFeedbackCreateApi,
MCPIntentClusterSnapshotApi,
MCPMissingCapabilityCreateApi,
+ MCPSessionIntentApi,
McpAnalyticsFeedbackListParams,
McpAnalyticsMissingCapabilitiesListParams,
McpAnalyticsSessionsListParams,
@@ -192,6 +193,24 @@ export const mcpAnalyticsSessionsList = async (
})
}
+export const getMcpAnalyticsSessionsGenerateIntentUrl = (projectId: string, id: string) => {
+ return `/api/environments/${projectId}/mcp_analytics/sessions/${id}/generate_intent/`
+}
+
+/**
+ * Generate (or return the cached) LLM summary of the agent's goal for a session, derived from its recorded $mcp_intents. The first call summarises and persists the result; subsequent calls return the stored summary.
+ */
+export const mcpAnalyticsSessionsGenerateIntent = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MCPSessionIntentApi> => {
+ return apiMutator<MCPSessionIntentApi>(getMcpAnalyticsSessionsGenerateIntentUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getMcpAnalyticsSessionsToolCallsUrl = (
projectId: string,
id: string,
diff --git a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
index 84d7bd500ebc..66cdccbc9b56 100644
--- a/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
+++ b/products/mcp_analytics/frontend/sessions/MCPSessionDetail.tsx
@@ -1,7 +1,7 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { IconBolt, IconClock, IconSparkles, IconUser, IconWarning } from '@posthog/icons'
-import { LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
@@ -19,7 +19,9 @@ function MetaBadge({ icon, label }: { icon: React.ReactNode; label: React.ReactN
}
export function MCPSessionDetail(): JSX.Element {
- const { selectedSession, toolCalls, toolCallsLoading } = useValues(mcpSessionsLogic)
+ const { selectedSession, toolCalls, toolCallsLoading, selectedSessionIntent, isSelectedSessionGenerating } =
+ useValues(mcpSessionsLogic)
+ const { generateIntent } = useActions(mcpSessionsLogic)
if (!selectedSession) {
return (
@@ -161,21 +163,29 @@ export function MCPSessionDetail(): JSX.Element {
<hr className="shrink-0 border-t border-primary my-0" />
<footer className="shrink-0 bg-gradient-to-br from-accent/15 via-accent/5 to-surface-primary px-3 py-3">
- <div className="flex items-center gap-2 mb-1.5">
- <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-accent/20 text-accent">
- <IconSparkles className="text-xs" />
- </div>
- <span className="text-[10px] uppercase tracking-wider font-semibold text-accent">
- Session intent
- </span>
- </div>
- <p className="text-xs leading-relaxed text-default">
- {selectedSession.intent || (
- <span className="text-secondary italic">
- Summary will appear once the intent workflow runs.
- </span>
- )}
- </p>
+ {selectedSessionIntent ? (
+ <>
+ <div className="flex items-center gap-2 mb-1.5">
+ <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-accent/20 text-accent">
+ <IconSparkles className="text-xs" />
+ </div>
+ <span className="text-[10px] uppercase tracking-wider font-semibold text-accent">
+ Session intent
+ </span>
+ </div>
+ <p className="text-xs leading-relaxed text-default">{selectedSessionIntent}</p>
+ </>
+ ) : (
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ icon={<IconSparkles />}
+ loading={isSelectedSessionGenerating}
+ onClick={() => generateIntent(selectedSession.session_id)}
+ >
+ {isSelectedSessionGenerating ? 'Thinking…' : "What's the session intent?"}
+ </LemonButton>
+ )}
</footer>
</div>
)
diff --git a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
index f7d80307d9dd..db8e0e3a1a98 100644
--- a/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
+++ b/products/mcp_analytics/frontend/sessions/mcpSessionsLogic.ts
@@ -1,10 +1,15 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { mcpAnalyticsSessionsList, mcpAnalyticsSessionsToolCalls } from '../generated/api'
-import type { MCPSessionApi, MCPToolCallApi } from '../generated/api.schemas'
+import {
+ mcpAnalyticsSessionsGenerateIntent,
+ mcpAnalyticsSessionsList,
+ mcpAnalyticsSessionsToolCalls,
+} from '../generated/api'
+import type { MCPSessionApi, MCPSessionIntentApi, MCPToolCallApi } from '../generated/api.schemas'
import type { mcpSessionsLogicType } from './mcpSessionsLogicType'
export interface MCPSessionsFilters {
@@ -112,12 +117,33 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
if (!values.currentProjectId || !sessionId) {
return []
}
- const response = await mcpAnalyticsSessionsToolCalls(String(values.currentProjectId), sessionId)
+ // session_id comes from untrusted event properties — encode it so path/query
+ // delimiters can't redirect this request to another same-origin endpoint.
+ const response = await mcpAnalyticsSessionsToolCalls(
+ String(values.currentProjectId),
+ encodeURIComponent(sessionId)
+ )
breakpoint()
return [...(response.results ?? [])]
},
},
],
+ generatedIntent: [
+ null as MCPSessionIntentApi | null,
+ {
+ generateIntent: async (sessionId: string) => {
+ if (!values.currentProjectId || !sessionId) {
+ return null
+ }
+ // session_id comes from untrusted event properties — encode it so path/query
+ // delimiters can't redirect this POST to another same-origin endpoint.
+ return await mcpAnalyticsSessionsGenerateIntent(
+ String(values.currentProjectId),
+ encodeURIComponent(sessionId)
+ )
+ },
+ },
+ ],
})),
reducers({
filters: [
@@ -147,6 +173,23 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
loadSessions: () => false,
},
],
+ intentOverrides: [
+ {} as Record<string, string>,
+ {
+ generateIntentSuccess: (state, { generatedIntent }) =>
+ generatedIntent?.intent
+ ? { ...state, [generatedIntent.session_id]: generatedIntent.intent }
+ : state,
+ },
+ ],
+ generatingSessionId: [
+ null as string | null,
+ {
+ generateIntent: (_, sessionId) => sessionId,
+ generateIntentSuccess: () => null,
+ generateIntentFailure: () => null,
+ },
+ ],
}),
selectors({
selectedSession: [
@@ -158,6 +201,22 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
return sessions.find((session) => session.session_id === selectedSessionId) ?? null
},
],
+ selectedSessionIntent: [
+ (s) => [s.selectedSession, s.intentOverrides, s.selectedSessionId],
+ (selectedSession, intentOverrides, selectedSessionId): string => {
+ if (selectedSessionId && intentOverrides[selectedSessionId]) {
+ return intentOverrides[selectedSessionId]
+ }
+ return selectedSession?.intent ?? ''
+ },
+ ],
+ // True only while a generation for the *currently selected* session is running, so a
+ // generation kicked off for another session never shows a spinner on this one.
+ isSelectedSessionGenerating: [
+ (s) => [s.generatedIntentLoading, s.generatingSessionId, s.selectedSessionId],
+ (generatedIntentLoading, generatingSessionId, selectedSessionId): boolean =>
+ generatedIntentLoading && generatingSessionId === selectedSessionId,
+ ],
}),
listeners(({ actions, values }) => ({
// A new filter or sort changes the result set — reload from the first page.
@@ -172,6 +231,11 @@ export const mcpSessionsLogic = kea<mcpSessionsLogicType>([
actions.loadToolCalls(sessionId)
}
},
+ // The button just resets to its idle state on failure; surface a toast so the user
+ // knows the request failed (e.g. a 503 when intent generation is unavailable).
+ generateIntentFailure: () => {
+ lemonToast.error('Could not generate the session intent. Please try again.')
+ },
// Only fires on a reset load (not on loadMore), so appending more pages doesn't
// steal the user's selection. Auto-selects the first row when the set changes.
loadSessionsSuccess: ({ sessions }) => {
diff --git a/products/mcp_analytics/mcp/tools.yaml b/products/mcp_analytics/mcp/tools.yaml
index 18765bebc3ba..45ccbd0fbea2 100644
--- a/products/mcp_analytics/mcp/tools.yaml
+++ b/products/mcp_analytics/mcp/tools.yaml
@@ -15,6 +15,9 @@ tools:
mcp-analytics-intent-clusters-retrieve:
operation: mcp_analytics_intent_clusters_retrieve
enabled: false
+ mcp-analytics-sessions-generate-intent:
+ operation: mcp_analytics_sessions_generate_intent
+ enabled: false
mcp-analytics-sessions-list:
operation: mcp_analytics_sessions_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index be213b30ac84..e729396e862f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21225,7 +21225,14 @@ export namespace Schemas {
readonly person_email: string;
/** name property of the Person resolved from distinct_id; empty when no Person is mapped. */
readonly person_name: string;
- /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until the summary workflow runs. */
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. Empty until generated on demand via the generate_intent endpoint. */
+ readonly intent: string;
+ }
+
+ export interface MCPSessionIntent {
+ /** $mcp_session_id the intent summary was generated for. */
+ readonly session_id: string;
+ /** LLM-generated summary (at most two sentences) of the agent's overall goal for the session. */
readonly intent: string;
}