: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): respect explicit date_to timestamps in query tools (#69697)
posthog[bot]31bec79063ff
diff --git a/posthog/api/query.py b/posthog/api/query.pyindex be78825261e8..ec2a1c67f8f7 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -100,6 +100,31 @@ def _extract_validation_code(error: ValidationError) -> str:return "unknown"+# Matches an absolute ISO date that carries an explicit time-of-day (e.g. `2026-07-09T00:00:00Z`,+# `2026-07-09 05:00:00`), but not a bare calendar day (`2026-07-09`) or a relative token (`-7d`, `mStart`).+_ISO_TIMESTAMP_WITH_TIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}")+++def _date_bound_has_explicit_time(value: object) -> bool:+ return isinstance(value, str) and _ISO_TIMESTAMP_WITH_TIME_RE.match(value) is not None+++def _mark_explicit_date_boundaries(query: BaseModel) -> None:+ """MCP query tools accept ISO timestamps in `dateRange.date_to`. When a caller passes a full+ timestamp with a time-of-day (e.g. `2026-07-09T00:00:00Z`) rather than a bare calendar day, they+ mean an exact boundary, so mark the range explicit instead of snapping `date_to` to end of day.++ Scoped to the MCP entrypoint on purpose: the web UI serialises fixed calendar ranges as naive+ `YYYY-MM-DDTHH:mm:ss` strings and relies on the default end-of-day rounding, so this must not+ change that path.+ """+ date_range = getattr(query, "dateRange", None)+ if date_range is None or not hasattr(date_range, "explicitDate") or date_range.explicitDate:+ return+ if _date_bound_has_explicit_time(getattr(date_range, "date_to", None)):+ date_range.explicitDate = True++def _process_query_request(request_data: QueryRequest, team, client_query_id: str | None = None, user=None) -> tuple[BaseModel, str, ExecutionMode]:@@ -208,6 +233,10 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMidata, self.team, data.client_query_id, request.user)+ is_mcp_client = request.headers.get("x-posthog-client") == "mcp"+ if is_mcp_client:+ _mark_explicit_date_boundaries(query)+self._tag_client_query_id(client_query_id)analytics_props = get_request_analytics_properties(request)query_dict = query.model_dump()@@ -278,7 +307,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMielse status.HTTP_200_OK)- if request.headers.get("x-posthog-client") == "mcp":+ if is_mcp_client:with tracer.start_as_current_span("posthog.query.format_for_llm") as llm_span:formatted = self._try_format_for_llm(query, result)llm_span.set_attribute("query.formatted", formatted is not None)diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex 3d99e466457e..16929b5f4f02 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -13,6 +13,7 @@ from posthog.test.base import (from unittest import mockfrom unittest.mock import patch+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.schema import (@@ -1429,6 +1430,62 @@ class TestQueryLLMFormatting(ClickhouseTestMixin, APIBaseTest):self.assertIn("results", data)self.assertNotIn("formatted_results", data)+ @parameterized.expand(+ [+ # An explicit ISO timestamp (including midnight Z) is an exact boundary, not a calendar day.+ ("explicit_midnight", "2026-07-09T00:00:00Z", "to 2026-07-09 00:00:00"),+ ("explicit_time_of_day", "2026-07-09T14:30:00Z", "to 2026-07-09 14:30:00"),+ # A bare calendar day keeps the default end-of-day rounding so the last day stays included.+ ("bare_date", "2026-07-09", "to 2026-07-09 23:59:59"),+ ]+ )+ @patch("posthog.api.query.process_query_model")+ def test_mcp_funnel_respects_explicit_timestamp_date_to(+ self, _name, date_to, expected_range_suffix, mock_process_query_model+ ):+ mock_process_query_model.return_value = {+ "results": [+ {"name": "$pageview", "count": 10, "average_conversion_time": None, "median_conversion_time": None}+ ],+ "is_cached": False,+ }++ response = self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {+ "query": {+ "kind": "FunnelsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "dateRange": {"date_from": "2026-07-02T00:00:00Z", "date_to": date_to},+ }+ },+ HTTP_X_POSTHOG_CLIENT="mcp",+ )++ self.assertEqual(response.status_code, 200)+ formatted = response.json()["formatted_results"]+ self.assertIn(expected_range_suffix, formatted)++ @patch("posthog.api.query.process_query_model")+ def test_non_mcp_request_does_not_mark_explicit_date(self, mock_process_query_model):+ # The web UI serialises fixed calendar ranges as naive timestamps and relies on end-of-day+ # rounding, so a non-MCP request must never have its date boundary marked explicit.+ mock_process_query_model.return_value = {"results": [], "is_cached": False}++ self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {+ "query": {+ "kind": "FunnelsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ "dateRange": {"date_from": "2026-07-02T00:00:00Z", "date_to": "2026-07-09T00:00:00Z"},+ }+ },+ )++ executed_query = mock_process_query_model.call_args.args[1]+ self.assertFalse(executed_query.dateRange.explicitDate)+class TestMcpProductTaggingEndToEnd(ClickhouseTestMixin, APIBaseTest):"""End-to-end tests that an MCP request to the /query endpoint ends up tagged as