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(endpoints): add execution logs viewer, MCP tool, and skill (#62218)

Jovan Sakovicc8afa430b6e4
diff --git a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
index f3f0de1af915..0b2e274a7667 100644
--- a/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
+++ b/frontend/src/scenes/hog-functions/logs/LogsViewer.tsx
@@ -191,7 +191,7 @@ export function LogsViewer({
<div className="flex items-center gap-2 flex-1 min-w-100">
<LemonInput
type="search"
- placeholder="Search messages or invocation ID…"
+ placeholder={`Search messages or ${instanceLabel ? instanceLabel : 'invocation'} ID…`}
fullWidth
onChange={(value) => setFilters({ search: value })}
value={filters.search}
diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
index 76af6235bb94..6cc903011430 100644
--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
@@ -33,7 +33,7 @@ export const LOG_GROUP_TOTAL_LOGS_LIMIT = 5000
export type LogsViewerLogicProps = {
logicKey?: string
- sourceType: 'hog_function' | 'hog_flow' | 'batch_exports' | 'external_data_jobs' | 'data_modeling_run'
+ sourceType: 'hog_function' | 'hog_flow' | 'batch_exports' | 'external_data_jobs' | 'data_modeling_run' | 'endpoints'
sourceId: string
groupByInstanceId?: boolean
searchGroups?: string[]
@@ -66,7 +66,7 @@ export type GroupedLogEntry = {
}
export type LogEntryParams = {
- sourceType: 'hog_function' | 'hog_flow' | 'data_modeling_run'
+ sourceType: LogsViewerLogicProps['sourceType']
sourceId: string
levels: LogEntryLevel[]
searchGroups: string[]
diff --git a/playwright/e2e/batch-exports/batch-export-logs.spec.ts b/playwright/e2e/batch-exports/batch-export-logs.spec.ts
index 110fcef3a55d..51c3833f429b 100644
--- a/playwright/e2e/batch-exports/batch-export-logs.spec.ts
+++ b/playwright/e2e/batch-exports/batch-export-logs.spec.ts
@@ -57,7 +57,8 @@ test.describe('Batch export logs', () => {
await page.goto(`/pipeline/batch-exports/${MOCK_EXPORT_ID}?tab=logs`)
- // The logs tab should render the LogsViewer with its search input
- await expect(page.getByPlaceholder('Search messages or invocation ID')).toBeVisible()
+ // The logs tab should render the LogsViewer with its search input.
+ // Batch exports label instances as "run", so the placeholder reads "run ID".
+ await expect(page.getByPlaceholder('Search messages or run ID')).toBeVisible()
})
})
diff --git a/posthog/api/log_entries.py b/posthog/api/log_entries.py
index 24309f17c6d4..85bb5c976f89 100644
--- a/posthog/api/log_entries.py
+++ b/posthog/api/log_entries.py
@@ -19,6 +19,7 @@ LOG_SOURCE_TO_PRODUCT_KEY: dict[str, ProductKey] = {
"hog_function": ProductKey.PIPELINE_DESTINATIONS,
"hog_flow": ProductKey.WORKFLOWS,
"batch_exports": ProductKey.PIPELINE_BATCH_EXPORTS,
+ "endpoints": ProductKey.ENDPOINTS,
}
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index ea8fb9f426b4..244960bf6ea0 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -5,7 +5,7 @@ import builtins
import dataclasses
from collections.abc import Iterator
from datetime import timedelta
-from typing import Optional, Union, cast
+from typing import Any, Optional, Union, cast
from django.shortcuts import get_object_or_404
from django.utils import timezone
@@ -17,7 +17,10 @@ from dateutil.parser import isoparse
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import OpenApiParameter, extend_schema_view
from loginas.utils import is_impersonated_session
-from pydantic import BaseModel
+from pydantic import (
+ BaseModel,
+ ValidationError as PydanticValidationError,
+)
from rest_framework import serializers, status, viewsets
from rest_framework.exceptions import PermissionDenied, Throttled, ValidationError
from rest_framework.permissions import IsAuthenticated
@@ -50,6 +53,7 @@ from posthog.hogql.printer.utils import print_prepared_ast
from posthog.hogql.visitor import CloningVisitor
from posthog.api.documentation import extend_schema
+from posthog.api.log_entries import LogEntryMixin
from posthog.api.mixins import PydanticModelMixin, ValidatedRequest, validated_request
from posthog.api.query import _process_query_request
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -87,6 +91,7 @@ from products.endpoints.backend.insight_transformers import (
MaterializedSeriesMismatchError,
transform_materialized_insight_response,
)
+from products.endpoints.backend.logs import ENDPOINTS_LOG_SOURCE, build_execution_message, log_endpoint_execution
from products.endpoints.backend.materialization import (
ENDPOINT_BREAKDOWN_LIMIT,
SUPPORTED_BUCKET_FUNCTIONS,
@@ -383,6 +388,18 @@ class MaterializationPreviewRequestSerializer(serializers.Serializer):
)
+class _RunRejected(Exception):
+ """Internal control-flow signal: a run request was rejected during validation.
+
+ Carries the 4xx Response to return to the caller. Caught in `run()`, where the rejection is
+ logged once — alongside DRF ValidationErrors — so every rejected run surfaces in the logs.
+ """
+
+ def __init__(self, response: Response):
+ self.response = response
+ super().__init__()
+
+
@extend_schema_view(
partial_update=extend_schema(
request=EndpointRequestSerializer,
@@ -395,10 +412,13 @@ class EndpointViewSet(
AccessControlViewSetMixin,
PydanticModelMixin,
TaggedItemViewSetMixin,
+ LogEntryMixin,
viewsets.ModelViewSet,
):
# NOTE: Do we need to override the scopes for the "create"
scope_object = "endpoint"
+ # Read endpoint execution logs from the `log_entries` table keyed by this source.
+ log_source = ENDPOINTS_LOG_SOURCE
# Special case for query - these are all essentially read actions
scope_object_read_actions = [
"retrieve",
@@ -409,6 +429,7 @@ class EndpointViewSet(
"materialization_preview",
"materialization_status",
"get_endpoints_last_execution_times",
+ "logs",
]
scope_object_write_actions: list[str] = [
"create",
@@ -1921,8 +1942,8 @@ class EndpointViewSet(
@staticmethod
def _parse_int_param(
body_value: int | None, query_param: str | None, name: str, min_value: int | None = None
- ) -> tuple[int | None, Response | None]:
- """Parse an integer from the request body or query params. Returns (value, error_response)."""
+ ) -> int | None:
+ """Parse an integer from the request body or query params. Raises `_RunRejected` if invalid."""
value = body_value
if value is None and query_param is not None:
try:
@@ -1930,16 +1951,14 @@ class EndpointViewSet(
if min_value is not None and value < min_value:
raise ValueError()
except (ValueError, TypeError):
- return None, Response(
- {"error": f"Invalid {name} parameter: {query_param}"},
- status=status.HTTP_400_BAD_REQUEST,
+ raise _RunRejected(
+ Response({"error": f"Invalid {name} parameter: {query_param}"}, status=status.HTTP_400_BAD_REQUEST)
)
elif value is not None and min_value is not None and value < min_value:
- return None, Response(
- {"error": f"Invalid {name} parameter: {value}"},
- status=status.HTTP_400_BAD_REQUEST,
+ raise _RunRejected(
+ Response({"error": f"Invalid {name} parameter: {value}"}, status=status.HTTP_400_BAD_REQUEST)
)
- return value, None
+ return value
def _apply_pagination_to_query(self, query: dict, limit: int, offset: int) -> tuple[dict, EndpointPagination]:
"""Apply pagination to a HogQL query. Returns (modified_query, pagination).
@@ -2235,6 +2254,69 @@ class EndpointViewSet(
)
raise
+ def _log_rejected_run(self, endpoint: Endpoint, reason: str) -> None:
+ """Record a rejected run request as a failed execution so it surfaces in the endpoint logs.
+
+ Request validation runs before the execution block, so a rejected request would otherwise
+ never appear in the logs. Each rejection gets its own execution id.
+ """
+ log_endpoint_execution(
+ team_id=self.team_id,
+ endpoint_id=str(endpoint.id),
+ instance_id=str(uuid.uuid4()),
+ level="ERROR",
+ message=f"Endpoint execution failed · invalid request · {reason}",
+ )
+
+ def _resolve_version(
+ self, endpoint: Endpoint, version_number: int | None, name: str | None
+ ) -> EndpointVersion | None:
+ """Return the requested version, or None when no specific version was asked for and none exist.
+
+ Raises `_RunRejected` (404) only when a specific `version_number` was requested but not found —
+ matching the original behavior where an unspecified version falls through to the inline path.
+ """
+ try:
+ return endpoint.get_version(version_number)
+ except EndpointVersion.DoesNotExist:
+ if version_number is not None:
+ raise _RunRejected(
+ Response(
+ {
+ "error": f"Version {version_number} not found for endpoint '{name}'",
+ "current_version": endpoint.current_version,
+ },
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ )
+ return None
+
+ @staticmethod
+ def _format_validation_detail(detail: Any) -> str:
+ """Flatten a DRF ValidationError detail (str | list | dict, possibly nested) into one line."""
+ if isinstance(detail, dict):
+ return "; ".join(
+ f"{field}: {EndpointViewSet._format_validation_detail(messages)}" for field, messages in detail.items()
+ )
+ if isinstance(detail, list):
+ return "; ".join(EndpointViewSet._format_validation_detail(item) for item in detail)
+ return str(detail)
+
+ @staticmethod
+ def _parse_run_request(request: Request) -> EndpointRunRequest:
+ """Parse and validate the run request body into a clean, field-level 400 on failure.
+
+ Raises a DRF ValidationError so the caller never sees pydantic's raw error dump. Rejection
+ logging is handled centrally in `run()`.
+ """
+ try:
+ return EndpointRunRequest.model_validate(request.data)
+ except PydanticValidationError as exc:
+ field_errors = {
+ ".".join(str(part) for part in error["loc"]) or "body": error["msg"] for error in exc.errors()
+ }
+ raise ValidationError(field_errors)
+
@extend_schema(
request=EndpointRunRequest,
responses={200: EndpointRunResponseSerializer},
@@ -2245,63 +2327,56 @@ class EndpointViewSet(
"""Execute endpoint with optional parameters."""
endpoint = get_object_or_404(Endpoint, team=self.team, name=name, is_active=True, deleted=False)
self._enforce_object_level_access(endpoint)
- data = self.get_model(request.data, EndpointRunRequest)
- # Track endpoint execution for deprecation monitoring
- report_user_action(
- user=cast(User, request.user),
- event="endpoint executed",
- properties={
- "endpoint_id": str(endpoint.id),
- "endpoint_name": endpoint.name,
- "has_filters_override": bool(data.filters_override),
- "has_variables": bool(data.variables),
- "has_limit": data.limit is not None,
- "has_offset": data.offset is not None,
- "refresh_mode": data.refresh.value if data.refresh else None,
- },
- team=self.team,
- request=request,
- )
+ # All run-request validation lives in one place so every rejection — whether it raises a DRF
+ # ValidationError or returns a 4xx Response — is logged exactly once before we bail out.
+ try:
+ data = self._parse_run_request(request)
- version_number, err = self._parse_int_param(data.version, request.query_params.get("version"), "version")
- if err:
- return err
- limit, err = self._parse_int_param(data.limit, request.query_params.get("limit"), "limit", min_value=1)
- if err:
- return err
- offset, err = self._parse_int_param(data.offset, request.query_params.get("offset"), "offset", min_value=0)
- if err:
- return err
-
- if offset is not None and limit is None:
- return Response(
- {"error": "offset requires limit to be set"},
- status=status.HTTP_400_BAD_REQUEST,
+ # Track endpoint execution for deprecation monitoring
+ report_user_action(
+ user=cast(User, request.user),
+ event="endpoint executed",
+ properties={
+ "endpoint_id": str(endpoint.id),
+ "endpoint_name": endpoint.name,
+ "has_filters_override": bool(data.filters_override),
+ "has_variables": bool(data.variables),
+ "has_limit": data.limit is not None,
+ "has_offset": data.offset is not None,
+ "refresh_mode": data.refresh.value if data.refresh else None,
+ },
+ team=self.team,
+ request=request,
)
- version_obj = None
- try:
- version_obj = endpoint.get_version(version_number)
- except EndpointVersion.DoesNotExist:
- if version_number is not None:
- return Response(
- {
- "error": f"Version {version_number} not found for endpoint '{name}'",
- "current_version": endpoint.current_version,
- },
- status=status.HTTP_404_NOT_FOUND,
+ version_number = self._parse_int_param(data.version, request.query_params.get("version"), "version")
+ limit = self._parse_int_param(data.limit, request.query_params.get("limit"), "limit", min_value=1)
+ offset = self._parse_int_param(data.offset, request.query_params.get("offset"), "offset", min_value=0)
+
+ if offset is not None and limit is None:
+ raise _RunRejected(
+ Response({"error": "offset requires limit to be set"}, status=status.HTTP_400_BAD_REQUEST)
)
- self.validate_run_request(data, endpoint, version_obj)
+ version_obj = self._resolve_version(endpoint, version_number, name)
- if offset is not None and version_obj:
- query_kind = version_obj.query.get("kind")
- if query_kind != "HogQLQuery":
- return Response(
- {"error": "offset is only supported for HogQL endpoints"},
- status=status.HTTP_400_BAD_REQUEST,
+ self.validate_run_request(data, endpoint, version_obj)
+
+ if offset is not None and version_obj and version_obj.query.get("kind") != "HogQLQuery":
+ raise _RunRejected(
+ Response(
+ {"error": "offset is only supported for HogQL endpoints"}, status=status.HTTP_400_BAD_REQUEST
+ )
)
+ except ValidationError as exc:
+ self._log_rejected_run(endpoint, self._format_validation_detail(exc.detail))
+ raise
+ except _RunRejected as rejected:
+ data_ = rejected.response.data
+ reason = data_.get("error", data_) if isinstance(data_, dict) else data_
+ self._log_rejected_run(endpoint, str(reason))
+ return rejected.response
# Check if we should use materialization for this version
use_materialized = self._should_use_materialized_table(endpoint, data, version_obj)
@@ -2310,7 +2385,12 @@ class EndpointViewSet(
execution_type = "materialized" if use_materialized else "inline"
query_kind_metric = query_kind_label(version_obj.query if version_obj else None)
execution_status: str | None = None
+ execution_id = str(uuid.uuid4())
+ cache_outcome: str | None = None
+ result_row_count: int | None = None
+ error_label: str | None = None
_start_time = time.monotonic()
+ _duration = 0.0
try:
if use_materialized:
@@ -2362,6 +2442,7 @@ class EndpointViewSet(
execution_status = "success"
except (ExposedHogQLError, ExposedCHQueryError) as e:
execution_status = "error"
+ error_label = getattr(e, "code_name", None) or type(e).__name__
logger.exception(
"Endpoint execution failed",
endpoint_name=endpoint.name,
@@ -2370,6 +2451,7 @@ class EndpointViewSet(
raise ValidationError("Query execution failed.", getattr(e, "code_name", None))
except HogVMException:
execution_status = "error"
+ error_label = "HogVMException"
logger.exception(
"Endpoint execution failed (HogVM)",
endpoint_name=endpoint.name,
@@ -2377,6 +2459,7 @@ class EndpointViewSet(
raise ValidationError("Query execution failed: HogQL virtual machine error")
except ResolutionError:
execution_status = "error"
+ error_label = "ResolutionError"
logger.exception(
"Endpoint resolution failed",
endpoint_name=endpoint.name,
@@ -2385,8 +2468,9 @@ class EndpointViewSet(
except ConcurrencyLimitExceeded:
ENDPOINT_CONCURRENCY_REJECTED_TOTAL.inc()
raise Throttled(detail="Too many concurrent requests. Please try again later.")
- except Exception:
+ except Exception as e:
execution_status = "error"
+ error_label = type(e).__name__
raise
finally:
if execution_status is not None:
@@ -2397,6 +2481,19 @@ class EndpointViewSet(
ENDPOINT_EXECUTION_TOTAL.labels(
execution_type=execution_type, query_kind=query_kind_metric, status=execution_status
).inc()
+ if execution_status == "error":
+ log_endpoint_execution(
+ team_id=self.team_id,
+ endpoint_id=str(endpoint.id),
+ instance_id=execution_id,
+ level="ERROR",
+ message=build_execution_message(
+ succeeded=False,
+ execution_type=execution_type,
+ version=version_obj.version if version_obj else None,
+ error=error_label,
+ ),
+ )
try:
if isinstance(result.data, dict):
@@ -2407,13 +2504,29 @@ class EndpointViewSet(
execution_type=execution_type, query_kind=query_kind_metric, outcome=cache_outcome
).inc()
- if query_kind_metric == "hogql":
- results_value = result.data.get("results")
- if isinstance(results_value, list):
- ENDPOINT_HOGQL_RESULT_ROWS.labels(execution_type=execution_type).observe(len(results_value))
+ results_value = result.data.get("results")
+ if isinstance(results_value, list):
+ result_row_count = len(results_value)
+ if query_kind_metric == "hogql":
+ ENDPOINT_HOGQL_RESULT_ROWS.labels(execution_type=execution_type).observe(result_row_count)
except Exception:
logger.debug("Failed to record endpoint result metrics", exc_info=True)
+ log_endpoint_execution(
+ team_id=self.team_id,
+ endpoint_id=str(endpoint.id),
+ instance_id=execution_id,
+ level="INFO",
+ message=build_execution_message(
+ succeeded=True,
+ execution_type=execution_type,
+ cache_outcome=cache_outcome,
+ duration_ms=round(_duration * 1000),
+ rows=result_row_count,
+ version=version_obj.version if version_obj else None,
+ ),
+ )
+
if get_query_tag_value("access_method") == "personal_api_key":
now = timezone.now()
throttle = timedelta(minutes=30)
@@ -2428,6 +2541,7 @@ class EndpointViewSet(
if isinstance(result.data, dict):
result.data["name"] = endpoint.name
+ result.data["execution_id"] = execution_id
if version_obj:
result.data["endpoint_version"] = version_obj.version
result.data["endpoint_version_created_at"] = version_obj.created_at.isoformat()
diff --git a/products/endpoints/backend/logs.py b/products/endpoints/backend/logs.py
new file mode 100644
index 000000000000..178ea7515beb
--- /dev/null
+++ b/products/endpoints/backend/logs.py
@@ -0,0 +1,75 @@
+from datetime import UTC, datetime
+from typing import Optional
+
+import structlog
+
+from posthog.kafka_client.routing import get_producer
+from posthog.kafka_client.topics import KAFKA_LOG_ENTRIES
+
+logger = structlog.get_logger(__name__)
+
+# Matches the `log_source` column written for endpoint execution logs in the `log_entries`
+# ClickHouse table. The Logs tab and the `endpoints_logs_retrieve` API both read by this value.
+ENDPOINTS_LOG_SOURCE = "endpoints"
+
+# ClickHouse DateTime64(6, 'UTC') input format — same as the temporal logger uses.
+_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
+
+
+def build_execution_message(
+ *,
+ succeeded: bool,
+ execution_type: str,
+ cache_outcome: Optional[str] = None,
+ duration_ms: Optional[int] = None,
+ rows: Optional[int] = None,
+ version: Optional[int] = None,
+ error: Optional[str] = None,
+) -> str:
+ """One human-readable line carrying the extra data as searchable `key=value` tokens.
+
+ Only non-sensitive execution metadata belongs here. Never add variable values — they
+ routinely carry PII (emails, customer IDs, filter values) and must stay out of logs.
+ """
+ prefix = "Endpoint executed" if succeeded else "Endpoint execution failed"
+ tokens = {
+ "path": execution_type,
+ "cache": cache_outcome,
+ "duration_ms": duration_ms,
+ "rows": rows,
+ "version": version,
+ "error": error,
+ }
+ token_str = " ".join(f"{key}={value}" for key, value in tokens.items() if value is not None)
+ return f"{prefix} · {token_str}" if token_str else prefix
+
+
+def log_endpoint_execution(
+ *,
+ team_id: int,
+ endpoint_id: str,
+ instance_id: str,
+ level: str,
+ message: str,
+) -> None:
+ """Emit a user-facing endpoint execution log entry to the `log_entries` table.
+
+ Best-effort: a produce failure must never break or slow down an endpoint run, so failures are
+ swallowed (debug-logged). We don't flush — `produce()` polls non-blocking.
+ """
+ try:
+ producer = get_producer(topic=KAFKA_LOG_ENTRIES)
+ producer.produce(
+ topic=KAFKA_LOG_ENTRIES,
+ data={
+ "team_id": team_id,
+ "log_source": ENDPOINTS_LOG_SOURCE,
+ "log_source_id": str(endpoint_id),
+ "instance_id": instance_id,
+ "timestamp": datetime.now(tz=UTC).strftime(_TIMESTAMP_FORMAT),
+ "level": level,
+ "message": message,
+ },
+ )
+ except Exception:
+ logger.debug("Failed to emit endpoint execution log entry", exc_info=True)
diff --git a/products/endpoints/backend/serializers.py b/products/endpoints/backend/serializers.py
index 36c656d29feb..920f0c15b179 100644
--- a/products/endpoints/backend/serializers.py
+++ b/products/endpoints/backend/serializers.py
@@ -197,6 +197,10 @@ class EndpointRunResponseSerializer(serializers.Serializer):
"""Response from executing an endpoint query."""
name = serializers.CharField(help_text="URL-safe endpoint name that was executed.")
+ execution_id = serializers.UUIDField(
+ required=False,
+ help_text="Unique identifier for this execution. Use it to find the matching entry in the endpoint's logs.",
+ )
results = serializers.ListField(
required=False,
help_text="Query result rows. Each row is a list of values matching the columns order.",
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 2ec0599f56ea..9e7263a144de 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -199,7 +199,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("query_override", response.json()["detail"])
+ self.assertEqual(response.json()["attr"], "query_override")
def test_hogql_endpoint_rejects_filters_override(self):
endpoint = create_endpoint_with_version(
@@ -343,7 +343,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn("query_override", response.json()["detail"])
+ self.assertEqual(response.json()["attr"], "query_override")
def test_insight_endpoint_accepts_filters_override_for_backwards_compat(self):
endpoint = create_endpoint_with_version(
diff --git a/products/endpoints/backend/tests/test_endpoint_logs.py b/products/endpoints/backend/tests/test_endpoint_logs.py
new file mode 100644
index 000000000000..1b6cf2870970
--- /dev/null
+++ b/products/endpoints/backend/tests/test_endpoint_logs.py
@@ -0,0 +1,265 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest import mock
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.test.test_log_entries import create_log_entry
+from posthog.models import Team
+
+from products.endpoints.backend.logs import ENDPOINTS_LOG_SOURCE, build_execution_message, log_endpoint_execution
+from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+
+
+class TestBuildExecutionMessage(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "success_full",
+ {
+ "succeeded": True,
+ "execution_type": "materialized",
+ "cache_outcome": "hit",
+ "duration_ms": 142,
+ "rows": 1024,
+ "version": 3,
+ },
+ "Endpoint executed · path=materialized cache=hit duration_ms=142 rows=1024 version=3",
+ ),
+ (
+ "failure",
+ {
+ "succeeded": False,
+ "execution_type": "inline",
+ "error": "ResolutionError",
+ "version": 3,
+ },
+ "Endpoint execution failed · path=inline version=3 error=ResolutionError",
+ ),
+ (
+ "success_partial_tokens_omitted",
+ {"succeeded": True, "execution_type": "ducklake", "version": 1},
+ "Endpoint executed · path=ducklake version=1",
+ ),
+ ]
+ )
+ def test_build_execution_message(self, _name, kwargs, expected):
+ self.assertEqual(build_execution_message(**kwargs), expected)
+
+ def test_produce_failure_is_swallowed(self):
+ with mock.patch(
+ "products.endpoints.backend.logs.get_producer",
+ side_effect=Exception("kafka down"),
+ ):
+ # Must not raise — emitting a log line is best-effort.
+ log_endpoint_execution(
+ team_id=1,
+ endpoint_id="abc",
+ instance_id="exec-1",
+ level="INFO",
+ message="Endpoint executed",
+ )
+
+
+class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
+ def _create_hogql_endpoint(self, name: str, query: str):
+ return create_endpoint_with_version(
+ name=name,
+ team=self.team,
+ query={"kind": "HogQLQuery", "query": query},
+ created_by=self.user,
+ is_active=True,
+ )
+
+ def test_successful_run_emits_info_log(self):
+ endpoint = self._create_hogql_endpoint("logs_ok", "SELECT 1")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_log.assert_called_once()
+ kwargs = mock_log.call_args.kwargs
+ self.assertEqual(kwargs["level"], "INFO")
+ self.assertEqual(kwargs["endpoint_id"], str(endpoint.id))
+ self.assertTrue(kwargs["instance_id"])
+ self.assertIn("Endpoint executed", kwargs["message"])
+ self.assertIn("path=inline", kwargs["message"])
+ self.assertIn("rows=1", kwargs["message"])
+ self.assertIn("version=1", kwargs["message"])
+
+ def test_failed_run_emits_error_log(self):
+ endpoint = self._create_hogql_endpoint("logs_fail", "SELECT nonexistent_column_xyz FROM events")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_log.assert_called_once()
+ kwargs = mock_log.call_args.kwargs
+ self.assertEqual(kwargs["level"], "ERROR")
+ self.assertEqual(kwargs["endpoint_id"], str(endpoint.id))
+ self.assertIn("Endpoint execution failed", kwargs["message"])
+ self.assertIn("error=", kwargs["message"])
+
+ def test_successful_run_returns_execution_id_matching_log(self):
+ endpoint = self._create_hogql_endpoint("logs_exec_id", "SELECT 1")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ execution_id = response.json()["execution_id"]
+ self.assertTrue(execution_id)
+ # The id returned to the client must be the same one written to the logs, so it can be traced.
+ self.assertEqual(execution_id, mock_log.call_args.kwargs["instance_id"])
+
+ def test_invalid_refresh_mode_emits_error_log_and_clean_message(self):
+ endpoint = self._create_hogql_endpoint("logs_bad_refresh", "SELECT 1")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
+ {"refresh": "hey"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ # A rejected request must still surface as a failed execution in the logs.
+ mock_log.assert_called_once()
+ kwargs = mock_log.call_args.kwargs
+ self.assertEqual(kwargs["level"], "ERROR")
+ self.assertEqual(kwargs["endpoint_id"], str(endpoint.id))
+ self.assertIn("Endpoint execution failed", kwargs["message"])
+
+ # The customer-facing error must be clean — no pydantic internals leaking through.
+ body = response.json()
+ serialized = str(body)
+ self.assertNotIn("errors.pydantic.dev", serialized)
+ self.assertNotIn("JSON parse error", serialized)
+ self.assertIn("refresh", serialized)
+ self.assertIn("cache", serialized)
+
+ @parameterized.expand(
+ [
+ ("invalid_limit", {"limit": 0}, status.HTTP_400_BAD_REQUEST),
+ ("offset_without_limit", {"offset": 5}, status.HTTP_400_BAD_REQUEST),
+ ("version_not_found", {"version": 999}, status.HTTP_404_NOT_FOUND),
+ ]
+ )
+ def test_rejected_run_params_emit_error_log(self, _name, body, expected_status):
+ # Version/limit/offset parsing returns a 4xx Response instead of raising, but the rejection
+ # must still surface in the logs.
+ endpoint = self._create_hogql_endpoint(f"logs_reject_{_name}", "SELECT 1")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", body, format="json"
+ )
+
+ self.assertEqual(response.status_code, expected_status)
+ mock_log.assert_called_once()
+ kwargs = mock_log.call_args.kwargs
+ self.assertEqual(kwargs["level"], "ERROR")
+ self.assertEqual(kwargs["endpoint_id"], str(endpoint.id))
+ self.assertIn("Endpoint execution failed", kwargs["message"])
+
+ def test_validate_run_request_failure_emits_error_log(self):
+ # `direct` refresh is valid per the schema but rejected by validate_run_request for a
+ # non-materialized endpoint — this failure must still surface in the logs.
+ endpoint = self._create_hogql_endpoint("logs_bad_validate", "SELECT 1")
+
+ with mock.patch("products.endpoints.backend.api.log_endpoint_execution") as mock_log:
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
+ {"refresh": "direct"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ mock_log.assert_called_once()
+ kwargs = mock_log.call_args.kwargs
+ self.assertEqual(kwargs["level"], "ERROR")
+ self.assertEqual(kwargs["endpoint_id"], str(endpoint.id))
+ self.assertIn("Endpoint execution failed", kwargs["message"])
+ self.assertIn("refresh", kwargs["message"])
+
+ def test_logs_action_returns_endpoint_entries(self):
+ endpoint = self._create_hogql_endpoint("logs_read", "SELECT 1")
+ create_log_entry(
+ team_id=self.team.pk,
+ log_source=ENDPOINTS_LOG_SOURCE,
+ log_source_id=str(endpoint.id),
+ instance_id="exec-1",
+ message="Endpoint executed · path=inline cache=miss duration_ms=5 rows=1 version=1",
+ level="info",
+ timestamp="2026-01-01 12:00:00",
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/logs/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["log_source_id"], str(endpoint.id))
+ self.assertEqual(results[0]["instance_id"], "exec-1")
+ self.assertEqual(results[0]["level"], "INFO")
+ self.assertIn("path=inline", results[0]["message"])
+
+ def test_logs_action_filters_by_level(self):
+ endpoint = self._create_hogql_endpoint("logs_levels", "SELECT 1")
+ for level in ("info", "error", "info"):
+ create_log_entry(
+ team_id=self.team.pk,
+ log_source=ENDPOINTS_LOG_SOURCE,
+ log_source_id=str(endpoint.id),
+ instance_id="exec-1",
+ message=f"msg {level}",
+ level=level,
+ )
+
+ results = self.client.get(
+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/logs/", {"level": "ERROR"}
+ ).json()["results"]
+
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["level"], "ERROR")
+
+ def test_logs_action_isolated_across_teams(self):
+ other_team = Team.objects.create(organization=self.organization)
+ other_endpoint = create_endpoint_with_version(
+ name="other_team_endpoint",
+ team=other_team,
+ query={"kind": "HogQLQuery", "query": "SELECT 1"},
+ created_by=self.user,
+ is_active=True,
+ )
+ # The other team's endpoint has logs, but they must be unreachable from our team's context.
+ create_log_entry(
+ team_id=other_team.pk,
+ log_source=ENDPOINTS_LOG_SOURCE,
+ log_source_id=str(other_endpoint.id),
+ instance_id="exec-1",
+ message="Endpoint executed · path=inline",
+ level="info",
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{other_endpoint.name}/logs/")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_logs_action_rejects_invalid_limit(self):
+ endpoint = self._create_hogql_endpoint("logs_bad_limit", "SELECT 1")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/logs/", {"limit": 999})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/endpoints/frontend/EndpointScene.tsx b/products/endpoints/frontend/EndpointScene.tsx
index b9eb20225af1..a6c0ad96f8d4 100644
--- a/products/endpoints/frontend/EndpointScene.tsx
+++ b/products/endpoints/frontend/EndpointScene.tsx
@@ -8,6 +8,7 @@ import {
IconDatabase,
IconEndpoints,
IconGraph,
+ IconLive,
IconPause,
IconPlay,
IconPlayFilled,
@@ -46,6 +47,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope, EndpointVersionType } from '~/types'
import { EndpointConfiguration } from './endpoint-tabs/EndpointConfiguration'
+import { EndpointLogs } from './endpoint-tabs/EndpointLogs'
import { EndpointOverview } from './endpoint-tabs/EndpointOverview'
import { EndpointPlayground } from './endpoint-tabs/EndpointPlayground'
import { EndpointQuery } from './endpoint-tabs/EndpointQuery'
@@ -111,6 +113,15 @@ export function EndpointScene(): JSX.Element {
? combineUrl(urls.endpoint(endpoint.name), { ...searchParams, tab: EndpointTab.PLAYGROUND }).url
: undefined,
},
+ {
+ key: EndpointTab.LOGS,
+ label: 'Logs',
+ 'data-attr': 'endpoint-logs-tab',
+ content: <EndpointLogs />,
+ link: endpoint
+ ? combineUrl(urls.endpoint(endpoint.name), { ...searchParams, tab: EndpointTab.LOGS }).url
+ : undefined,
+ },
{
key: EndpointTab.HISTORY,
label: 'History',
@@ -174,6 +185,8 @@ export function EndpointScene(): JSX.Element {
return <EndpointVersions />
case EndpointTab.PLAYGROUND:
return <EndpointPlayground />
+ case EndpointTab.LOGS:
+ return <EndpointLogs />
case EndpointTab.HISTORY:
return <ActivityLog scope={[ActivityScope.ENDPOINT, ActivityScope.ENDPOINT_VERSION]} id={endpoint.id} />
case EndpointTab.QUERY:
@@ -225,6 +238,17 @@ export function EndpointScene(): JSX.Element {
<IconPlayFilled />
Open playground
</SceneMenuBarItem>
+ <SceneMenuBarItem
+ onClick={() =>
+ router.actions.push(
+ combineUrl(urls.endpoint(endpoint.name), { tab: EndpointTab.LOGS }).url
+ )
+ }
+ data-attr="endpoint-menubar-view-logs"
+ >
+ <IconLive />
+ View logs
+ </SceneMenuBarItem>
<SceneMenuBarItem
onClick={() =>
router.actions.push(
diff --git a/products/endpoints/frontend/endpoint-tabs/EndpointLogs.tsx b/products/endpoints/frontend/endpoint-tabs/EndpointLogs.tsx
new file mode 100644
index 000000000000..1f5736a71596
--- /dev/null
+++ b/products/endpoints/frontend/endpoint-tabs/EndpointLogs.tsx
@@ -0,0 +1,17 @@
+import { useValues } from 'kea'
+
+import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'
+
+import { endpointSceneLogic } from '../endpointSceneLogic'
+
+export function EndpointLogs(): JSX.Element {
+ const { endpoint } = useValues(endpointSceneLogic)
+
+ if (!endpoint) {
+ return <></>
+ }
+
+ return (
+ <LogsViewer sourceType="endpoints" sourceId={endpoint.id} groupByInstanceId={false} instanceLabel="execution" />
+ )
+}
diff --git a/products/endpoints/frontend/endpointSceneLogic.tsx b/products/endpoints/frontend/endpointSceneLogic.tsx
index 231d43c9bca0..7d5247180c04 100644
--- a/products/endpoints/frontend/endpointSceneLogic.tsx
+++ b/products/endpoints/frontend/endpointSceneLogic.tsx
@@ -95,6 +95,7 @@ export enum EndpointTab {
CONFIGURATION = 'configuration',
VERSIONS = 'versions',
PLAYGROUND = 'playground',
+ LOGS = 'logs',
HISTORY = 'history',
}
diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.ts
index cd24e250a1c3..a30ae62ba7d8 100644
--- a/products/endpoints/frontend/generated/api.schemas.ts
+++ b/products/endpoints/frontend/generated/api.schemas.ts
@@ -428,6 +428,8 @@ export interface MaterializationPreviewRequestApi {
export interface EndpointRunResponseApi {
/** URL-safe endpoint name that was executed. */
name: string
+ /** Unique identifier for this execution. Use it to find the matching entry in the endpoint's logs. */
+ execution_id?: string
/** Query result rows. Each row is a list of values matching the columns order. */
results?: unknown[]
/** Column names from the query SELECT clause. */
@@ -868,6 +870,38 @@ export type EndpointsListParams = {
offset?: number
}
+export type EndpointsLogsRetrieveParams = {
+ /**
+ * Only return entries after this ISO 8601 timestamp.
+ */
+ after?: string
+ /**
+ * Only return entries before this ISO 8601 timestamp.
+ */
+ before?: string
+ /**
+ * Filter logs to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string
+ /**
+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.
+ * @minLength 1
+ */
+ level?: string
+ /**
+ * Maximum number of log entries to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+ /**
+ * Case-insensitive substring search across log messages.
+ * @minLength 1
+ */
+ search?: string
+}
+
export type EndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
diff --git a/products/endpoints/frontend/generated/api.ts b/products/endpoints/frontend/generated/api.ts
index ae6780f8d732..b2f0184fdaaf 100644
--- a/products/endpoints/frontend/generated/api.ts
+++ b/products/endpoints/frontend/generated/api.ts
@@ -17,6 +17,7 @@ import type {
EndpointRunResponseApi,
EndpointVersionResponseApi,
EndpointsListParams,
+ EndpointsLogsRetrieveParams,
EndpointsOpenapiSpecRetrieveParams,
EndpointsVersionsListParams,
MaterializationPreviewRequestApi,
@@ -150,6 +151,34 @@ export const endpointsDestroy = async (projectId: string, name: string, options?
})
}
+export const getEndpointsLogsRetrieveUrl = (projectId: string, name: string, params?: EndpointsLogsRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/endpoints/${name}/logs/?${stringifiedParams}`
+ : `/api/projects/${projectId}/endpoints/${name}/logs/`
+}
+
+export const endpointsLogsRetrieve = async (
+ projectId: string,
+ name: string,
+ params?: EndpointsLogsRetrieveParams,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getEndpointsLogsRetrieveUrl(projectId, name, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEndpointsMaterializationPreviewCreateUrl = (projectId: string, name: string) => {
return `/api/projects/${projectId}/endpoints/${name}/materialization_preview/`
}
diff --git a/products/endpoints/mcp/tools.yaml b/products/endpoints/mcp/tools.yaml
index 26f1f8f5b47d..dbf6e7aec7d8 100644
--- a/products/endpoints/mcp/tools.yaml
+++ b/products/endpoints/mcp/tools.yaml
@@ -58,6 +58,23 @@ tools:
description: >
Get a specific endpoint by name. Returns the full endpoint configuration including query definition, version
info, materialization status, and column types. Supports ?version=N to retrieve a specific version.
+ endpoint-logs:
+ operation: endpoints_logs_retrieve
+ enabled: true
+ scopes:
+ - endpoint:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Get endpoint logs
+ description: >
+ Retrieve execution logs for an endpoint by name. Each run emits one entry with a timestamp, level (INFO or
+ ERROR), and a message whose extra data is in key=value tokens (path=materialized|inline|ducklake,
+ cache=hit|miss, duration_ms=, rows=, version=, error=). Filter by level (e.g. "ERROR"), text search (e.g.
+ "cache=miss"), time range (after/before), a specific execution (instance_id), and limit (max 500). Use to
+ debug why an endpoint failed, timed out, missed cache, or returned unexpected row counts.
endpoint-materialization-status:
operation: endpoints_materialization_status_retrieve
enabled: true
diff --git a/products/endpoints/skills/exploring-endpoint-execution-logs/SKILL.md b/products/endpoints/skills/exploring-endpoint-execution-logs/SKILL.md
new file mode 100644
index 000000000000..6808aae5e667
--- /dev/null
+++ b/products/endpoints/skills/exploring-endpoint-execution-logs/SKILL.md
@@ -0,0 +1,126 @@
+---
+name: exploring-endpoint-execution-logs
+description: >
+ Explore and diagnose a PostHog endpoint's execution logs — error messages, failed runs, cache
+ misses, slow runs, or unexpected row counts during endpoint invocations. Use when the user says
+ "my endpoint is failing", "show me the logs for endpoint X", "what error did endpoint Y produce",
+ "why did endpoint Z return no rows", "is this endpoint hitting cache", or "check the last N runs".
+ Focused on a single named endpoint's runtime log entries, not project-wide auditing or query
+ performance profiling.
+---
+
+# Exploring endpoint execution logs
+
+Every endpoint run emits one execution log entry to PostHog's `log_entries` store. This skill
+reads those entries for a specific endpoint to answer "what happened when it ran?". It is the
+log-level counterpart to `diagnosing-endpoint-performance` (which reasons about cache/materialisation
+strategy from config and `query_log`).
+
+## When to use this skill
+
+- "Why is my endpoint failing / erroring?"
+- "Show me the logs / recent runs for endpoint X"
+- "Did the last run hit cache? How many rows did it return?"
+- "What happened the last time endpoint Y ran?"
+
+If the question is "this endpoint is slow, what should I change?", use
+`diagnosing-endpoint-performance`. If it's project-wide ("what can I clean up?"), use
+`auditing-endpoints`.
+
+## What an execution log entry looks like
+
+Each run produces exactly one entry. The level is `INFO` on success and `ERROR` on failure, and the
+message carries the extra data as searchable `key=value` tokens:
+
+```text
+Endpoint executed · path=materialized cache=hit duration_ms=142 rows=1024 version=3
+Endpoint execution failed · path=inline error=ResolutionError version=3
+```
+
+Token meanings:
+
+| Token | Values | Meaning |
+| ------------- | ------------------------------------------------------------ | -------------------------------------------------------------- |
+| `path` | `materialized` / `inline` / `ducklake` / `ducklake_fallback` | Which execution path ran |
+| `cache` | `hit` / `miss` | Whether the query result cache was used (omitted for ducklake) |
+| `duration_ms` | integer | Wall-clock execution time |
+| `rows` | integer | Number of result rows returned |
+| `version` | integer | Which endpoint version ran |
+| `error` | e.g. `ResolutionError`, `HogVMException` | Error class / HogQL code name (failures only) |
+
+Each run gets a distinct `instance_id`, so logs group one-per-execution in the viewer.
+
+## Available tools
+
+| Tool | Purpose |
+| --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
+| `endpoint-logs` | Primary. Execution log entries for one endpoint by name. Filter by level, search, time range, instance_id; `limit` up to 500. |
+| `endpoint-get` | Endpoint config for context (current version, materialisation, query kind) |
+| `execute-sql` | Fallback / aggregation directly against `log_entries` (`log_source='endpoints'`) |
+
+## Filtering
+
+`endpoint-logs` exposes the standard log filters:
+
+- **level** — comma-separated, e.g. `ERROR` to see only failed runs, or `INFO,ERROR` for all.
+- **search** — case-insensitive substring over the message. Because the extra data is in
+ `key=value` tokens, you can search `cache=miss`, `path=inline`, `error=ResolutionError`, or a
+ specific `version=3`.
+- **after / before** — ISO timestamps to bound the time range.
+- **instance_id** — pin a single execution.
+- **limit** — 1–500 (default 50).
+
+## Workflow
+
+1. Identify the endpoint by name. If given a URL, parse it from
+ `/api/projects/{team_id}/endpoints/{name}/run`.
+2. Start broad: `endpoint-logs` for the endpoint with a recent time range. Skim levels and tokens.
+3. Narrow to the symptom:
+ - Failures → `level=ERROR`; read the `error=` token and `path=` to see where it broke.
+ - Cache concerns → `search=cache=miss` to see how often runs miss cache.
+ - Wrong results → compare `rows=` across runs, and `version=` to spot a regression after a
+ version bump.
+4. For counts/trends across many runs (e.g. error rate over a week), drop to `execute-sql` against
+ `log_entries`:
+
+ ```sql
+ SELECT toDate(timestamp) AS day, upper(level) AS level, count() AS runs
+ FROM log_entries
+ WHERE log_source = 'endpoints' AND log_source_id = '<endpoint_uuid>'
+ GROUP BY day, level ORDER BY day DESC
+ ```
+
+ Get the endpoint UUID from `endpoint-get` (the `log_source_id` is the endpoint id, not its name).
+
+5. Summarize: what's failing, since when, on which version/path, and whether it's a config issue
+ (hand off to `diagnosing-endpoint-performance`) or a query bug.
+
+## Example interaction
+
+```text
+User: "weekly_signups started erroring this morning"
+
+Agent steps:
+- endpoint-logs weekly_signups, level=ERROR, after=<this morning>
+ → several "Endpoint execution failed · path=inline error=ResolutionError version=5"
+- endpoint-get weekly_signups → current version is v5 (bumped today)
+- endpoint-logs weekly_signups, level=INFO, before=<this morning>
+ → prior runs: "path=inline cache=hit ... version=4" succeeded
+
+- "v5 (created this morning) is failing with a ResolutionError on the inline path — it can't
+ resolve a table or field reference. v4 ran fine. This looks like a bad query in the new
+ version. Want me to pull the v5 query (endpoint-versions) so we can fix it, or roll back to v4?"
+```
+
+## Important notes
+
+- **One entry per run.** Don't expect step-by-step traces — endpoints log a single completion line.
+ The detail lives in the tokens, not in multiple lines.
+- **`log_source_id` is the endpoint UUID**, not the name. For `execute-sql`, fetch it via
+ `endpoint-get` first.
+- **Logs are retained ~90 days** (the `log_entries` TTL). Older runs won't appear.
+- **Execution logs ≠ query performance.** `endpoint-logs` tells you what happened and why a run
+ failed; for "should I materialise / bump cache TTL?" use `diagnosing-endpoint-performance`, which
+ reasons over config and `query_log` cost metrics.
+- **Best-effort emission.** A log line is emitted after each run but never blocks it — if a run
+ succeeded for the caller but no log shows, the emit was dropped, not the query.
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 572b5f7a5d36..4e8bb56ba5b7 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -18,6 +18,9 @@ tools:
domains-scim-logs-retrieve:
operation: domains_scim_logs_retrieve
enabled: false
+ endpoints-logs-retrieve:
+ operation: endpoints_logs_retrieve
+ enabled: false
file-download-batch-exports-logs-retrieve:
operation: file_download_batch_exports_logs_retrieve
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 4fe63b6cff65..d121699b964e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1459,6 +1459,20 @@
"readOnlyHint": true
}
},
+ "endpoint-logs": {
+ "description": "Retrieve execution logs for an endpoint by name. Each run emits one entry with a timestamp, level (INFO or ERROR), and a message whose extra data is in key=value tokens (path=materialized|inline|ducklake, cache=hit|miss, duration_ms=, rows=, version=, error=). Filter by level (e.g. \"ERROR\"), text search (e.g. \"cache=miss\"), time range (after/before), a specific execution (instance_id), and limit (max 500). Use to debug why an endpoint failed, timed out, missed cache, or returned unexpected row counts.",
+ "category": "Endpoints",
+ "feature": "endpoints",
+ "summary": "Get endpoint logs",
+ "title": "Get endpoint logs",
+ "required_scopes": ["endpoint:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"endpoint-materialization-status": {
"description": "Get lightweight materialization status for an endpoint without fetching full endpoint data. Returns whether materialization is possible, current status, last run time, and any errors. Supports ?version=N.",
"category": "Endpoints",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 7ca5f6953e90..9cb12ed85e3f 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1489,6 +1489,20 @@
"readOnlyHint": true
}
},
+ "endpoint-logs": {
+ "description": "Retrieve execution logs for an endpoint by name. Each run emits one entry with a timestamp, level (INFO or ERROR), and a message whose extra data is in key=value tokens (path=materialized|inline|ducklake, cache=hit|miss, duration_ms=, rows=, version=, error=). Filter by level (e.g. \"ERROR\"), text search (e.g. \"cache=miss\"), time range (after/before), a specific execution (instance_id), and limit (max 500). Use to debug why an endpoint failed, timed out, missed cache, or returned unexpected row counts.",
+ "category": "Endpoints",
+ "feature": "endpoints",
+ "summary": "Get endpoint logs",
+ "title": "Get endpoint logs",
+ "required_scopes": ["endpoint:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"endpoint-materialization-status": {
"description": "Get lightweight materialization status for an endpoint without fetching full endpoint data. Returns whether materialization is possible, current status, last run time, and any errors. Supports ?version=N.",
"category": "Endpoints",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5b8f9e035d57..c2b5ffa3a7d9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14951,6 +14951,8 @@ export namespace Schemas {
export interface EndpointRunResponse {
/** URL-safe endpoint name that was executed. */
name: string;
+ /** Unique identifier for this execution. Use it to find the matching entry in the endpoint's logs. */
+ execution_id?: string;
/** Query result rows. Each row is a list of values matching the columns order. */
results?: unknown[];
/** Column names from the query SELECT clause. */
@@ -43513,6 +43515,38 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsEndpointsLogsRetrieveParams = {
+ /**
+ * Only return entries after this ISO 8601 timestamp.
+ */
+ after?: string;
+ /**
+ * Only return entries before this ISO 8601 timestamp.
+ */
+ before?: string;
+ /**
+ * Filter logs to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string;
+ /**
+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.
+ * @minLength 1
+ */
+ level?: string;
+ /**
+ * Maximum number of log entries to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Case-insensitive substring search across log messages.
+ * @minLength 1
+ */
+ search?: string;
+ };
+
export type EnvironmentsEndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
@@ -48958,6 +48992,38 @@ export namespace Schemas {
offset?: number;
};
+ export type EndpointsLogsRetrieveParams = {
+ /**
+ * Only return entries after this ISO 8601 timestamp.
+ */
+ after?: string;
+ /**
+ * Only return entries before this ISO 8601 timestamp.
+ */
+ before?: string;
+ /**
+ * Filter logs to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string;
+ /**
+ * Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.
+ * @minLength 1
+ */
+ level?: string;
+ /**
+ * Maximum number of log entries to return (1-500, default 50).
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Case-insensitive substring search across log messages.
+ * @minLength 1
+ */
+ search?: string;
+ };
+
export type EndpointsOpenapiSpecRetrieveParams = {
/**
* Specific endpoint version to generate the spec for. Defaults to latest.
diff --git a/services/mcp/src/generated/endpoints/api.ts b/services/mcp/src/generated/endpoints/api.ts
index 5406e4fa5dc6..1cbedb55bd70 100644
--- a/services/mcp/src/generated/endpoints/api.ts
+++ b/services/mcp/src/generated/endpoints/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 11 enabled ops
+ * PostHog API - MCP 12 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -159,6 +159,41 @@ export const EndpointsDestroyParams = /* @__PURE__ */ zod.object({
),
})
+export const EndpointsLogsRetrieveParams = /* @__PURE__ */ zod.object({
+ name: zod.string(),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const endpointsLogsRetrieveQueryLimitDefault = 50
+export const endpointsLogsRetrieveQueryLimitMax = 500
+
+export const EndpointsLogsRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ after: zod.iso.datetime({ offset: true }).optional().describe('Only return entries after this ISO 8601 timestamp.'),
+ before: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('Only return entries before this ISO 8601 timestamp.'),
+ instance_id: zod.string().min(1).optional().describe('Filter logs to a specific execution instance.'),
+ level: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ "Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR."
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(endpointsLogsRetrieveQueryLimitMax)
+ .default(endpointsLogsRetrieveQueryLimitDefault)
+ .describe('Maximum number of log entries to return (1-500, default 50).'),
+ search: zod.string().min(1).optional().describe('Case-insensitive substring search across log messages.'),
+})
+
/**
* Preview the materialization transform for an endpoint. Shows what the query will look like after materialization, including range pair detection and bucket functions.
*/
diff --git a/services/mcp/src/tools/generated/endpoints.ts b/services/mcp/src/tools/generated/endpoints.ts
index 0d3dce40d4df..37d2a0ad00c8 100644
--- a/services/mcp/src/tools/generated/endpoints.ts
+++ b/services/mcp/src/tools/generated/endpoints.ts
@@ -7,6 +7,8 @@ import {
EndpointsDestroyParams,
EndpointsLastExecutionTimesCreateBody,
EndpointsListQueryParams,
+ EndpointsLogsRetrieveParams,
+ EndpointsLogsRetrieveQueryParams,
EndpointsMaterializationPreviewCreateBody,
EndpointsMaterializationPreviewCreateParams,
EndpointsMaterializationStatusRetrieveParams,
@@ -95,6 +97,31 @@ const endpointGet = (): ToolBase<typeof EndpointGetSchema, WithPostHogUrl<Schema
},
})
+const EndpointLogsSchema = EndpointsLogsRetrieveParams.omit({ project_id: true }).extend(
+ EndpointsLogsRetrieveQueryParams.shape
+)
+
+const endpointLogs = (): ToolBase<typeof EndpointLogsSchema, unknown> => ({
+ name: 'endpoint-logs',
+ schema: EndpointLogsSchema,
+ handler: async (context: Context, params: z.infer<typeof EndpointLogsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/endpoints/${encodeURIComponent(String(params.name))}/logs/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ instance_id: params.instance_id,
+ level: params.level,
+ limit: params.limit,
+ search: params.search,
+ },
+ })
+ return await withPostHogUrl(context, result, '/endpoints')
+ },
+})
+
const EndpointMaterializationStatusSchema = EndpointsMaterializationStatusRetrieveParams.omit({ project_id: true })
const endpointMaterializationStatus = (): ToolBase<
@@ -331,6 +358,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'endpoint-create': endpointCreate,
'endpoint-delete': endpointDelete,
'endpoint-get': endpointGet,
+ 'endpoint-logs': endpointLogs,
'endpoint-materialization-status': endpointMaterializationStatus,
'endpoint-openapi-spec': endpointOpenapiSpec,
'endpoint-run': endpointRun,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoint-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoint-logs.json
new file mode 100644
index 000000000000..2bb4e16a0226
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/endpoint-logs.json
@@ -0,0 +1,44 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "after": {
+ "description": "Only return entries after this ISO 8601 timestamp.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "before": {
+ "description": "Only return entries before this ISO 8601 timestamp.",
+ "format": "date-time",
+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "type": "string"
+ },
+ "instance_id": {
+ "description": "Filter logs to a specific execution instance.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "level": {
+ "description": "Comma-separated log levels to include, e.g. 'WARN,ERROR'. Valid levels: DEBUG, LOG, INFO, WARN, ERROR.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "limit": {
+ "default": 50,
+ "description": "Maximum number of log entries to return (1-500, default 50).",
+ "maximum": 500,
+ "minimum": 1,
+ "type": "number"
+ },
+ "name": {
+ "type": "string"
+ },
+ "search": {
+ "description": "Case-insensitive substring search across log messages.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["name"],
+ "type": "object"
+}