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: add hybrid search MCP tool for knowledge retrieval (#62899)

Alex Vc072ac8a9d37
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index 2aea24388ce0..5b1c1f789253 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -366,6 +366,52 @@ class KnowledgeDocumentWindowSerializer(serializers.Serializer):
)
+class KnowledgeSearchResultSerializer(serializers.Serializer):
+ """
+ One ranked chunk from a business knowledge search.
+
+ Output-only — the rows come from the ``search_knowledge_for_team`` logic
+ helper (a ``KnowledgeSearchResult`` dataclass), not the ORM.
+ """
+
+ chunk_id = serializers.UUIDField(
+ read_only=True,
+ help_text="Stable identifier of this chunk.",
+ )
+ document_id = serializers.UUIDField(
+ read_only=True,
+ help_text="ID of the parent document. Pass to the document-window endpoint with `around_ordinal` to drill down.",
+ )
+ ordinal = serializers.IntegerField(
+ read_only=True,
+ help_text="Zero-based position of this chunk within its document. Use as `around_ordinal` in the document-window endpoint.",
+ )
+ source_id = serializers.UUIDField(
+ read_only=True,
+ help_text="ID of the knowledge source this chunk belongs to.",
+ )
+ source_name = serializers.CharField(
+ read_only=True,
+ help_text="Human label of the knowledge source this chunk belongs to.",
+ )
+ source_type = serializers.CharField(
+ read_only=True,
+ help_text="Source type (text, url, or file).",
+ )
+ document_title = serializers.CharField(
+ read_only=True,
+ help_text="Title of the document this chunk belongs to.",
+ )
+ 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.",
+ )
+ content = serializers.CharField(
+ read_only=True,
+ help_text="The chunk's text content.",
+ )
+
+
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 90864b175de0..40b81a7417a8 100644
--- a/products/business_knowledge/backend/api/views.py
+++ b/products/business_knowledge/backend/api/views.py
@@ -36,6 +36,7 @@ from .serializers import (
CreateTextSourceSerializer,
CreateUrlSourceSerializer,
KnowledgeDocumentWindowSerializer,
+ KnowledgeSearchResultSerializer,
KnowledgeSourceSerializer,
UpdateTextSourceSerializer,
UpdateUrlSourceSerializer,
@@ -359,9 +360,9 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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.
+ Read-only access to parsed knowledge documents. Exposes hybrid search
+ (``search``) and a drill-down window (``window``) so an agent (PHAI or
+ MCP) can find and explore business knowledge chunks.
"""
scope_object = "business_knowledge"
@@ -425,6 +426,40 @@ class KnowledgeDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
results = logic.get_document_window(self.team_id, document_id, around_ordinal, radius=radius)
return Response(KnowledgeDocumentWindowSerializer(instance=results, many=True).data)
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "query",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Natural-language search query. Runs hybrid (semantic + full-text) retrieval over all SAFE, READY knowledge chunks in this project.",
+ ),
+ OpenApiParameter(
+ "limit",
+ OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of ranked chunks to return. Defaults to 10, capped at 20.",
+ ),
+ ],
+ responses={200: KnowledgeSearchResultSerializer(many=True)},
+ )
+ @action(
+ detail=False,
+ methods=["get"],
+ url_path="search",
+ pagination_class=None,
+ required_scopes=["business_knowledge:read"],
+ )
+ def search(self, request: Request, **kwargs) -> Response:
+ query = request.query_params.get("query")
+ if not query or not query.strip():
+ raise exceptions.ValidationError({"query": "This query parameter is required."})
+ limit = self._parse_int_param(request, "limit", required=False, default=10)
+ results = logic.search_knowledge_for_team(self.team, query.strip(), limit=limit)
+ return Response(KnowledgeSearchResultSerializer(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:
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 93ed88a0e878..05e798359933 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -24,8 +24,10 @@ from django.utils import timezone
import structlog
+from posthog.api.embedding_worker import generate_embedding
from posthog.helpers.full_text_search import process_query
from posthog.models.scoping import with_team_scope
+from posthog.models.team.team import Team
from posthog.security.url_validation import is_url_allowed
from . import crawl, discover, file_parse, html_parse, url_fetch
@@ -1760,6 +1762,28 @@ def search_knowledge(
]
+def search_knowledge_for_team(
+ team: Team,
+ query: str,
+ *,
+ limit: int = 10,
+) -> list[KnowledgeSearchResult]:
+ """
+ Sync orchestration of hybrid BK search: embed the query, then call
+ ``search_knowledge``. Falls back to FTS-only on any embedding failure.
+
+ Used by the DRF search endpoint (sync view). The async PHAI tool path
+ uses ``async_generate_embedding`` directly — they share ``search_knowledge``
+ as the common layer, not this wrapper.
+ """
+ embedding: list[float] | None = None
+ try:
+ embedding = generate_embedding(team, query, model=BK_EMBEDDING_MODEL).embedding
+ except Exception:
+ logger.warning("bk_query_embedding_failed", team_id=team.id, exc_info=True)
+ return search_knowledge(team.id, query, limit=limit, use_semantic=embedding is not None, query_embedding=embedding)
+
+
# ---------------------------------------------------------------------------
# Drill-down: wider context window for a single document
# ---------------------------------------------------------------------------
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index 1d139ce9c857..44542a85ad89 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -233,3 +233,123 @@ class TestKnowledgeDocumentWindowScopes(APIBaseTest):
self._auth_with_pak(["insight:read"])
response = self.client.get(self.url)
assert response.status_code == status.HTTP_403_FORBIDDEN
+
+
+# ---------------------------------------------------------------------------
+# Search endpoint
+# ---------------------------------------------------------------------------
+
+
+@patch("posthoganalytics.feature_enabled", return_value=True)
+class TestKnowledgeDocumentSearchAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/business_knowledge/documents/search/"
+
+ def _ready_safe_source(self, *, name: str = "Docs", text: str | None = None, team=None) -> KnowledgeSource:
+ team = team or self.team
+ if text is None:
+ filler = "lorem ipsum dolor sit amet " * 50
+ text = "\n\n".join(f"Paragraph {i}: {filler}" for i in range(5))
+ source = logic.create_text_source(team_id=team.id, created_by_id=self.user.id, name=name, text=text)
+ KnowledgeDocument.objects.unscoped().filter(source_id=source.id).update(safety_verdict=SafetyVerdict.SAFE)
+ return source
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_returns_ranked_chunks(self, _embed, _ff) -> None:
+ self._ready_safe_source(
+ text="Pricing plans are available on request.\n\n" + "x " * 600 + "\n\nOur refund policy is flexible."
+ )
+ response = self.client.get(self.url, {"query": "pricing"})
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert len(body) >= 1
+ first = body[0]
+ assert set(first.keys()) == {
+ "chunk_id",
+ "document_id",
+ "ordinal",
+ "source_id",
+ "source_name",
+ "source_type",
+ "document_title",
+ "heading_path",
+ "content",
+ }
+ assert first["source_name"] == "Docs"
+ assert "pricing" in first["content"].lower() or "Pricing" in first["content"]
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_requires_query(self, _embed, _ff) -> None:
+ self._ready_safe_source()
+ response = self.client.get(self.url)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json().get("attr") == "query"
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_rejects_blank_query(self, _embed, _ff) -> None:
+ self._ready_safe_source()
+ response = self.client.get(self.url, {"query": " "})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_cross_team_isolation(self, _embed, _ff) -> None:
+ from posthog.models.team import Team
+
+ other_team = Team.objects.create_with_data(
+ organization=self.organization, initiating_user=self.user, name="Other"
+ )
+ self._ready_safe_source(name="Theirs", text="secret pricing data " * 60, team=other_team)
+ response = self.client.get(self.url, {"query": "secret pricing"})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_excludes_unsafe_documents(self, _embed, _ff) -> None:
+ source = self._ready_safe_source(text="Return policy details " * 60)
+ KnowledgeDocument.objects.unscoped().filter(source_id=source.id).update(safety_verdict=SafetyVerdict.UNSAFE)
+ response = self.client.get(self.url, {"query": "return policy"})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+
+ def test_search_feature_flag_gated(self, _ff) -> None:
+ _ff.return_value = False
+ response = self.client.get(self.url, {"query": "anything"})
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_search_embedding_failure_falls_back_to_fts(self, _embed, _ff) -> None:
+ self._ready_safe_source(text="Deployment guide for kubernetes " * 60)
+ response = self.client.get(self.url, {"query": "kubernetes"})
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert len(body) >= 1
+ assert "kubernetes" in body[0]["content"].lower()
+
+
+@patch("posthoganalytics.feature_enabled", return_value=True)
+class TestKnowledgeDocumentSearchScopes(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ filler = "lorem ipsum dolor sit amet " * 50
+ text = "\n\n".join(f"Paragraph {i}: {filler}" for i in range(3))
+ 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.url = f"/api/projects/{self.team.id}/business_knowledge/documents/search/?query=lorem"
+
+ 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}")
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_read_scope_allows_search(self, _embed, _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
+
+ @patch("posthog.api.embedding_worker.generate_embedding", side_effect=Exception("unavailable"))
+ def test_wrong_scope_is_forbidden(self, _embed, _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 2518aca96283..c7c7b0cb47fc 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -29,6 +29,33 @@ export interface KnowledgeDocumentWindowApi {
readonly document_title: string
}
+/**
+ * One ranked chunk from a business knowledge search.
+ *
+ * Output-only — the rows come from the ``search_knowledge_for_team`` logic
+ * helper (a ``KnowledgeSearchResult`` dataclass), not the ORM.
+ */
+export interface KnowledgeSearchResultApi {
+ /** Stable identifier of this chunk. */
+ readonly chunk_id: string
+ /** ID of the parent document. Pass to the document-window endpoint with `around_ordinal` to drill down. */
+ readonly document_id: string
+ /** Zero-based position of this chunk within its document. Use as `around_ordinal` in the document-window endpoint. */
+ readonly ordinal: number
+ /** ID of the knowledge source this chunk belongs to. */
+ readonly source_id: string
+ /** Human label of the knowledge source this chunk belongs to. */
+ readonly source_name: string
+ /** Source type (text, url, or file). */
+ readonly source_type: string
+ /** Title of the document this chunk belongs to. */
+ readonly document_title: string
+ /** Breadcrumb of section headings this chunk sits under. Empty when the document has no heading structure. */
+ readonly heading_path: string
+ /** The chunk's text content. */
+ readonly content: string
+}
+
/**
* * `text` - Text
* * `url` - URL
@@ -183,6 +210,17 @@ export type BusinessKnowledgeDocumentsWindowListParams = {
radius?: number
}
+export type BusinessKnowledgeDocumentsSearchListParams = {
+ /**
+ * Maximum number of ranked chunks to return. Defaults to 10, capped at 20.
+ */
+ limit?: number
+ /**
+ * Natural-language search query. Runs hybrid (semantic + full-text) retrieval over all SAFE, READY knowledge chunks in this project.
+ */
+ query: string
+}
+
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 0d846b91bd92..afffd9155921 100644
--- a/products/business_knowledge/frontend/generated/api.ts
+++ b/products/business_knowledge/frontend/generated/api.ts
@@ -9,11 +9,13 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ BusinessKnowledgeDocumentsSearchListParams,
BusinessKnowledgeDocumentsWindowListParams,
BusinessKnowledgeSourcesListParams,
BusinessKnowledgeSourcesTextRetrieve200,
CreateTextSourceApi,
KnowledgeDocumentWindowApi,
+ KnowledgeSearchResultApi,
KnowledgeSourceApi,
PaginatedKnowledgeSourceListApi,
PatchedUpdateTextSourceApi,
@@ -57,9 +59,9 @@ export const getBusinessKnowledgeDocumentsWindowListUrl = (
}
/**
- * 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.
+ * Read-only access to parsed knowledge documents. Exposes hybrid search
+ * (``search``) and a drill-down window (``window``) so an agent (PHAI or
+ * MCP) can find and explore business knowledge chunks.
*/
export const businessKnowledgeDocumentsWindowList = async (
projectId: string,
@@ -73,6 +75,41 @@ export const businessKnowledgeDocumentsWindowList = async (
})
}
+export const getBusinessKnowledgeDocumentsSearchListUrl = (
+ projectId: string,
+ params: BusinessKnowledgeDocumentsSearchListParams
+) => {
+ 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/search/?${stringifiedParams}`
+ : `/api/projects/${projectId}/business_knowledge/documents/search/`
+}
+
+/**
+ * Read-only access to parsed knowledge documents. Exposes hybrid search
+ * (``search``) and a drill-down window (``window``) so an agent (PHAI or
+ * MCP) can find and explore business knowledge chunks.
+ */
+export const businessKnowledgeDocumentsSearchList = async (
+ projectId: string,
+ params: BusinessKnowledgeDocumentsSearchListParams,
+ options?: RequestInit
+): Promise<KnowledgeSearchResultApi[]> => {
+ return apiMutator<KnowledgeSearchResultApi[]>(getBusinessKnowledgeDocumentsSearchListUrl(projectId, 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
index 48fff1182858..85e80741cf0e 100644
--- a/products/business_knowledge/mcp/tools.yaml
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -23,6 +23,21 @@ tools:
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.
feature_flag: product-business-knowledge
+ business-knowledge-documents-search:
+ operation: business_knowledge_documents_search_list
+ enabled: true
+ scopes:
+ - business_knowledge:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Search business knowledge
+ description: >
+ Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with
+ document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use
+ for any question about the team's own product, policies, domain knowledge, or internal docs.
+ feature_flag: product-business-knowledge
business-knowledge-sources-destroy:
operation: business_knowledge_sources_destroy
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 09515c53c025..075638b7ed60 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -618,6 +618,21 @@
},
"feature_flag": "product-business-knowledge"
},
+ "business-knowledge-documents-search": {
+ "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Search business knowledge",
+ "title": "Search business knowledge",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-sources-list": {
"description": "List all business knowledge sources in the project, with document/chunk counts, processing status, and refresh metadata.",
"category": "Business knowledge",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 97e19b184895..1b8aa3a3568e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -634,6 +634,21 @@
},
"feature_flag": "product-business-knowledge"
},
+ "business-knowledge-documents-search": {
+ "description": "Hybrid (semantic + full-text) search over the project's business knowledge base. Returns ranked chunks with document_id and ordinal — pass these to the document-window tool to drill down into surrounding context. Use for any question about the team's own product, policies, domain knowledge, or internal docs.",
+ "category": "Business knowledge",
+ "feature": "business_knowledge",
+ "summary": "Search business knowledge",
+ "title": "Search business knowledge",
+ "required_scopes": ["business_knowledge:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "product-business-knowledge"
+ },
"business-knowledge-sources-list": {
"description": "List all business knowledge sources in the project, with document/chunk counts, processing status, and refresh metadata.",
"category": "Business knowledge",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fea760bfa43f..5d77eb40f910 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21883,6 +21883,33 @@ export namespace Schemas {
readonly document_title: string;
}
+ /**
+ * One ranked chunk from a business knowledge search.
+ *
+ * Output-only — the rows come from the ``search_knowledge_for_team`` logic
+ * helper (a ``KnowledgeSearchResult`` dataclass), not the ORM.
+ */
+ export interface KnowledgeSearchResult {
+ /** Stable identifier of this chunk. */
+ readonly chunk_id: string;
+ /** ID of the parent document. Pass to the document-window endpoint with `around_ordinal` to drill down. */
+ readonly document_id: string;
+ /** Zero-based position of this chunk within its document. Use as `around_ordinal` in the document-window endpoint. */
+ readonly ordinal: number;
+ /** ID of the knowledge source this chunk belongs to. */
+ readonly source_id: string;
+ /** Human label of the knowledge source this chunk belongs to. */
+ readonly source_name: string;
+ /** Source type (text, url, or file). */
+ readonly source_type: string;
+ /** Title of the document this chunk belongs to. */
+ readonly document_title: string;
+ /** Breadcrumb of section headings this chunk sits under. Empty when the document has no heading structure. */
+ readonly heading_path: string;
+ /** The chunk's text content. */
+ readonly content: string;
+ }
+
/**
* * `text` - Text
* * `url` - URL
@@ -48381,6 +48408,17 @@ export namespace Schemas {
radius?: number;
};
+ export type BusinessKnowledgeDocumentsSearchListParams = {
+ /**
+ * Maximum number of ranked chunks to return. Defaults to 10, capped at 20.
+ */
+ limit?: number;
+ /**
+ * Natural-language search query. Runs hybrid (semantic + full-text) retrieval over all SAFE, READY knowledge chunks in this project.
+ */
+ query: string;
+ };
+
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
index 0ea6c71fdce3..367bc5c23584 100644
--- a/services/mcp/src/generated/business_knowledge/api.ts
+++ b/services/mcp/src/generated/business_knowledge/api.ts
@@ -3,15 +3,15 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 4 enabled ops
+ * PostHog API - MCP 5 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.
+ * Read-only access to parsed knowledge documents. Exposes hybrid search
+ * (``search``) and a drill-down window (``window``) so an agent (PHAI or
+ * MCP) can find and explore business knowledge chunks.
*/
export const BusinessKnowledgeDocumentsWindowListParams = /* @__PURE__ */ zod.object({
id: zod.string().describe('A UUID string identifying this knowledge document.'),
@@ -30,6 +30,28 @@ export const BusinessKnowledgeDocumentsWindowListQueryParams = /* @__PURE__ */ z
.describe('Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].'),
})
+/**
+ * Read-only access to parsed knowledge documents. Exposes hybrid search
+ * (``search``) and a drill-down window (``window``) so an agent (PHAI or
+ * MCP) can find and explore business knowledge chunks.
+ */
+export const BusinessKnowledgeDocumentsSearchListParams = /* @__PURE__ */ zod.object({
+ 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 BusinessKnowledgeDocumentsSearchListQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod.number().optional().describe('Maximum number of ranked chunks to return. Defaults to 10, capped at 20.'),
+ query: zod
+ .string()
+ .describe(
+ 'Natural-language search query. Runs hybrid (semantic + full-text) retrieval over all SAFE, READY knowledge chunks in this project.'
+ ),
+})
+
export const BusinessKnowledgeSourcesListParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.ts
index eed9d713b625..caff2431495a 100644
--- a/services/mcp/src/tools/generated/business_knowledge.ts
+++ b/services/mcp/src/tools/generated/business_knowledge.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
+ BusinessKnowledgeDocumentsSearchListQueryParams,
BusinessKnowledgeDocumentsWindowListParams,
BusinessKnowledgeDocumentsWindowListQueryParams,
BusinessKnowledgeSourcesCreateBody,
@@ -37,6 +38,28 @@ const businessKnowledgeDocumentWindowRetrieve = (): ToolBase<
},
})
+const BusinessKnowledgeDocumentsSearchSchema = BusinessKnowledgeDocumentsSearchListQueryParams
+
+const businessKnowledgeDocumentsSearch = (): ToolBase<
+ typeof BusinessKnowledgeDocumentsSearchSchema,
+ Schemas.KnowledgeSearchResult[]
+> => ({
+ name: 'business-knowledge-documents-search',
+ schema: BusinessKnowledgeDocumentsSearchSchema,
+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeDocumentsSearchSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.KnowledgeSearchResult[]>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/documents/search/`,
+ query: {
+ limit: params.limit,
+ query: params.query,
+ },
+ })
+ return result
+ },
+})
+
const BusinessKnowledgeSourcesListSchema = BusinessKnowledgeSourcesListQueryParams
const businessKnowledgeSourcesList = (): ToolBase<
@@ -145,6 +168,7 @@ const businessKnowledgeSourcesUrlCreate = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'business-knowledge-document-window-retrieve': businessKnowledgeDocumentWindowRetrieve,
+ 'business-knowledge-documents-search': businessKnowledgeDocumentsSearch,
'business-knowledge-sources-list': businessKnowledgeSourcesList,
'business-knowledge-sources-retrieve': businessKnowledgeSourcesRetrieve,
'business-knowledge-sources-text-create': businessKnowledgeSourcesTextCreate,