:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: bk mcp for creating and listing sources (#62846)
Alex V8184af8d0c4b
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.ymlindex 9b83353792a0..fe24972af030 100644--- a/.github/workflows/ci-mcp.yml+++ b/.github/workflows/ci-mcp.yml@@ -268,7 +268,7 @@ jobs:DISABLE_SECURE_SSL_REDIRECT: 'True'CLICKHOUSE_LOGS_CLUSTER_SECURE: 'False'CELERY_METRICS_PORT: 8999- POSTHOG_FEATURE_FLAGS_FORCE_ENABLED: 'logs-alerting,dashboard-widgets'+ POSTHOG_FEATURE_FLAGS_FORCE_ENABLED: 'logs-alerting,dashboard-widgets,product-business-knowledge'# Required for the feature_flags test_evaluation endpoint, which authenticates# historical-flag override requests to the Rust flags service. Any non-empty# value is fine for CI — the Rust service in the test stack accepts it.diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yamlindex f1dbed4912f0..48fff1182858 100644--- a/products/business_knowledge/mcp/tools.yaml+++ b/products/business_knowledge/mcp/tools.yaml@@ -6,7 +6,7 @@# All other fields (title, description, enrich_url, etc.) are yours to configure.category: Business knowledgefeature: business_knowledge-url_prefix: /business_knowledge+url_prefix: /business-knowledgeui_apps: {}tools:business-knowledge-document-window-retrieve:@@ -22,15 +22,40 @@ tools: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+ feature_flag: product-business-knowledgebusiness-knowledge-sources-destroy:operation: business_knowledge_sources_destroyenabled: falsebusiness-knowledge-sources-list:operation: business_knowledge_sources_list- enabled: false+ enabled: true+ scopes:+ - business_knowledge:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List business knowledge sources+ description: >+ List all business knowledge sources in the project, with document/chunk counts, processing status, and+ refresh metadata.+ feature_flag: product-business-knowledge+ response:+ include:+ - id+ - name+ - source_type+ - status+ - error_message+ - document_count+ - chunk_count+ - source_url+ - has_unsafe_documents+ - refresh_interval+ - next_refresh_at+ - created_at+ - updated_atbusiness-knowledge-sources-partial-update:operation: business_knowledge_sources_partial_updateenabled: false@@ -39,7 +64,59 @@ tools:enabled: falsebusiness-knowledge-sources-retrieve:operation: business_knowledge_sources_retrieve- enabled: false+ enabled: true+ scopes:+ - business_knowledge:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get business knowledge source+ description: >+ Get a single business knowledge source by ID, including processing status, document/chunk counts, and+ refresh metadata.+ feature_flag: product-business-knowledge+ business-knowledge-sources-text-create:+ operation: business_knowledge_sources_create+ enabled: true+ scopes:+ - business_knowledge:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create text business knowledge source+ description: >+ Save durable, reusable company knowledge as a searchable text source — the kind of reference material a team+ wants every future agent session to draw on. Good fits: product specs, internal docs, runbooks, policies,+ FAQs, glossaries, architecture/decision records, brand or style guides. Do NOT use this as a scratchpad for+ the current task or to dump transient material (raw web-search results, random articles, one-off snippets,+ chat logs) — only persist knowledge the user has asked to keep or that is clearly of lasting value to the+ whole team. Never store secrets or personal data. Provide a short descriptive name and the raw text (capped+ at 1 MB); it is chunked, embedded, and made searchable. Returns the created source with its processing+ status.+ feature_flag: product-business-knowledgebusiness-knowledge-sources-text-retrieve:operation: business_knowledge_sources_text_retrieveenabled: false+ business-knowledge-sources-url-create:+ operation: business_knowledge_sources_create+ enabled: true+ scopes:+ - business_knowledge:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ input_schema: BusinessKnowledgeUrlSourceCreateSchema+ title: Create URL business knowledge source+ description: >+ Index a web page as durable, reusable company knowledge that every future agent session can draw on. Use it+ for authoritative, lasting references the whole team benefits from — public product docs, API references,+ help-center articles, changelogs, status/policy pages. Do NOT index pages you happened to open while+ researching the current task, arbitrary search-result links, or pages the user didn't ask to keep — this+ store is curated team knowledge, not a browsing history. Provide a name and a public HTTP(S) URL; the page+ is fetched, parsed, chunked, and made searchable. Optionally set a refresh interval so the source is+ re-fetched automatically. Returns the created source with its processing status (initially "processing"+ while the URL is fetched in the background).+ feature_flag: product-business-knowledgediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 22f1835d957d..45ae0c4f1c5d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -615,7 +615,68 @@"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",+ "feature": "business_knowledge",+ "summary": "List business knowledge sources",+ "title": "List business knowledge sources",+ "required_scopes": ["business_knowledge:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-retrieve": {+ "description": "Get a single business knowledge source by ID, including processing status, document/chunk counts, and refresh metadata.",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Get business knowledge source",+ "title": "Get business knowledge source",+ "required_scopes": ["business_knowledge:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-text-create": {+ "description": "Save durable, reusable company knowledge as a searchable text source — the kind of reference material a team wants every future agent session to draw on. Good fits: product specs, internal docs, runbooks, policies, FAQs, glossaries, architecture/decision records, brand or style guides. Do NOT use this as a scratchpad for the current task or to dump transient material (raw web-search results, random articles, one-off snippets, chat logs) — only persist knowledge the user has asked to keep or that is clearly of lasting value to the whole team. Never store secrets or personal data. Provide a short descriptive name and the raw text (capped at 1 MB); it is chunked, embedded, and made searchable. Returns the created source with its processing status.",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Create text business knowledge source",+ "title": "Create text business knowledge source",+ "required_scopes": ["business_knowledge:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-url-create": {+ "description": "Index a web page as durable, reusable company knowledge that every future agent session can draw on. Use it for authoritative, lasting references the whole team benefits from — public product docs, API references, help-center articles, changelogs, status/policy pages. Do NOT index pages you happened to open while researching the current task, arbitrary search-result links, or pages the user didn't ask to keep — this store is curated team knowledge, not a browsing history. Provide a name and a public HTTP(S) URL; the page is fetched, parsed, chunked, and made searchable. Optionally set a refresh interval so the source is re-fetched automatically. Returns the created source with its processing status (initially \"processing\" while the URL is fetched in the background).",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Create URL business knowledge source",+ "title": "Create URL business knowledge source",+ "required_scopes": ["business_knowledge:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-business-knowledge"},"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).",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fe32963bb183..90aac4cedeac 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -631,7 +631,68 @@"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",+ "feature": "business_knowledge",+ "summary": "List business knowledge sources",+ "title": "List business knowledge sources",+ "required_scopes": ["business_knowledge:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-retrieve": {+ "description": "Get a single business knowledge source by ID, including processing status, document/chunk counts, and refresh metadata.",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Get business knowledge source",+ "title": "Get business knowledge source",+ "required_scopes": ["business_knowledge:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-text-create": {+ "description": "Save durable, reusable company knowledge as a searchable text source — the kind of reference material a team wants every future agent session to draw on. Good fits: product specs, internal docs, runbooks, policies, FAQs, glossaries, architecture/decision records, brand or style guides. Do NOT use this as a scratchpad for the current task or to dump transient material (raw web-search results, random articles, one-off snippets, chat logs) — only persist knowledge the user has asked to keep or that is clearly of lasting value to the whole team. Never store secrets or personal data. Provide a short descriptive name and the raw text (capped at 1 MB); it is chunked, embedded, and made searchable. Returns the created source with its processing status.",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Create text business knowledge source",+ "title": "Create text business knowledge source",+ "required_scopes": ["business_knowledge:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-business-knowledge"+ },+ "business-knowledge-sources-url-create": {+ "description": "Index a web page as durable, reusable company knowledge that every future agent session can draw on. Use it for authoritative, lasting references the whole team benefits from — public product docs, API references, help-center articles, changelogs, status/policy pages. Do NOT index pages you happened to open while researching the current task, arbitrary search-result links, or pages the user didn't ask to keep — this store is curated team knowledge, not a browsing history. Provide a name and a public HTTP(S) URL; the page is fetched, parsed, chunked, and made searchable. Optionally set a refresh interval so the source is re-fetched automatically. Returns the created source with its processing status (initially \"processing\" while the URL is fetched in the background).",+ "category": "Business knowledge",+ "feature": "business_knowledge",+ "summary": "Create URL business knowledge source",+ "title": "Create URL business knowledge source",+ "required_scopes": ["business_knowledge:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "product-business-knowledge"},"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).",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 044077728ca1..644971122b7e 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -15,6 +15,35 @@},"required": ["projectId"]},+ "BusinessKnowledgeUrlSourceCreateSchema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "maxLength": 255,+ "description": "Short human label for the source. Shown in the settings list and in agent citations."+ },+ "url": {+ "type": "string",+ "maxLength": 2048,+ "format": "uri",+ "description": "Public HTTP(S) URL to fetch. Private or internal hosts are rejected."+ },+ "source_type": {+ "default": "url",+ "description": "Source type. Always \"url\" for this tool.",+ "type": "string",+ "const": "url"+ },+ "refresh_interval": {+ "default": "manual",+ "description": "How often to auto-refresh this source in the background. Defaults to \"manual\" (no auto-refresh).",+ "type": "string",+ "enum": ["manual", "1h", "6h", "24h", "7d"]+ }+ },+ "required": ["name", "url"]+ },"DebugMcpUiAppsSchema": {"type": "object","properties": {diff --git a/services/mcp/src/generated/business_knowledge/api.ts b/services/mcp/src/generated/business_knowledge/api.tsindex 94cc13ba9859..0ea6c71fdce3 100644--- a/services/mcp/src/generated/business_knowledge/api.ts+++ b/services/mcp/src/generated/business_knowledge/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 1 enabled ops+ * PostHog API - MCP 4 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -29,3 +29,47 @@ export const BusinessKnowledgeDocumentsWindowListQueryParams = /* @__PURE__ */ z.optional().describe('Number of chunks before and after the center to include. Defaults to 5, clamped to [0, 15].'),})++export const BusinessKnowledgeSourcesListParams = /* @__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 BusinessKnowledgeSourcesListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++export const BusinessKnowledgeSourcesCreateParams = /* @__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 businessKnowledgeSourcesCreateBodyNameMax = 255++export const BusinessKnowledgeSourcesCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(businessKnowledgeSourcesCreateBodyNameMax)+ .describe('Short human label for the source. Shown in the settings list and in agent citations.'),+ text: zod+ .string()+ .describe(+ 'Raw text to index. Capped at 1 MB; larger payloads should be split into multiple sources or wait for URL/file support in Stage 2/3.'+ ),+})++export const BusinessKnowledgeSourcesRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this knowledge source.'),+ 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/."+ ),+})diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 9a8c938aa753..f33859b84c97 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -1,5 +1,19 @@import { z } from 'zod'+export const BusinessKnowledgeUrlSourceCreateSchema = z.object({+ name: z+ .string()+ .max(255)+ .describe('Short human label for the source. Shown in the settings list and in agent citations.'),+ url: z.string().url().max(2048).describe('Public HTTP(S) URL to fetch. Private or internal hosts are rejected.'),+ source_type: z.literal('url').default('url').describe('Source type. Always "url" for this tool.'),+ refresh_interval: z+ .enum(['manual', '1h', '6h', '24h', '7d'])+ .optional()+ .default('manual')+ .describe('How often to auto-refresh this source in the background. Defaults to "manual" (no auto-refresh).'),+})+export const ExternalDataJobsAfterSchema = z.string().describe('ISO timestamp — only return jobs created after this date (e.g. "2025-01-01T00:00:00Z").')diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.tsindex c37fd6748a0b..eed9d713b625 100644--- a/services/mcp/src/tools/generated/business_knowledge.ts+++ b/services/mcp/src/tools/generated/business_knowledge.ts@@ -5,7 +5,12 @@ import type { Schemas } from '@/api/generated'import {BusinessKnowledgeDocumentsWindowListParams,BusinessKnowledgeDocumentsWindowListQueryParams,+ BusinessKnowledgeSourcesCreateBody,+ BusinessKnowledgeSourcesListQueryParams,+ BusinessKnowledgeSourcesRetrieveParams,} from '@/generated/business_knowledge/api'+import { BusinessKnowledgeUrlSourceCreateSchema } from '@/schema/tool-inputs'+import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const BusinessKnowledgeDocumentWindowRetrieveSchema = BusinessKnowledgeDocumentsWindowListParams.omit({@@ -32,6 +37,116 @@ const businessKnowledgeDocumentWindowRetrieve = (): ToolBase<},})+const BusinessKnowledgeSourcesListSchema = BusinessKnowledgeSourcesListQueryParams++const businessKnowledgeSourcesList = (): ToolBase<+ typeof BusinessKnowledgeSourcesListSchema,+ WithPostHogUrl<Schemas.PaginatedKnowledgeSourceList>+> => ({+ name: 'business-knowledge-sources-list',+ schema: BusinessKnowledgeSourcesListSchema,+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeSourcesListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedKnowledgeSourceList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ const filtered = {+ ...result,+ results: (result.results ?? []).map((item: any) =>+ pickResponseFields(item, [+ 'id',+ 'name',+ 'source_type',+ 'status',+ 'error_message',+ 'document_count',+ 'chunk_count',+ 'source_url',+ 'has_unsafe_documents',+ 'refresh_interval',+ 'next_refresh_at',+ 'created_at',+ 'updated_at',+ ])+ ),+ } as typeof result+ return await withPostHogUrl(context, filtered, '/business-knowledge')+ },+})++const BusinessKnowledgeSourcesRetrieveSchema = BusinessKnowledgeSourcesRetrieveParams.omit({ project_id: true })++const businessKnowledgeSourcesRetrieve = (): ToolBase<+ typeof BusinessKnowledgeSourcesRetrieveSchema,+ Schemas.KnowledgeSource+> => ({+ name: 'business-knowledge-sources-retrieve',+ schema: BusinessKnowledgeSourcesRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeSourcesRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.KnowledgeSource>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const BusinessKnowledgeSourcesTextCreateSchema = BusinessKnowledgeSourcesCreateBody++const businessKnowledgeSourcesTextCreate = (): ToolBase<+ typeof BusinessKnowledgeSourcesTextCreateSchema,+ Schemas.KnowledgeSource+> => ({+ name: 'business-knowledge-sources-text-create',+ schema: BusinessKnowledgeSourcesTextCreateSchema,+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeSourcesTextCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.text !== undefined) {+ body['text'] = params.text+ }+ const result = await context.api.request<Schemas.KnowledgeSource>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/`,+ body,+ })+ return result+ },+})++const BusinessKnowledgeSourcesUrlCreateSchema = BusinessKnowledgeUrlSourceCreateSchema++const businessKnowledgeSourcesUrlCreate = (): ToolBase<+ typeof BusinessKnowledgeSourcesUrlCreateSchema,+ Schemas.KnowledgeSource+> => ({+ name: 'business-knowledge-sources-url-create',+ schema: BusinessKnowledgeSourcesUrlCreateSchema,+ handler: async (context: Context, params: z.infer<typeof BusinessKnowledgeSourcesUrlCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const parsedParams = BusinessKnowledgeSourcesUrlCreateSchema.parse(params)+ const result = await context.api.request<Schemas.KnowledgeSource>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/`,+ body: parsedParams,+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'business-knowledge-document-window-retrieve': businessKnowledgeDocumentWindowRetrieve,+ 'business-knowledge-sources-list': businessKnowledgeSourcesList,+ 'business-knowledge-sources-retrieve': businessKnowledgeSourcesRetrieve,+ 'business-knowledge-sources-text-create': businessKnowledgeSourcesTextCreate,+ 'business-knowledge-sources-url-create': businessKnowledgeSourcesUrlCreate,}diff --git a/services/mcp/tests/tools/businessKnowledge.integration.test.ts b/services/mcp/tests/tools/businessKnowledge.integration.test.tsnew file mode 100644index 000000000000..38c08b89c87d--- /dev/null+++ b/services/mcp/tests/tools/businessKnowledge.integration.test.ts@@ -0,0 +1,145 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest'++import {+ TEST_ORG_ID,+ TEST_PROJECT_ID,+ createTestClient,+ createTestContext,+ generateUniqueKey,+ getToolByName,+ parseToolResponse,+ setActiveProjectAndOrg,+ validateEnvironmentVariables,+} from '@/shared/test-utils'+import { GENERATED_TOOLS as FF_TOOLS } from '@/tools/generated/feature_flags'+import type { Context } from '@/tools/types'++const BK_FEATURE_FLAG = 'product-business-knowledge'++describe('Business knowledge sources', { concurrent: false }, () => {+ let context: Context+ const createdSourceIds: string[] = []++ beforeAll(async () => {+ validateEnvironmentVariables()+ const client = createTestClient()+ context = createTestContext(client)+ await setActiveProjectAndOrg(context, TEST_PROJECT_ID!, TEST_ORG_ID!)++ // The BK API is gated behind the product-business-knowledge flag — ensure it's active.+ const listFlags = FF_TOOLS['feature-flag-get-all']!()+ const updateFlag = FF_TOOLS['update-feature-flag']!()+ const createFlag = FF_TOOLS['create-feature-flag']!()++ const flagsResult = await listFlags.handler(context, { search: BK_FEATURE_FLAG })+ const flags = (flagsResult as any).results ?? []+ const flag = flags.find((f: any) => f.key === BK_FEATURE_FLAG)++ if (flag && !flag.active) {+ await updateFlag.handler(context, { id: flag.id, active: true })+ } else if (!flag) {+ await createFlag.handler(context, {+ key: BK_FEATURE_FLAG,+ name: 'Business knowledge',+ active: true,+ filters: {+ groups: [{ properties: [], rollout_percentage: 100 }],+ },+ })+ }+ })++ afterAll(async () => {+ for (const id of createdSourceIds) {+ try {+ await context.api.request({+ method: 'DELETE',+ path: `/api/projects/${TEST_PROJECT_ID}/business_knowledge/sources/${id}/`,+ })+ } catch (error) {+ console.warn(`Failed to cleanup knowledge source ${id}:`, error)+ }+ }+ })++ describe('text-create and retrieve', () => {+ const textCreateTool = getToolByName('business-knowledge-sources-text-create')+ const retrieveTool = getToolByName('business-knowledge-sources-retrieve')++ it('should create a text source and retrieve it by ID', async () => {+ const name = generateUniqueKey('MCP Text Source')+ const result = await textCreateTool.handler(context, {+ name,+ text: 'PostHog is an open-source product analytics platform.',+ })+ const source = parseToolResponse(result)++ expect(source.id).toBeTruthy()+ expect(source.name).toBe(name)+ expect(source.source_type).toBe('text')+ createdSourceIds.push(source.id)++ const retrieved = parseToolResponse(await retrieveTool.handler(context, { id: source.id }))+ expect(retrieved.id).toBe(source.id)+ expect(retrieved.name).toBe(name)+ expect(retrieved.source_type).toBe('text')+ expect(retrieved).not.toHaveProperty('_posthogUrl')+ })+ })++ describe('url-create', () => {+ const urlCreateTool = getToolByName('business-knowledge-sources-url-create')++ // Must be a public host: claim_url_source runs the SSRF check (is_url_allowed),+ // which blocks localhost/private hosts. The actual fetch is backgrounded and not+ // awaited here, so the URL only needs to pass SSRF, not return real content.+ const PUBLIC_TEST_URL = 'https://example.com/'++ // A URL source is claimed in PROCESSING and ingested in the background; the+ // backend enforces a single PROCESSING source per team, so a second concurrent+ // create would 409. We therefore exercise dispatch + refresh_interval in one+ // create rather than two.+ it('should dispatch source_type=url and persist refresh_interval', async () => {+ const name = generateUniqueKey('MCP URL Source')+ const result = await urlCreateTool.handler(context, {+ name,+ url: PUBLIC_TEST_URL,+ refresh_interval: '24h',+ })+ const source = parseToolResponse(result)++ expect(source.id).toBeTruthy()+ expect(source.name).toBe(name)+ expect(source.source_type).toBe('url')+ expect(source.refresh_interval).toBe('24h')+ createdSourceIds.push(source.id)+ })+ })++ describe('list', () => {+ const listTool = getToolByName('business-knowledge-sources-list')++ it('should return sources with filtered response fields', async () => {+ const result = await listTool.handler(context, {})+ const response = parseToolResponse(result)++ expect(response.results).toBeTruthy()+ expect(Array.isArray(response.results)).toBe(true)+ expect(response).toHaveProperty('_posthogUrl')+ expect(response._posthogUrl).toContain('/business-knowledge')++ if (response.results.length > 0) {+ const source = response.results[0]+ expect(source).toHaveProperty('id')+ expect(source).toHaveProperty('name')+ expect(source).toHaveProperty('source_type')+ expect(source).toHaveProperty('status')++ const unexpectedFields = ['documents', 'source_text', 'team']+ for (const field of unexpectedFields) {+ expect(source).not.toHaveProperty(field)+ }+ }+ })+ })+})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.jsondeleted file mode 100644index 915269637fac..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/business-knowledge-document-window-retrieve.json+++ /dev/null@@ -1,19 +0,0 @@-{- "$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"-}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 8ee9b061ba25..bae9e3e3caf0 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -746,9 +746,10 @@ describe('Tool Filtering - Feature Flags', () => {'dashboard-widgets','heatmaps-mcp','marketing-analytics-mcp',+ 'product-business-knowledge',]))- expect(flags).toHaveLength(14)+ expect(flags).toHaveLength(15)})// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries