: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
fix(mcp): let read-data-schema verify the sessions table (#97249)
posthog[bot]e4aa96a7ea46
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.pyindex b23e7adef099..b7772611dac2 100644--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py@@ -187,12 +187,62 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):self.assertIn("$virt_initial_channel_type", result)self.assertIn("$virt_revenue", result)+ @parameterized.expand(+ [+ ["plural table name", "sessions", "$session_duration"],+ ["mixed case", "Session", "$session_duration"],+ ["plural person", "persons", "$virt_initial_channel_type"],+ ]+ )+ def test_retrieve_entity_properties_accepts_the_name_a_query_uses(+ self, _name: str, entity: str, expected_property: str+ ):+ result = DummyToolkit(self.team, self.user).retrieve_entity_properties(entity)++ self.assertIn(f"- {expected_property}", result)++ def test_retrieve_entity_properties_names_the_entities_it_has(self):+ result = DummyToolkit(self.team, self.user).retrieve_entity_properties("sesion")++ self.assertEqual(+ result,+ "The entity sesion does not exist in the taxonomy. You must use one of the following: person, session.",+ )++ def test_retrieve_entity_properties_lists_the_session_fields_web_analytics_breaks_down_by(self):+ breakdown_fields = (+ "$entry_pathname",+ "$entry_hostname",+ "$end_pathname",+ "$end_hostname",+ "$entry_referring_domain",+ "$entry_utm_source",+ "$entry_utm_medium",+ "$entry_utm_campaign",+ "$entry_utm_term",+ "$entry_utm_content",+ "$channel_type",+ "$last_external_click_url",+ )++ result = DummyToolkit(self.team, self.user).retrieve_entity_properties("session")++ self.assertEqual([name for name in breakdown_fields if f"- {name} " not in result], [])+def test_retrieve_entity_property_values(self):toolkit = DummyToolkit(self.team, self.user)self.assertEqual(toolkit.retrieve_entity_property_values("session", "$session_duration"),"30, 146, 2 and many more distinct values.",)+ self.assertEqual(+ toolkit.retrieve_entity_property_values("sessions", "$session_duration"),+ "30, 146, 2 and many more distinct values.",+ )+ self.assertEqual(+ toolkit.retrieve_entity_property_values("session", "$entry_utm_source"),+ '"Google", "Bing", "Twitter", "Facebook" and many more distinct values.',+ )self.assertEqual(toolkit.retrieve_entity_property_values("session", "nonsense"),"The property nonsense does not exist in the taxonomy.",diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.pyindex 06d91c69b969..70f9e058d0e0 100644--- a/ee/hogai/chat_agent/query_planner/toolkit.py+++ b/ee/hogai/chat_agent/query_planner/toolkit.py@@ -31,7 +31,9 @@ from products.event_definitions.backend.models.property_definition import (effective_project_id_expr,)+from ee.hogai.chat_agent.taxonomy.entities import resolve_entity_namefrom ee.hogai.chat_agent.taxonomy.format import enrich_props_with_descriptions+from ee.hogai.chat_agent.taxonomy.session_properties import session_property_typesfrom ee.hogai.chat_agent.taxonomy.tools import (ask_user_for_help,retrieve_action_properties,@@ -140,6 +142,9 @@ class TaxonomyAgentToolkit:]return entities+ def _entity_not_found_message(self, entity: str) -> str:+ return f"The entity {entity} does not exist in the taxonomy. You must use one of the following: {', '.join(self._entity_names)}."+def _generate_properties_output(self, props: list[tuple[str, str | None, str | None]]) -> str:"""Generate the output format for properties. Can be overridden by subclasses.@@ -214,8 +219,10 @@ class TaxonomyAgentToolkit:Retrieve properties for an entitiy like person, session, or one of the groups."""- if entity not in ("person", "session", *[g["group_type"] for g in self._groups]):- return f"Entity {entity} does not exist in the taxonomy."+ resolved = resolve_entity_name(entity, self._entity_names)+ if resolved is None:+ return self._entity_not_found_message(entity)+ entity = resolvedtruncated = Falseif entity == "person":@@ -232,14 +239,7 @@ class TaxonomyAgentToolkit:props = self._enrich_props_with_descriptions("person", stored_props, stored_descriptions)elif entity == "session":# Session properties are not in the DB.- props = self._enrich_props_with_descriptions(- "session",- [- (prop_name, prop["type"])- for prop_name, prop in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"].items()- if prop.get("type") is not None- ],- )+ props = self._enrich_props_with_descriptions("session", list(session_property_types().items()))else:group_type_index = next((g["group_type_index"] for g in self._groups if g["group_type"] == entity), None)@@ -466,23 +466,20 @@ class TaxonomyAgentToolkit:sample_values = cast(list[str | int | float], DEFAULT_CHANNEL_TYPES.copy())sample_count = len(sample_values)is_str = True- elif (- property_name in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"]- and "examples" in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]- ):+ elif "examples" in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]:sample_values = CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]["examples"]sample_count = None- is_str = (- CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]["type"] == PropertyType.String- )+ is_str = session_property_types().get(property_name) == PropertyType.Stringelse:return f"Property values for {property_name} do not exist in the taxonomy for the session entity."return self._format_property_values(sample_values, sample_count, format_as_string=is_str)def retrieve_entity_property_values(self, entity: str, property_name: str) -> str:- if entity not in self._entity_names:- return f"The entity {entity} does not exist in the taxonomy. You must use one of the following: {', '.join(self._entity_names)}."+ resolved = resolve_entity_name(entity, self._entity_names)+ if resolved is None:+ return self._entity_not_found_message(entity)+ entity = resolvedif entity == "session":return self._retrieve_session_properties(property_name)diff --git a/ee/hogai/chat_agent/taxonomy/entities.py b/ee/hogai/chat_agent/taxonomy/entities.pynew file mode 100644index 000000000000..039ee457ab7b--- /dev/null+++ b/ee/hogai/chat_agent/taxonomy/entities.py@@ -0,0 +1,15 @@+from collections.abc import Iterable+++def resolve_entity_name(entity: str, entity_names: Iterable[str]) -> str | None:+ """+ Match a caller's entity name to one of the taxonomy's own names, or return None.++ The taxonomy names an entity in the singular, but a query reads the plural table it lives in,+ so a caller that starts from the query asks about `sessions`.+ """+ candidate = entity.strip().lower()+ by_name = {name.lower(): name for name in entity_names}+ if candidate in by_name:+ return by_name[candidate]+ return by_name.get(candidate.removesuffix("s"))diff --git a/ee/hogai/chat_agent/taxonomy/session_properties.py b/ee/hogai/chat_agent/taxonomy/session_properties.pynew file mode 100644index 000000000000..4ceb5fd5695e--- /dev/null+++ b/ee/hogai/chat_agent/taxonomy/session_properties.py@@ -0,0 +1,23 @@+from posthog.hogql.database.schema.sessions_v2 import get_lazy_session_table_properties_v2++from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP+++def session_property_types() -> dict[str, str]:+ """+ Map each session property to the type to report for it, in the taxonomy's own order.++ A session entry property is copied from an event property that carries no type, so the copy+ has none either, and an untyped property is dropped from the taxonomy read. The `sessions`+ table declares a column for each one, so its type answers for the copy.+ """+ column_types = {+ str(prop["name"]): str(prop["property_type"]) for prop in get_lazy_session_table_properties_v2(None)+ }+ types: dict[str, str] = {}+ for name, definition in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"].items():+ declared = definition.get("type")+ resolved = str(declared) if declared is not None else column_types.get(name)+ if resolved is not None:+ types[name] = resolved+ return typesdiff --git a/ee/hogai/chat_agent/taxonomy/test/test_entities.py b/ee/hogai/chat_agent/taxonomy/test/test_entities.pyindex e4ab1e7e5791..693a4c3f5926 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_entities.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_entities.py@@ -139,7 +139,7 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):property_vals = await self.toolkit.retrieve_entity_property_values({"person": ["property_no_values"],- "session": ["$session_duration", "$channel_type", "nonexistent_property"],+ "session": ["$session_duration", "$channel_type", "$entry_utm_source", "nonexistent_property"],})@@ -154,6 +154,8 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):self.assertIn("session", property_vals)self.assertIn("$session_duration", "\n".join(property_vals.get("session", [])))self.assertIn("$channel_type", "\n".join(property_vals.get("session", [])))+ self.assertIn("$entry_utm_source", "\n".join(property_vals.get("session", [])))+ self.assertTrue(any("Google" in str(val) for val in property_vals.get("session", [])))self.assertIn("nonexistent_property", "\n".join(property_vals.get("session", [])))self.assertTrue(any(diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.pyindex bb8c1478796c..75dadea09c9c 100644--- a/ee/hogai/chat_agent/taxonomy/toolkit.py+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py@@ -43,6 +43,7 @@ from ee.hogai.chat_agent.taxonomy.format import (format_properties_yaml,format_property_values,)+from ee.hogai.chat_agent.taxonomy.session_properties import session_property_typesfrom ee.hogai.chat_agent.taxonomy.virtual_properties import (PropertyDefinitionOrVirtual,VirtualPropertyGroup,@@ -272,15 +273,10 @@ class TaxonomyAgentToolkit:sample_values = cast(list[str | int | float], DEFAULT_CHANNEL_TYPES.copy())sample_count = len(sample_values)is_str = True- elif (- property_name in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"]- and "examples" in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]- ):+ elif "examples" in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]:sample_values = CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]["examples"]sample_count = None- is_str = (- CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"][property_name]["type"] == PropertyType.String- )+ is_str = session_property_types().get(property_name) == PropertyType.Stringelse:return TaxonomyErrorMessages.property_values_not_found(property_name, "session")@@ -683,11 +679,7 @@ class TaxonomyAgentToolkit:status=status,)elif entity == "session":- props = [- (prop_name, prop["type"])- for prop_name, prop in CORE_FILTER_DEFINITIONS_BY_GROUP["session_properties"].items()- if prop.get("type") is not None- ]+ props = list(session_property_types().items())if props:result = self._format_properties(self._enrich_props_with_descriptions("session", props))diff --git a/ee/hogai/tools/read_taxonomy/core.py b/ee/hogai/tools/read_taxonomy/core.pyindex 3005e9921640..f9defab0b5a0 100644--- a/ee/hogai/tools/read_taxonomy/core.py+++ b/ee/hogai/tools/read_taxonomy/core.py@@ -6,8 +6,14 @@ from posthog.event_usage import EventSourcefrom posthog.models import Team, Userfrom ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit+from ee.hogai.chat_agent.taxonomy.entities import resolve_entity_namefrom ee.hogai.utils.helpers import format_events_yaml, get_event_description+ENTITY_FIELD_DESCRIPTION = (+ "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. "+ "The plural form of any of these is accepted too."+)+class ReadEvents(BaseModel):"""Returns the list of available events. Events are sorted by their popularity where the most popular events are at the top."""@@ -28,7 +34,7 @@ class ReadEntityProperties(BaseModel):"""Returns the properties list for a provided entity."""kind: Literal["entity_properties"] = "entity_properties"- entity: str = Field(description="The type of the entity that you want to retrieve properties for.")+ entity: str = Field(description=ENTITY_FIELD_DESCRIPTION)# Keep entity as string to allow for dynamic entity types.@@ -43,7 +49,7 @@ class ReadEntitySamplePropertyValues(BaseModel):"""For a provided entity and a property, returns a list of maximum 25 sample values that the combination has."""kind: Literal["entity_property_values"] = "entity_property_values"- entity: str = Field(description="The type of the entity that you want to retrieve properties for.")+ entity: str = Field(description=ENTITY_FIELD_DESCRIPTION)# Keep entity as string to allow for dynamic entity types.property_name: str = Field(description="Verified property name of an entity.")@@ -124,7 +130,7 @@ def execute_taxonomy_query(return toolkit.retrieve_event_or_action_property_values(query.action_id, query.property_name)case ReadEntityProperties():result = toolkit.retrieve_entity_properties(query.entity)- if query.entity == "person":+ if resolve_entity_name(query.entity, ["person"]) == "person":return f"{result}\n\n{DYNAMIC_PERSON_PROPERTIES_HINT}"return resultcase ReadEntitySamplePropertyValues():diff --git a/ee/hogai/tools/read_taxonomy/test/test_tool.py b/ee/hogai/tools/read_taxonomy/test/test_tool.pyindex fe88630043e1..8661d32fdc5a 100644--- a/ee/hogai/tools/read_taxonomy/test/test_tool.py+++ b/ee/hogai/tools/read_taxonomy/test/test_tool.py@@ -116,12 +116,13 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):[], self.team, self.user, limit=500, offset=0, event_source=EventSource.POSTHOG_AI)+ @parameterized.expand([("singular", "person"), ("plural", "persons")])@patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")- def test_person_entity_properties_include_dynamic_hint(self, mock_toolkit_class):+ def test_person_entity_properties_include_dynamic_hint(self, _name, entity, mock_toolkit_class):mock_toolkit = mock_toolkit_class.return_valuemock_toolkit.retrieve_entity_properties.return_value = "- email\n- name"- result = execute_taxonomy_query(ReadEntityProperties(entity="person"), mock_toolkit, self.team, self.user)+ result = execute_taxonomy_query(ReadEntityProperties(entity=entity), mock_toolkit, self.team, self.user)self.assertIn(DYNAMIC_PERSON_PROPERTIES_HINT, result)self.assertIn("$survey_dismissed", result)diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 9dc98f1d30c7..88c3eb34ea21 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -1091,7 +1091,7 @@},"entity": {"type": "string",- "description": "The type of the entity that you want to retrieve properties for."+ "description": "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. The plural form of any of these is accepted too."}},"required": ["kind", "entity"],@@ -1123,7 +1123,7 @@},"entity": {"type": "string",- "description": "The type of the entity that you want to retrieve properties for."+ "description": "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. The plural form of any of these is accepted too."},"property_name": {"type": "string",diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 15714b92e8b9..17e6474db8fa 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -677,6 +677,9 @@ export const ExecuteSQLSchema = z.object({const MAX_EVENTS_PAGE_SIZE = 500+const ENTITY_FIELD_DESCRIPTION =+ 'The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. The plural form of any of these is accepted too.'+// Every read below is strict so a field it does not have is named back to the caller. Left// open, an ignored `search` or `property_name` returns a confident answer to a different// question than the one asked.@@ -705,7 +708,7 @@ const ReadEventPropertiesQuerySchema = zconst ReadEntityPropertiesQuerySchema = z.object({kind: z.literal('entity_properties'),- entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),+ entity: z.string().describe(ENTITY_FIELD_DESCRIPTION),}).strict()@@ -719,7 +722,7 @@ const ReadActionPropertiesQuerySchema = zconst ReadEntitySamplePropertyValuesQuerySchema = z.object({kind: z.literal('entity_property_values'),- entity: z.string().describe('The type of the entity that you want to retrieve properties for.'),+ entity: z.string().describe(ENTITY_FIELD_DESCRIPTION),property_name: z.string().describe('Verified property name of an entity.'),}).strict()diff --git a/services/mcp/src/templates/sections/cli-data-discovery.md b/services/mcp/src/templates/sections/cli-data-discovery.mdindex 8c0b053fa0d4..056f5c0eb75d 100644--- a/services/mcp/src/templates/sections/cli-data-discovery.md+++ b/services/mcp/src/templates/sections/cli-data-discovery.md@@ -7,5 +7,5 @@ Always run `info read-data-schema` first — the recipes below are common cases,- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed). Actions come from `actions-get-all` instead.- Event properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`-- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session`, or a group type name)+- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session` for the columns of the `sessions` table, or a group type name)- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txtindex 379ef8394c9f..ca4494cbd3a3 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt@@ -61,7 +61,7 @@ Always run `info read-data-schema` first — the recipes below are common cases,- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed). Actions come from `actions-get-all` instead.- Event properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`-- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session`, or a group type name)+- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session` for the columns of the `sessions` table, or a group type name)- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`**CORRECT usage pattern:**diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txtindex 5afb2c83237a..292d6937dbd7 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt@@ -48,7 +48,7 @@ Always run `info read-data-schema` first — the recipes below are common cases,- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed). Actions come from `actions-get-all` instead.- Event properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`-- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session`, or a group type name)+- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session` for the columns of the `sessions` table, or a group type name)- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`**CORRECT usage pattern:**diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txtindex d764762fb62b..0c6154000bbe 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt@@ -48,7 +48,7 @@ Always run `info read-data-schema` first — the recipes below are common cases,- Events: `call read-data-schema {"query": {"kind": "events"}}` (paginate with `limit`/`offset` if needed). Actions come from `actions-get-all` instead.- Event properties: `call read-data-schema {"query": {"kind": "event_properties", "event_name": "<event>"}}`-- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session`, or a group type name)+- Person, session, and group properties: `call read-data-schema {"query": {"kind": "entity_properties", "entity": "<entity>"}}` (`entity` is `person`, `session` for the columns of the `sessions` table, or a group type name)- Values: `call read-data-schema {"query": {"kind": "event_property_values", "event_name": "<event>", "property_name": "<prop>"}}`**CORRECT usage pattern:**diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.jsonindex aef27843b268..ebf42284ddd8 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-schema.json@@ -48,7 +48,7 @@"additionalProperties": false,"properties": {"entity": {- "description": "The type of the entity that you want to retrieve properties for.",+ "description": "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. The plural form of any of these is accepted too.","type": "string"},"kind": {@@ -80,7 +80,7 @@"additionalProperties": false,"properties": {"entity": {- "description": "The type of the entity that you want to retrieve properties for.",+ "description": "The entity to read: `person`, `session` for the columns of the `sessions` table, or a group type name. The plural form of any of these is accepted too.","type": "string"},"kind": {