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: BK drill-down via read_data + MCP endpoint (C) (#62623)

Alex Vc6b0df16049f
diff --git a/products/business_knowledge/backend/api/__init__.py b/products/business_knowledge/backend/api/__init__.py
index d3bc05e01030..36ac74e53709 100644
--- a/products/business_knowledge/backend/api/__init__.py
+++ b/products/business_knowledge/backend/api/__init__.py
@@ -1,3 +1,3 @@
-from .views import KnowledgeSourceViewSet
+from .views import KnowledgeDocumentViewSet, KnowledgeSourceViewSet
-__all__ = ["KnowledgeSourceViewSet"]
+__all__ = ["KnowledgeDocumentViewSet", "KnowledgeSourceViewSet"]
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index 5d784ada3487..2aea24388ce0 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -331,6 +331,41 @@ class CreateCrawlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, ser
return attrs
+class KnowledgeDocumentWindowSerializer(serializers.Serializer):
+ """
+ One chunk in a drill-down window over a single knowledge document.
+
+ Output-only — the rows come from the `get_document_window` logic helper
+ (a `KnowledgeSearchResult` dataclass), not the ORM, so this is a plain
+ read serializer rather than a `ModelSerializer`.
+ """
+
+ chunk_id = serializers.UUIDField(
+ read_only=True,
+ help_text="Stable identifier of this chunk. Same value used in search results.",
+ )
+ ordinal = serializers.IntegerField(
+ read_only=True,
+ help_text="Zero-based position of this chunk within its document. Use it as `around_ordinal` to recenter the window.",
+ )
+ content = serializers.CharField(
+ read_only=True,
+ help_text="The chunk's text content.",
+ )
+ heading_path = serializers.CharField(
+ read_only=True,
+ help_text="Breadcrumb of section headings this chunk sits under. Empty when the document has no heading structure.",
+ )
+ source_name = serializers.CharField(
+ read_only=True,
+ help_text="Human label of the knowledge source this chunk belongs to.",
+ )
+ document_title = serializers.CharField(
+ read_only=True,
+ help_text="Title of the document this chunk belongs to.",
+ )
+
+
class CreateFileSourceSerializer(_NameValidationMixin, serializers.Serializer):
"""
Multipart upload payload for file sources. The file's content type is
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.py
index 5abbaebd50c6..90864b175de0 100644
--- a/products/business_knowledge/backend/api/views.py
+++ b/products/business_knowledge/backend/api/views.py
@@ -9,7 +9,8 @@ from django.db.models import QuerySet
import structlog
from asgiref.sync import async_to_sync
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import exceptions, status, viewsets
from rest_framework.decorators import action
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
@@ -24,8 +25,9 @@ from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle
from posthog.temporal.common.client import sync_connect
from .. import logic
+from ..constants import BK_DRILLDOWN_DEFAULT_RADIUS, BK_DRILLDOWN_MAX_RADIUS
from ..file_parse import FileParseError
-from ..models import KnowledgeSource, SourceType
+from ..models import KnowledgeDocument, KnowledgeSource, SourceType
from ..models.constants import CrawlMode
from ..temporal.coordinator import IngestSourceInputs, RefreshSourceInputs
from .serializers import (
@@ -33,6 +35,7 @@ from .serializers import (
CreateFileSourceSerializer,
CreateTextSourceSerializer,
CreateUrlSourceSerializer,
+ KnowledgeDocumentWindowSerializer,
KnowledgeSourceSerializer,
UpdateTextSourceSerializer,
UpdateUrlSourceSerializer,
@@ -352,3 +355,85 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not logic.delete_source(source_id, self.team_id):
raise exceptions.NotFound()
return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """
+ Read-only access to parsed knowledge documents. Currently exposes only the
+ `window` drill-down so an agent (PHAI or MCP) can pull a wider context span
+ around a chunk it found via search.
+ """
+
+ scope_object = "business_knowledge"
+ queryset = KnowledgeDocument.objects.unscoped()
+ serializer_class = KnowledgeDocumentWindowSerializer
+ permission_classes = [IsAuthenticated, APIScopePermission, PostHogFeatureFlagPermission]
+ posthog_feature_flag = "product-business-knowledge"
+ throttle_classes = [BurstRateThrottle, SustainedRateThrottle]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return queryset.filter(team_id=self.team_id)
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "around_ordinal",
+ OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Zero-based chunk ordinal to center the window on (from a search result).",
+ ),
+ OpenApiParameter(
+ "radius",
+ OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ f"Number of chunks before and after the center to include. "
+ f"Defaults to {BK_DRILLDOWN_DEFAULT_RADIUS}, clamped to [0, {BK_DRILLDOWN_MAX_RADIUS}]."
+ ),
+ ),
+ ],
+ responses={200: KnowledgeDocumentWindowSerializer(many=True)},
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="window",
+ pagination_class=None,
+ # Custom actions aren't in APIScopePermission's default read list, so
+ # programmatic tokens (personal API key / OAuth — how MCP authenticates)
+ # would otherwise be rejected as "does not support personal API key access".
+ required_scopes=["business_knowledge:read"],
+ )
+ def window(self, request: Request, pk: str, **kwargs) -> Response:
+ try:
+ document_id = UUID(pk)
+ except (ValueError, DjangoValidationError):
+ raise exceptions.NotFound()
+
+ # 404 for unknown / cross-team docs before touching the chunk window so
+ # an attacker can't probe doc existence. `.unscoped()` + explicit
+ # team_id filter mirrors the source viewset (the manager needs an
+ # explicit team scope otherwise).
+ if not KnowledgeDocument.objects.unscoped().filter(id=document_id, team_id=self.team_id).exists():
+ raise exceptions.NotFound()
+
+ around_ordinal = self._parse_int_param(request, "around_ordinal", required=True)
+ radius = self._parse_int_param(request, "radius", required=False, default=BK_DRILLDOWN_DEFAULT_RADIUS)
+
+ results = logic.get_document_window(self.team_id, document_id, around_ordinal, radius=radius)
+ return Response(KnowledgeDocumentWindowSerializer(instance=results, many=True).data)
+
+ def _parse_int_param(self, request: Request, name: str, *, required: bool, default: int | None = None) -> int:
+ raw = request.query_params.get(name)
+ if raw is None:
+ if required:
+ raise exceptions.ValidationError({name: "This query parameter is required."})
+ if default is None:
+ raise ValueError(f"Non-required param {name!r} must have a non-None default")
+ return default
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ raise exceptions.ValidationError({name: "Must be an integer."})
diff --git a/products/business_knowledge/backend/routes.py b/products/business_knowledge/backend/routes.py
index 4f0da34c7e78..65128d5f2fc3 100644
--- a/products/business_knowledge/backend/routes.py
+++ b/products/business_knowledge/backend/routes.py
@@ -1,6 +1,6 @@
from posthog.api.routing import RouterRegistry
-from products.business_knowledge.backend.api import KnowledgeSourceViewSet
+from products.business_knowledge.backend.api import KnowledgeDocumentViewSet, KnowledgeSourceViewSet
def register_routes(routers: RouterRegistry) -> None:
@@ -10,3 +10,9 @@ def register_routes(routers: RouterRegistry) -> None:
"environment_business_knowledge_sources",
["team_id"],
)
+ routers.projects.register(
+ r"business_knowledge/documents",
+ KnowledgeDocumentViewSet,
+ "environment_business_knowledge_documents",
+ ["team_id"],
+ )
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index 03bc94fcc5ae..1d139ce9c857 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -5,7 +5,8 @@ from rest_framework import status
from posthog.models.activity_logging.activity_log import ActivityLog
-from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource
+from products.business_knowledge.backend import logic
+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SafetyVerdict
@patch("posthoganalytics.feature_enabled", return_value=True)
@@ -108,3 +109,127 @@ class TestKnowledgeSourceAPI(APIBaseTest):
response = self.client.post(self.url, {"name": "Docs", "text": "hello"}, format="json")
assert response.status_code == status.HTTP_201_CREATED
assert response.json()["source_type"] == "text"
+
+
+@patch("posthoganalytics.feature_enabled", return_value=True)
+class TestKnowledgeDocumentWindowAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.base = f"/api/projects/{self.team.id}/business_knowledge/documents"
+
+ def _ready_safe_document(self, *, paragraphs: int = 10, team=None) -> KnowledgeDocument:
+ """Create a READY text source with exactly `paragraphs` chunks, all SAFE."""
+ team = team or self.team
+ # Each paragraph is padded past CHUNK_TARGET_CHARS (1200) but under
+ # CHUNK_HARD_MAX_CHARS (1600) so the chunker emits one chunk per
+ # paragraph — giving deterministic ordinals to window around.
+ filler = "lorem ipsum dolor sit amet " * 50
+ text = "\n\n".join(f"Paragraph {i}: {filler}" for i in range(paragraphs))
+ source = logic.create_text_source(team_id=team.id, created_by_id=self.user.id, name="Docs", text=text)
+ # create_text_source leaves the doc UNKNOWN (excluded from search/drill-down)
+ # until the classifier clears it — mark SAFE so the window returns chunks.
+ KnowledgeDocument.objects.unscoped().filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)
+ return KnowledgeDocument.objects.unscoped().get(source_id=source.id)
+
+ def test_window_returns_contiguous_span(self, _ff) -> None:
+ doc = self._ready_safe_document(paragraphs=10)
+ response = self.client.get(f"{self.base}/{doc.id}/window/?around_ordinal=5&radius=2")
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ ordinals = [row["ordinal"] for row in body]
+ assert ordinals == [3, 4, 5, 6, 7]
+ first = body[0]
+ assert set(first.keys()) == {
+ "chunk_id",
+ "ordinal",
+ "content",
+ "heading_path",
+ "source_name",
+ "document_title",
+ }
+ assert first["source_name"] == "Docs"
+
+ def test_window_defaults_radius(self, _ff) -> None:
+ doc = self._ready_safe_document(paragraphs=20)
+ response = self.client.get(f"{self.base}/{doc.id}/window/?around_ordinal=10")
+ assert response.status_code == status.HTTP_200_OK
+ # Default radius is 5 -> ordinals 5..15.
+ ordinals = [row["ordinal"] for row in response.json()]
+ assert ordinals == list(range(5, 16))
+
+ def test_window_requires_around_ordinal(self, _ff) -> None:
+ doc = self._ready_safe_document()
+ response = self.client.get(f"{self.base}/{doc.id}/window/")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json().get("attr") == "around_ordinal"
+
+ def test_window_rejects_non_integer_params(self, _ff) -> None:
+ doc = self._ready_safe_document()
+ response = self.client.get(f"{self.base}/{doc.id}/window/?around_ordinal=abc")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json().get("attr") == "around_ordinal"
+
+ def test_window_unknown_document_is_404(self, _ff) -> None:
+ import uuid
+
+ response = self.client.get(f"{self.base}/{uuid.uuid4()}/window/?around_ordinal=0")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_window_invalid_uuid_is_404(self, _ff) -> None:
+ response = self.client.get(f"{self.base}/not-a-uuid/window/?around_ordinal=0")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_window_cross_team_document_is_404(self, _ff) -> None:
+ from posthog.models.team import Team
+
+ other_team = Team.objects.create_with_data(
+ organization=self.organization, initiating_user=self.user, name="Other"
+ )
+ theirs = self._ready_safe_document(team=other_team)
+ response = self.client.get(f"{self.base}/{theirs.id}/window/?around_ordinal=0")
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_window_excludes_unsafe_document(self, _ff) -> None:
+ # A document that exists in the team but is not SAFE has no readable
+ # chunks, so the window comes back empty (200, []), never leaking content.
+ doc = self._ready_safe_document(paragraphs=5)
+ KnowledgeDocument.objects.unscoped().filter(id=doc.id).update(safety_verdict=SafetyVerdict.UNSAFE)
+ response = self.client.get(f"{self.base}/{doc.id}/window/?around_ordinal=2")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+
+ def test_window_feature_flag_gated(self, _ff) -> None:
+ doc = self._ready_safe_document()
+ _ff.return_value = False
+ response = self.client.get(f"{self.base}/{doc.id}/window/?around_ordinal=0")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+
+@patch("posthoganalytics.feature_enabled", return_value=True)
+class TestKnowledgeDocumentWindowScopes(APIBaseTest):
+ """The window endpoint is the BK MCP surface; MCP authenticates with a
+ personal API key / OAuth token, so the custom action must enforce
+ `business_knowledge:read` (not silently 403 every programmatic caller)."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ text = "\n\n".join(f"Paragraph {i}: {'lorem ipsum dolor sit amet ' * 50}" for i in range(5))
+ source = logic.create_text_source(team_id=self.team.id, created_by_id=self.user.id, name="Docs", text=text)
+ KnowledgeDocument.objects.unscoped().filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)
+ self.doc = KnowledgeDocument.objects.unscoped().get(source_id=source.id)
+ self.url = f"/api/projects/{self.team.id}/business_knowledge/documents/{self.doc.id}/window/?around_ordinal=2"
+
+ def _auth_with_pak(self, scopes: list[str]) -> None:
+ key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {key}")
+
+ def test_read_scope_allows_window(self, _ff) -> None:
+ self._auth_with_pak(["business_knowledge:read"])
+ response = self.client.get(self.url)
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ def test_wrong_scope_is_forbidden(self, _ff) -> None:
+ self._auth_with_pak(["insight:read"])
+ response = self.client.get(self.url)
+ assert response.status_code == status.HTTP_403_FORBIDDEN
diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.ts
index 74083132591a..2518aca96283 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -7,6 +7,28 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * One chunk in a drill-down window over a single knowledge document.
+ *
+ * Output-only — the rows come from the `get_document_window` logic helper
+ * (a `KnowledgeSearchResult` dataclass), not the ORM, so this is a plain
+ * read serializer rather than a `ModelSerializer`.
+ */
+export interface KnowledgeDocumentWindowApi {
+ /** Stable identifier of this chunk. Same value used in search results. */
+ readonly chunk_id: string
+ /** Zero-based position of this chunk within its document. Use it as `around_ordinal` to recenter the window. */
+ readonly ordinal: number
+ /** The chunk's text content. */
+ readonly content: string
+ /** Breadcrumb of section headings this chunk sits under. Empty when the document has no heading structure. */
+ readonly heading_path: string
+ /** Human label of the knowledge source this chunk belongs to. */
+ readonly source_name: string
+ /** Title of the document this chunk belongs to. */
+ readonly document_title: string
+}
+
/**
* * `text` - Text
* * `url` - URL
@@ -150,6 +172,17 @@ export interface PatchedUpdateTextSourceApi {
text?: string
}
+export type BusinessKnowledgeDocumentsWindowListParams = {
+ /**
+ * Zero-based chunk ordinal to center the window on (from a search result).
+ */
+ around_ordinal: number
+ /**
+ * Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].
+ */
+ radius?: number
+}
+
export type BusinessKnowledgeSourcesListParams = {
/**
* Number of results to return per page.
diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.ts
index a714f7bf2fd5..0d846b91bd92 100644
--- a/products/business_knowledge/frontend/generated/api.ts
+++ b/products/business_knowledge/frontend/generated/api.ts
@@ -9,9 +9,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ BusinessKnowledgeDocumentsWindowListParams,
BusinessKnowledgeSourcesListParams,
BusinessKnowledgeSourcesTextRetrieve200,
CreateTextSourceApi,
+ KnowledgeDocumentWindowApi,
KnowledgeSourceApi,
PaginatedKnowledgeSourceListApi,
PatchedUpdateTextSourceApi,
@@ -34,6 +36,43 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getBusinessKnowledgeDocumentsWindowListUrl = (
+ projectId: string,
+ id: string,
+ params: BusinessKnowledgeDocumentsWindowListParams
+) => {
+ 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}/business_knowledge/documents/${id}/window/?${stringifiedParams}`
+ : `/api/projects/${projectId}/business_knowledge/documents/${id}/window/`
+}
+
+/**
+ * Read-only access to parsed knowledge documents. Currently exposes only the
+ * `window` drill-down so an agent (PHAI or MCP) can pull a wider context span
+ * around a chunk it found via search.
+ */
+export const businessKnowledgeDocumentsWindowList = async (
+ projectId: string,
+ id: string,
+ params: BusinessKnowledgeDocumentsWindowListParams,
+ options?: RequestInit
+): Promise<KnowledgeDocumentWindowApi[]> => {
+ return apiMutator<KnowledgeDocumentWindowApi[]>(getBusinessKnowledgeDocumentsWindowListUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getBusinessKnowledgeSourcesListUrl = (projectId: string, params?: BusinessKnowledgeSourcesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yaml
new file mode 100644
index 000000000000..f1dbed4912f0
--- /dev/null
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -0,0 +1,45 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Business knowledge
+feature: business_knowledge
+url_prefix: /business_knowledge
+ui_apps: {}
+tools:
+ business-knowledge-document-window-retrieve:
+ operation: business_knowledge_documents_window_list
+ enabled: true
+ scopes:
+ - business_knowledge:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Read business knowledge document context
+ description: >
+ Returns a window of content chunks from a business knowledge document, centered around a specific ordinal.
+ Use after searching knowledge to get more surrounding context for a specific result.
+ business-knowledge-sources-create:
+ operation: business_knowledge_sources_create
+ enabled: false
+ business-knowledge-sources-destroy:
+ operation: business_knowledge_sources_destroy
+ enabled: false
+ business-knowledge-sources-list:
+ operation: business_knowledge_sources_list
+ enabled: false
+ business-knowledge-sources-partial-update:
+ operation: business_knowledge_sources_partial_update
+ enabled: false
+ business-knowledge-sources-refresh-create:
+ operation: business_knowledge_sources_refresh_create
+ enabled: false
+ business-knowledge-sources-retrieve:
+ operation: business_knowledge_sources_retrieve
+ enabled: false
+ business-knowledge-sources-text-retrieve:
+ operation: business_knowledge_sources_text_retrieve
+ enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 7446e961231f..9d722a8072c4 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -603,6 +603,20 @@
"readOnlyHint": true
}
},
+ "business-knowledge-document-window-retrieve": {
+ "description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Read business knowledge document context",
+ "title": "Read business knowledge document context",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-function-templates-list": {
"description": "List available function templates. Templates are pre-built function configurations for common integrations (Slack, webhooks, email, etc.) and transformations (GeoIP, etc.). Filter by type (destination, site_destination, site_app, transformation, etc.) via the 'type' query parameter. Results are sorted by popularity (number of active functions using each template).",
"category": "Function templates",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 14913085f5b5..fae751e30e2f 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -619,6 +619,20 @@
"readOnlyHint": true
}
},
+ "business-knowledge-document-window-retrieve": {
+ "description": "Returns a window of content chunks from a business knowledge document, centered around a specific ordinal. Use after searching knowledge to get more surrounding context for a specific result.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Read business knowledge document context",
+ "title": "Read business knowledge document context",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"cdp-function-templates-list": {
"description": "List available function templates. Templates are pre-built function configurations for common integrations (Slack, webhooks, email, etc.) and transformations (GeoIP, etc.). Filter by type (destination, site_destination, site_app, transformation, etc.) via the 'type' query parameter. Results are sorted by popularity (number of active functions using each template).",
"category": "Function templates",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ab575da0bcb3..342f3b1afe30 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21376,6 +21376,28 @@ export namespace Schemas {
'20': '2.0',
} as const;
+ /**
+ * One chunk in a drill-down window over a single knowledge document.
+ *
+ * Output-only — the rows come from the `get_document_window` logic helper
+ * (a `KnowledgeSearchResult` dataclass), not the ORM, so this is a plain
+ * read serializer rather than a `ModelSerializer`.
+ */
+ export interface KnowledgeDocumentWindow {
+ /** Stable identifier of this chunk. Same value used in search results. */
+ readonly chunk_id: string;
+ /** Zero-based position of this chunk within its document. Use it as `around_ordinal` to recenter the window. */
+ readonly ordinal: number;
+ /** The chunk's text content. */
+ readonly content: string;
+ /** Breadcrumb of section headings this chunk sits under. Empty when the document has no heading structure. */
+ readonly heading_path: string;
+ /** Human label of the knowledge source this chunk belongs to. */
+ readonly source_name: string;
+ /** Title of the document this chunk belongs to. */
+ readonly document_title: string;
+ }
+
/**
* * `text` - Text
* * `url` - URL
@@ -47645,6 +47667,17 @@ export namespace Schemas {
search?: string;
};
+ export type BusinessKnowledgeDocumentsWindowListParams = {
+ /**
+ * Zero-based chunk ordinal to center the window on (from a search result).
+ */
+ around_ordinal: number;
+ /**
+ * Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].
+ */
+ radius?: number;
+ };
+
export type BusinessKnowledgeSourcesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/business_knowledge/api.ts b/services/mcp/src/generated/business_knowledge/api.ts
new file mode 100644
index 000000000000..94cc13ba9859
--- /dev/null
+++ b/services/mcp/src/generated/business_knowledge/api.ts
@@ -0,0 +1,31 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 1 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Read-only access to parsed knowledge documents. Currently exposes only the
+ * `window` drill-down so an agent (PHAI or MCP) can pull a wider context span
+ * around a chunk it found via search.
+ */
+export const BusinessKnowledgeDocumentsWindowListParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this knowledge document.'),
+ 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 BusinessKnowledgeDocumentsWindowListQueryParams = /* @__PURE__ */ zod.object({
+ around_ordinal: zod.number().describe('Zero-based chunk ordinal to center the window on (from a search result).'),
+ radius: zod
+ .number()
+ .optional()
+ .describe('Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].'),
+})
diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.ts
new file mode 100644
index 000000000000..c37fd6748a0b
--- /dev/null
+++ b/services/mcp/src/tools/generated/business_knowledge.ts
@@ -0,0 +1,37 @@
+// AUTO-GENERATED from products/business_knowledge/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ BusinessKnowledgeDocumentsWindowListParams,
+ BusinessKnowledgeDocumentsWindowListQueryParams,
+} from '@/generated/business_knowledge/api'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const BusinessKnowledgeDocumentWindowRetrieveSchema = BusinessKnowledgeDocumentsWindowListParams.omit({
+ project_id: true,
+}).extend(BusinessKnowledgeDocumentsWindowListQueryParams.shape)
+
+const businessKnowledgeDocumentWindowRetrieve = (): ToolBase<
+ typeof BusinessKnowledgeDocumentWindowRetrieveSchema,
+ Schemas.KnowledgeDocumentWindow[]
+> => ({
+ name: 'business-knowledge-document-window-retrieve',
+ schema: BusinessKnowledgeDocumentWindowRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeDocumentWindowRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.KnowledgeDocumentWindow[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/documents/${encodeURIComponent(String(params.id))}/window/`,
+ query: {
+ around_ordinal: params.around_ordinal,
+ radius: params.radius,
+ },
+ })
+ return result
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'business-knowledge-document-window-retrieve': businessKnowledgeDocumentWindowRetrieve,
+}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 56495a5ea332..3cf1149f126f 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -6,6 +6,7 @@ import { GENERATED_TOOLS as ai_observability } from './ai_observability'
import { GENERATED_TOOLS as alerts } from './alerts'
import { GENERATED_TOOLS as annotations } from './annotations'
import { GENERATED_TOOLS as batch_exports } from './batch_exports'
+import { GENERATED_TOOLS as business_knowledge } from './business_knowledge'
import { GENERATED_TOOLS as cdp_function_templates } from './cdp_function_templates'
import { GENERATED_TOOLS as cdp_functions } from './cdp_functions'
import { GENERATED_TOOLS as cohorts } from './cohorts'
@@ -49,6 +50,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...alerts,
...annotations,
...batch_exports,
+ ...business_knowledge,
...cdp_function_templates,
...cdp_functions,
...cohorts,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/business-knowledge-document-window-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/business-knowledge-document-window-retrieve.json
new file mode 100644
index 000000000000..915269637fac
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/business-knowledge-document-window-retrieve.json
@@ -0,0 +1,19 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "around_ordinal": {
+ "description": "Zero-based chunk ordinal to center the window on (from a search result).",
+ "type": "number"
+ },
+ "id": {
+ "description": "A UUID string identifying this knowledge document.",
+ "type": "string"
+ },
+ "radius": {
+ "description": "Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].",
+ "type": "number"
+ }
+ },
+ "required": ["id", "around_ordinal"],
+ "type": "object"
+}