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.

chore(mcp): remove mcp-sql-schema-discovery flag, roll out infoschema (#69666)

Georgiy Tarasova886c9b52884
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.py
index 932fedf11ed6..9578f063f827 100644
--- a/ee/hogai/eval/sandboxed/conftest.py
+++ b/ee/hogai/eval/sandboxed/conftest.py
@@ -552,10 +552,8 @@ def _mcp_server(_django_live_server, _sandbox_settings):
# here (no POSTHOG_ANALYTICS_* config), so every flag would resolve false.
# Force flag-gated behavior on for evals via the dev/test-only override seam
# (honored only when NODE_ENV is explicitly development/test — set above).
- # `mcp-sql-schema-discovery` routes warehouse/system-table schema discovery
- # through `system.information_schema.*` SQL instead of read-data-warehouse-schema
- # — see eval_system_table_search.py.
- "FEATURE_FLAG_OVERRIDES": json.dumps({"mcp-sql-schema-discovery": True}),
+ # No flags currently need forcing on.
+ "FEATURE_FLAG_OVERRIDES": json.dumps({}),
}
logger.info("Starting MCP server (Hono runtime) on port %d (API: %s)", MCP_PORT, api_url)
diff --git a/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py b/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py
index e524e645a4d7..c2dff7451e45 100644
--- a/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py
+++ b/ee/hogai/eval/sandboxed/data_warehouse/eval_information_schema.py
@@ -3,9 +3,8 @@
Each eval seeds a per-case team with hundreds of synthetic warehouse tables,
data-modeling views, and join relationships (``seed_warehouse_schema``), then grades
whether the agent uses ``system.information_schema`` to navigate the catalog at scale.
-The ``mcp-sql-schema-discovery`` flag is forced on in the harness, so discovery runs
-through ``execute-sql`` against ``system.information_schema.*`` and the dedicated
-``read-data-warehouse-schema`` tool is gated off.
+Schema discovery runs through ``execute-sql`` against ``system.information_schema.*``;
+there is no dedicated schema tool.
The cases are split into one eval function per capability so each Braintrust
experiment reports a clean, homogeneous scorecard (a single shared scorer list mixed
diff --git a/ee/hogai/eval/sandboxed/sql/scorers.py b/ee/hogai/eval/sandboxed/sql/scorers.py
index 469e4761b7c8..03db9f448732 100644
--- a/ee/hogai/eval/sandboxed/sql/scorers.py
+++ b/ee/hogai/eval/sandboxed/sql/scorers.py
@@ -47,8 +47,7 @@ def extract_last_execute_sql_call(output: dict[str, Any] | None) -> dict[str, st
"""Return the query and result from the most recent successful *answer* ``execute-sql`` call.
Schema discovery runs through ``execute-sql`` against
- ``system.information_schema.*`` (the ``mcp-sql-schema-discovery`` regime,
- forced on in the sandbox), so those discovery queries land in the same
+ ``system.information_schema.*``, so those discovery queries land in the same
``execute-sql`` call list as the real answer query. They are skipped here so
the judge grades the question's answer, not a column lookup the agent ran
afterward.
@@ -84,8 +83,7 @@ def _is_schema_discovery_query(query: Any) -> bool:
class AnswerQueryRan(Scorer):
"""Binary: did the agent run a real (non-discovery) ``execute-sql`` answer query?
- Under the ``mcp-sql-schema-discovery`` regime (forced on in the sandbox),
- schema discovery also runs through ``execute-sql`` against
+ Schema discovery also runs through ``execute-sql`` against
``system.information_schema.*``. So a plain "``execute-sql`` was called"
check passes even when the agent only inspected the schema and never
answered with SQL. This requires a successful ``execute-sql`` whose query
diff --git a/products/signals/skills/authoring-scouts/references/scout-patterns.md b/products/signals/skills/authoring-scouts/references/scout-patterns.md
index 612dd9200cdb..04d98591f5e2 100644
--- a/products/signals/skills/authoring-scouts/references/scout-patterns.md
+++ b/products/signals/skills/authoring-scouts/references/scout-patterns.md
@@ -18,12 +18,12 @@ This is a living reference — add a pattern when a genuinely new shape proves i
The single most useful thing to internalize: **a scout is not limited to PostHog analytics events.** It can watch anything the project can see, and the report / dedupe / memory contract is identical regardless of where the data comes from.
-| Source | How the scout reads it |
-| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| **Collected events** | `read-data-schema` to confirm the event + properties, then `query-*` tools or `execute-sql`. The common case. |
-| **The data warehouse** | `read-data-warehouse-schema` to confirm columns, then `execute-sql`. **Any source PostHog ingests becomes a queryable table** — see the warehouse-backed pattern below. |
-| **PostHog product entities** | dedicated list/get tools (insights, dashboards, surveys, error issues, experiments, flags) plus `execute-sql` over `system.*`. |
-| **External systems** | from inside the sandbox, when it runs with a TRUSTED network — a CLI tool, a public git repo, an HTTP API. See the external-tool pattern. |
+| Source | How the scout reads it |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Collected events** | `read-data-schema` to confirm the event + properties, then `query-*` tools or `execute-sql`. The common case. |
+| **The data warehouse** | `execute-sql` over `system.information_schema.*` to confirm columns, then `execute-sql`. **Any source PostHog ingests becomes a queryable table** — see the warehouse-backed pattern below. |
+| **PostHog product entities** | dedicated list/get tools (insights, dashboards, surveys, error issues, experiments, flags) plus `execute-sql` over `system.*`. |
+| **External systems** | from inside the sandbox, when it runs with a TRUSTED network — a CLI tool, a public git repo, an HTTP API. See the external-tool pattern. |
The warehouse row is the big unlock: once a Slack channel, a Stripe account, a CRM, a billing system, a support inbox, a social-listening feed, or an app database (via CDC) is synced into the warehouse, a scout queries it with `execute-sql` exactly like it queries events — and the watched surface need not be PostHog analytics at all.
@@ -107,7 +107,7 @@ Files P3 recommendations rather than P0–P2 anomalies.
The watched surface is not analytics data at all — it's whatever that upstream system produces.
- **Watched data:** one (or a few) warehouse tables.
- Always confirm columns with `read-data-warehouse-schema` first — column names are source-defined and often opaque.
+ Always confirm columns with `execute-sql` against `system.information_schema.columns` first — column names are source-defined and often opaque.
- **Discriminator — pre-classified vs derived, and know which you have:**
- **Pre-classified** — if the upstream tool already labels rows (a sentiment field, a category, a status, a priority), anchor on that.
It's a free, high-signal discriminator — e.g. a social-listening feed that ships a per-item sentiment.
diff --git a/products/signals/skills/signals-scout-general/references/discovery.md b/products/signals/skills/signals-scout-general/references/discovery.md
index e1814e136795..c86acfbf4d5c 100644
--- a/products/signals/skills/signals-scout-general/references/discovery.md
+++ b/products/signals/skills/signals-scout-general/references/discovery.md
@@ -70,7 +70,7 @@ directly when the breadth pass hints they might be present, one cheap read each:
- **Revenue** — revenue events in the taxonomy, or warehouse Stripe sources in the
profile.
- **Data warehouse** — the profile's `external_data_sources`; deeper structure via
- `read-data-warehouse-schema`.
+ `execute-sql` over `system.information_schema.*`.
When you hit a surface no tool seems to cover, that's worth a `mcp-gap:` scratchpad
note (see [conventions.md](conventions.md)) — a capability the fleet may want later.
diff --git a/products/warehouse_sources/skills/suggesting-data-imports/SKILL.md b/products/warehouse_sources/skills/suggesting-data-imports/SKILL.md
index edde27d7bf70..ecc47be36de1 100644
--- a/products/warehouse_sources/skills/suggesting-data-imports/SKILL.md
+++ b/products/warehouse_sources/skills/suggesting-data-imports/SKILL.md
@@ -38,7 +38,7 @@ Call `posthog:external-data-sources-list` to see existing sources. The data migh
If a source exists for the system they're asking about, call `posthog:external-data-schemas-list` to show the available tables. The data might be there but under a different name or prefix.
-Also call `posthog:read-data-warehouse-schema` to see all queryable tables — the data might already be available as a view or joined table.
+Also query `system.information_schema.tables` with `posthog:execute-sql` to see all queryable tables — the data might already be available as a view or joined table.
### 3. Identify the right source type
@@ -87,17 +87,17 @@ Common join patterns:
## Important notes
-- **Don't guess table names.** Always check `posthog:read-data-warehouse-schema` and `posthog:external-data-schemas-list` before saying data doesn't exist.
+- **Don't guess table names.** Always check `system.information_schema.tables` (via `posthog:execute-sql`) and `posthog:external-data-schemas-list` before saying data doesn't exist.
- **Check prefixes.** Imported tables are often prefixed (e.g. `stripe_charges` not `charges`). The user might not know the prefix.
- **Collect credentials securely.** Use `data-warehouse-source-connect-link` to hand the user a browser link — it opens a minimal connect page rendering the source's full connection form (OAuth or credentials, whichever the source offers) that stashes the details temporarily without creating the source. Afterwards pass `{"credential_id": <id>}` (discovered via `data-warehouse-stored-credentials-list`) to `data-warehouse-source-setup` — stored credentials are single-use and expire after 24 hours. Don't collect passwords or OAuth tokens in chat.
- **Not all systems are supported.** If the user's system isn't in the wizard list, suggest using Postgres/MySQL as a bridge if they can export to a database, or mention that custom sources can be requested.
-- **Connecting a source also documents it.** After the first sync, PostHog automatically generates semantic descriptions for the imported tables and columns (from the source database's own column comments where present, plus an LLM pass using the table relationships and the team's business context). Those descriptions surface in `posthog:read-data-warehouse-schema`, so once a source is connected the agent can reason about what each column means and how tables join — not just their names and types. Mention this when recommending an import: connecting the source is what makes the data answerable.
+- **Connecting a source also documents it.** After the first sync, PostHog automatically generates semantic descriptions for the imported tables and columns (from the source database's own column comments where present, plus an LLM pass using the table relationships and the team's business context). Those descriptions surface in `system.information_schema.columns` (query it with `posthog:execute-sql`), so once a source is connected the agent can reason about what each column means and how tables join — not just their names and types. Mention this when recommending an import: connecting the source is what makes the data answerable.
## Related tools
- `posthog:external-data-sources-list`: Check existing source connections
- `posthog:external-data-schemas-list`: Check what tables are already imported
-- `posthog:read-data-warehouse-schema`: See all queryable tables including views
+- `posthog:execute-sql` over `system.information_schema.*`: See all queryable tables including views
- `posthog:external-data-sources-wizard`: Get available source types
- `posthog:data-warehouse-source-connect-link`: Get a secure browser/OAuth link to collect credentials
- `posthog:data-warehouse-source-setup`: One-step create (validate, discover tables, apply sync defaults, create)
diff --git a/services/mcp/evals/benchmark/tasks.yaml b/services/mcp/evals/benchmark/tasks.yaml
index 668331bae13f..193aac781be1 100644
--- a/services/mcp/evals/benchmark/tasks.yaml
+++ b/services/mcp/evals/benchmark/tasks.yaml
@@ -57,9 +57,8 @@ tasks:
- id: warehouse-schema-tables
category: data-schema
intent: 'What tables are available in our data warehouse, and what columns do they have?'
- expected_tools: [read-data-warehouse-schema]
- acceptable_tools: [execute-sql]
- success_criteria: 'Enumerates warehouse tables with column details.'
+ expected_tools: [execute-sql]
+ success_criteria: 'Enumerates warehouse tables with column details via system.information_schema.'
# --- product-analytics ---------------------------------------------------
- id: trends-weekly-active-users
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4775afcb4d9f..05958c1fbf04 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7102,22 +7102,6 @@
"readOnlyHint": true
}
},
- "read-data-warehouse-schema": {
- "description": "Use this tool to retrieve the core data warehouse schemas for PostHog tables (events, groups, persons, sessions) and the available data warehouse tables, views, and system tables. Use this to understand the data model before writing HogQL queries.",
- "category": "Data schema",
- "feature": "data_schema",
- "summary": "Read core data warehouse schemas and table lists.",
- "title": "Read data warehouse schema",
- "required_scopes": ["warehouse_table:read", "warehouse_view:read"],
- "feature_flag": "mcp-sql-schema-discovery",
- "feature_flag_behavior": "disable",
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
"reminder-create": {
"description": "Create a reminder for yourself. Set organization (required) and optionally team to scope it to a project. Use a one-off reminder by setting scheduled_at (a future ISO 8601 time), or a recurring reminder by setting recurrence_interval (daily/weekly/monthly/yearly) OR cron_expression (5-field, max 4 fires/day). Set timezone to the user's IANA timezone so wall-clock times resolve correctly. Optionally attach a resource the reminder is about via resource_type + resource_id (e.g. a dashboard) — the notification will link to it. Reminders fire as in-app notifications when due. Proactively offer to create a reminder when the user mentions needing periodic checks, monitoring, recurring reviews, or follow-ups on a metric, dashboard, or task — reminders are how they get recurring in-app notifications without manual polling.",
"category": "Reminders",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 7b6b183e9734..d8d9b3632a63 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -620,22 +620,6 @@
"readOnlyHint": true
}
},
- "read-data-warehouse-schema": {
- "description": "Use this tool to retrieve the core data warehouse schemas for PostHog tables (events, groups, persons, sessions) and the available data warehouse tables, views, and system tables. Use this to understand the data model before writing HogQL queries.",
- "category": "Data schema",
- "feature": "data_schema",
- "summary": "Read core data warehouse schemas and table lists.",
- "title": "Read data warehouse schema",
- "required_scopes": ["warehouse_table:read", "warehouse_view:read"],
- "feature_flag": "mcp-sql-schema-discovery",
- "feature_flag_behavior": "disable",
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": true,
- "openWorldHint": true,
- "readOnlyHint": true
- }
- },
"workflows-enable": {
"description": "Enable / activate a draft workflow and start processing events. One-way door: a live workflow can't be edited over MCP (to change it you recreate it as a new draft), so test it first and get the user's explicit approval before invoking. Don't enable on your own initiative.",
"category": "Workflows",
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 953e96ff5d20..422762847777 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -683,11 +683,6 @@
},
"required": ["query"]
},
- "ReadDataWarehouseSchemaSchema": {
- "type": "object",
- "properties": {},
- "description": "No input required. Returns core data warehouse schemas."
- },
"SavedMetricsAttachSchema": {
"type": "array",
"items": {
diff --git a/services/mcp/src/hono/instructions.ts b/services/mcp/src/hono/instructions.ts
index 527cad5e863a..2ae707856810 100644
--- a/services/mcp/src/hono/instructions.ts
+++ b/services/mcp/src/hono/instructions.ts
@@ -2,17 +2,11 @@ import { RESOURCE_URI_META_KEY } from '@modelcontextprotocol/ext-apps/server'
import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'
import type { QueryToolInfo } from '@/lib/instructions'
-import {
- type InstructionsContext,
- InstructionsFormatter,
- schemaDiscoveryViaSqlEnabled,
-} from '@/lib/instructions-formatter'
-import type { EvaluatedFlags } from '@/lib/posthog/flags'
+import { type InstructionsContext, InstructionsFormatter } from '@/lib/instructions-formatter'
import { formatPrompt } from '@/lib/utils'
import { RENDER_UI_RESOURCE_URI } from '@/resources/ui-apps.generated'
import EXECUTE_SQL_PROMPT from '@/templates/execute-sql-prompt.md'
-import SCHEMA_DISCOVERY_INFOSCHEMA from '@/templates/sections/schema-discovery-infoschema.md'
-import SCHEMA_DISCOVERY_LEGACY from '@/templates/sections/schema-discovery-legacy.md'
+import SCHEMA_DISCOVERY from '@/templates/sections/schema-discovery.md'
import {
getRenderableToolNames,
makeRenderUiSchema,
@@ -130,13 +124,10 @@ export class InstructionsBuilder {
return this.guidelines
}
- formatExecuteSqlDescription(featureFlags?: EvaluatedFlags): string {
- const schemaDiscovery = schemaDiscoveryViaSqlEnabled(featureFlags)
- ? SCHEMA_DISCOVERY_INFOSCHEMA
- : SCHEMA_DISCOVERY_LEGACY
+ formatExecuteSqlDescription(): string {
return formatPrompt(EXECUTE_SQL_PROMPT, {
guidelines: this.guidelines.trim(),
- schema_discovery: schemaDiscovery.trim(),
+ schema_discovery: SCHEMA_DISCOVERY.trim(),
})
}
}
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 7e024a892aef..391691e03142 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -11,7 +11,6 @@ import {
} from '@/lib/posthog/flags'
import type { RequestProperties } from '@/lib/request-properties'
import type { McpMode } from '@/lib/utils'
-import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'
import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'
import type { Context, Tool, Env, State, ZodObjectAny } from '@/tools/types'
@@ -106,12 +105,7 @@ export class RequestStateResolver {
cachedProjectId = (await reqCtx.tokenCache.get('projectId')) ?? undefined
}
- const toolFlagKeys = getRequiredFeatureFlags()
- // `mcp-sql-schema-discovery` now gates the read-data-warehouse-schema tool, so
- // it already arrives via `getRequiredFeatureFlags()`; keep it listed (and dedupe)
- // since the instructions layer also reads it for SQL discovery steering — neither
- // concern should depend on the other's wiring.
- const allFlagKeys = [...new Set([...toolFlagKeys, SQL_SCHEMA_DISCOVERY_FEATURE_FLAG])]
+ const allFlagKeys = [...new Set(getRequiredFeatureFlags())]
const flagAnalyticsContext = await reqCtx.safelyGetAnalyticsContext(context)
const flagGroups = flagAnalyticsContext ? buildMCPAnalyticsGroups(flagAnalyticsContext) : undefined
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index b1a4de0967e6..a457ba8cb45a 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -87,7 +87,7 @@ export class ToolExecutor {
if (entry.name === EXECUTE_SQL_TOOL_NAME) {
return {
...entry,
- description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),
+ description: this.instructionsBuilder.formatExecuteSqlDescription(),
}
}
return entry
@@ -392,13 +392,13 @@ export class ToolExecutor {
const clientContext = getEffectiveMCPClientContext(state.requestContext, state.sessionContext)
// CLI `info execute-sql` returns the tool's static description from the catalog.
- // Override it with the same flag-aware prompt tools-mode advertises, so the
- // information_schema steering (or its absence) matches across both modes.
+ // Override it with the same prompt tools-mode advertises, so the
+ // information_schema schema-discovery steering matches across both modes.
const execTools = state.allTools.map((tool) =>
tool.name === EXECUTE_SQL_TOOL_NAME
? {
...tool,
- description: this.instructionsBuilder.formatExecuteSqlDescription(state.toolFeatureFlags),
+ description: this.instructionsBuilder.formatExecuteSqlDescription(),
}
: tool
)
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index fdfbabc99255..920df50e645b 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -18,8 +18,7 @@ import CLI_RENDERING from '@/templates/sections/cli-rendering.md'
import CLI_SCHEMA_DRILLDOWN from '@/templates/sections/cli-schema-drilldown.md'
import CLI_SYNTAX from '@/templates/sections/cli-syntax.md'
import COMPACT_INSTRUCTIONS from '@/templates/sections/compact-instructions.md'
-import ENTITY_SCHEMA_DISCOVERY_INFOSCHEMA from '@/templates/sections/entity-schema-discovery-infoschema.md'
-import ENTITY_SCHEMA_DISCOVERY_LEGACY from '@/templates/sections/entity-schema-discovery-legacy.md'
+import ENTITY_SCHEMA_DISCOVERY from '@/templates/sections/entity-schema-discovery.md'
import ENV_CONTEXT from '@/templates/sections/env-context.md'
import EXAMPLES from '@/templates/sections/examples.md'
import EXEC_TOOL_BLURB from '@/templates/sections/exec-tool-blurb.md'
@@ -27,7 +26,6 @@ import RETRIEVING_DATA from '@/templates/sections/retrieving-data.md'
import SCHEMA_WORKFLOW from '@/templates/sections/schema-workflow.md'
import TOOL_SEARCH from '@/templates/sections/tool-search.md'
import URL_PATTERNS from '@/templates/sections/url-patterns.md'
-import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'
export interface InstructionsContext {
guidelines: string
@@ -44,14 +42,6 @@ export interface InstructionsContext {
renderUiEnabled?: boolean | undefined
}
-/** Whether schema discovery should be routed through `system.information_schema.*`
- * SQL (the `mcp-sql-schema-discovery` flag) instead of the `read-data-warehouse-schema`
- * tool. Prompt-only: when on, no instruction names the tool, so the agent discovers
- * tables/columns/relationships with SQL. The tool itself stays advertised either way. */
-export function schemaDiscoveryViaSqlEnabled(featureFlags: EvaluatedFlags | undefined): boolean {
- return featureFlags?.[SQL_SCHEMA_DISCOVERY_FEATURE_FLAG] === true
-}
-
/**
* Composes MCP instruction prompts for the two client modes (tools-mode and
* single-exec). Each mode declares an ordered list of subprompts under
@@ -146,16 +136,13 @@ export class InstructionsFormatter {
// `{query_tools}` only appears in non-compact sections (the exec command
// reference and tools-mode instructions); compact mode surfaces queries
// via the single `query` tool domain instead.
- const entitySchemaDiscovery = schemaDiscoveryViaSqlEnabled(ctx.featureFlags)
- ? ENTITY_SCHEMA_DISCOVERY_INFOSCHEMA
- : ENTITY_SCHEMA_DISCOVERY_LEGACY
const vars = {
guidelines: ctx.guidelines.trim(),
defined_groups: buildDefinedGroupsBlock(ctx.groupTypes),
metadata: ctx.metadata?.trim() ?? '',
tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',
query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',
- entity_schema_discovery: entitySchemaDiscovery.trim(),
+ entity_schema_discovery: ENTITY_SCHEMA_DISCOVERY.trim(),
}
const body = sections
.map((s) => s.trim())
diff --git a/services/mcp/src/lib/posthog/flags.ts b/services/mcp/src/lib/posthog/flags.ts
index d77192bc692d..03d31cb164db 100644
--- a/services/mcp/src/lib/posthog/flags.ts
+++ b/services/mcp/src/lib/posthog/flags.ts
@@ -42,7 +42,7 @@ export async function evaluateFeatureFlags(
}
// Env var (or Cloudflare var) holding a JSON object of flag overrides, e.g.
-// `FEATURE_FLAG_OVERRIDES={"mcp-sql-schema-discovery": true, "some-flag": "variant-a"}`.
+// `FEATURE_FLAG_OVERRIDES={"dev-forced-flag": true, "some-flag": "variant-a"}`.
const FEATURE_FLAG_OVERRIDES_ENV = 'FEATURE_FLAG_OVERRIDES'
/** Parse a JSON object of flag overrides. Non-object JSON, parse errors, and
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 645b44dfbce6..8b3bc76054d8 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -368,10 +368,6 @@ export const ExecuteSQLSchema = z.object({
),
})
-export const ReadDataWarehouseSchemaSchema = z
- .object({})
- .describe('No input required. Returns core data warehouse schemas.')
-
const ReadEventsQuerySchema = z.object({
kind: z.literal('events'),
limit: z.number().int().min(1).max(500).default(500).optional().describe('Number of events to return per page.'),
diff --git a/services/mcp/src/templates/sections/entity-schema-discovery-legacy.md b/services/mcp/src/templates/sections/entity-schema-discovery-legacy.md
deleted file mode 100644
index 25023e63347c..000000000000
--- a/services/mcp/src/templates/sections/entity-schema-discovery-legacy.md
+++ /dev/null
@@ -1,16 +0,0 @@
-#### Searching for existing entities
-
-"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.
-
-Required order on every run, no shortcuts:
-
-1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.
-2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.
-3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.
-4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.
-
-<bad-example>
-User: rename / find / list … (any `system.*` question)
-Assistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]
-WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.
-</bad-example>
diff --git a/services/mcp/src/templates/sections/entity-schema-discovery-infoschema.md b/services/mcp/src/templates/sections/entity-schema-discovery.md
similarity index 100%
rename from services/mcp/src/templates/sections/entity-schema-discovery-infoschema.md
rename to services/mcp/src/templates/sections/entity-schema-discovery.md
diff --git a/services/mcp/src/templates/sections/schema-discovery-legacy.md b/services/mcp/src/templates/sections/schema-discovery-legacy.md
deleted file mode 100644
index a05192150680..000000000000
--- a/services/mcp/src/templates/sections/schema-discovery-legacy.md
+++ /dev/null
@@ -1,12 +0,0 @@
-### Discovery workflow (mandatory)
-
-1. **Warehouse schema** — call `read-data-warehouse-schema` to verify tables, views, and columns. Do not guess names. **This applies to `system.*` tables too** (`system.insights`, `system.dashboards`, `system.cohorts`, …); their column sets differ per entity and drift over time. For a specific custom warehouse table, inspect its columns with:
-
- ```sql
- SELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'
- ```
-
-2. **Event taxonomy** — call `read-data-schema` to verify events, properties, and property values. Do not rely on training data or PostHog defaults.
-3. **Write the SQL** only after steps 1 and 2 confirm the data exists, using the verified table and column names.
-
-If the required events, properties, or tables do not exist, say so — do not run queries that will return empty results.
diff --git a/services/mcp/src/templates/sections/schema-discovery-infoschema.md b/services/mcp/src/templates/sections/schema-discovery.md
similarity index 100%
rename from services/mcp/src/templates/sections/schema-discovery-infoschema.md
rename to services/mcp/src/templates/sections/schema-discovery.md
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 39cb2737467c..3948169e068d 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -140,8 +140,7 @@ export function createExecInnerToolCallResolver(
// guidance. A redirect only fires when the tool is absent, so an entry for a
// conditionally-gated tool is inert whenever that tool is registered.
const DEPRECATED_TOOL_REDIRECTS: Record<string, (allTools: Tool<ZodObjectAny>[]) => string> = {
- // Disabled while `mcp-sql-schema-discovery` is on; the SQL information_schema
- // path replaces it. See readDataWarehouseSchema.ts for the flag/TODO.
+ // Removed in favor of SQL-based schema discovery via `system.information_schema.*`.
'read-data-warehouse-schema': () =>
'Tool "read-data-warehouse-schema" was removed in favor of SQL-based schema discovery. Use "execute-sql" against `system.information_schema.*` (`tables`, `columns`, `relationships`, `data_types`) — it scales to large catalogs and supports filtering/search (e.g. `WHERE description ILIKE \'%...%\'`). Consult the `querying-posthog-data` skill for patterns.',
'entity-search': () =>
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index 112dd61b9a78..b82a6aa583f8 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -30,7 +30,6 @@ import {
externalDataSourcesPreview,
externalDataSyncLogs,
readDataSchema,
- readDataWarehouseSchema,
} from './posthogAiTools'
// Projects
import getProjects from './projects/getProjects'
@@ -93,7 +92,6 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// PostHog AI tools
[EXECUTE_SQL_TOOL_NAME]: executeSql,
'read-data-schema': readDataSchema,
- 'read-data-warehouse-schema': readDataWarehouseSchema,
// Replay
'session-recording-summarize': sessionRecordingSummarize,
diff --git a/services/mcp/src/tools/posthogAiTools/index.ts b/services/mcp/src/tools/posthogAiTools/index.ts
index 406e768c1091..368319627448 100644
--- a/services/mcp/src/tools/posthogAiTools/index.ts
+++ b/services/mcp/src/tools/posthogAiTools/index.ts
@@ -4,4 +4,3 @@ export { default as externalDataSourcesJobs } from './externalDataSourcesJobs'
export { default as externalDataSourcesPreview } from './externalDataSourcesPreview'
export { default as externalDataSyncLogs } from './externalDataSyncLogs'
export { default as readDataSchema } from './readDataSchema'
-export { default as readDataWarehouseSchema } from './readDataWarehouseSchema'
diff --git a/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts b/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts
deleted file mode 100644
index b608ea1cebe8..000000000000
--- a/services/mcp/src/tools/posthogAiTools/readDataWarehouseSchema.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { ReadDataWarehouseSchemaSchema } from '@/schema/tool-inputs'
-import type { Context, ToolBase } from '@/tools/types'
-
-import { invokeMcpTool } from './invokeTool'
-
-// Flag that routes schema discovery through `system.information_schema.*` SQL. When it
-// is on, two things happen: the discovery instructions steer the agent toward
-// `execute-sql` against `system.information_schema.*`, and this tool is gated OUT of the
-// catalog (via `feature_flag_behavior: "disable"` in tool-definitions.json) so the SQL
-// path is the only one. An agent that still calls it by name gets the redirect in
-// `DEPRECATED_TOOL_REDIRECTS`. Off-flag, the tool stays registered and callable.
-//
-// TODO: once `mcp-sql-schema-discovery` is rolled out to 100%, delete this tool
-// entirely — the `system.information_schema.*` SQL path fully replaces it — and retire
-// this flag along with the legacy (non-infoschema) discovery prompt sections.
-export const SQL_SCHEMA_DISCOVERY_FEATURE_FLAG = 'mcp-sql-schema-discovery'
-
-// The advertised name of this tool.
-export const READ_DATA_WAREHOUSE_SCHEMA_TOOL_NAME = 'read-data-warehouse-schema'
-
-const schema = ReadDataWarehouseSchemaSchema
-
-export const readDataWarehouseSchemaHandler: ToolBase<typeof schema, string>['handler'] = async (context: Context) => {
- const result = await invokeMcpTool(context, 'read_data_warehouse_schema', {
- query: { kind: 'data_warehouse_schema' },
- })
-
- if (!result.success) {
- throw new Error(result.content)
- }
-
- return result.content
-}
-
-const tool = (): ToolBase<typeof schema, string> => ({
- name: READ_DATA_WAREHOUSE_SCHEMA_TOOL_NAME,
- schema,
- handler: readDataWarehouseSchemaHandler,
-})
-
-export default tool
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index e028f304ee9d..21b1c48738f1 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -70,7 +70,7 @@ vi.mock('@/hono/request-context', () => {
import type { RedisLike } from '@/hono/cache/RedisCache'
import { RequestStateResolver } from '@/hono/request-state-resolver'
-import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'
+import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'
import type { RequestProperties } from '@/lib/request-properties'
import type { Env } from '@/tools/types'
@@ -96,13 +96,6 @@ function makeResolver(): RequestStateResolver {
return new RequestStateResolver(catalog as any, {} as RedisLike, {} as Env)
}
-function makeResolverWithTools(toolNames: string[]): RequestStateResolver {
- const catalog = {
- getFilteredTools: vi.fn(() => toolNames.map((name) => ({ name }))),
- }
- return new RequestStateResolver(catalog as any, {} as RedisLike, {} as Env)
-}
-
describe('RequestStateResolver MCP client contexts', () => {
beforeEach(() => {
mockSessionStore.clear()
@@ -305,11 +298,11 @@ describe('RequestStateResolver MCP client contexts', () => {
it('honors a dev/test flag override even when evaluation returns nothing', async () => {
// Evaluation stays empty (analytics client disabled, as in local dev/evals);
// the override seam is what flips a tool flag on so it reaches the tool layer.
- vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ 'mcp-sql-schema-discovery': true })
+ vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ 'dev-forced-flag': true })
const props = makeProps({ mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' })
const result = await makeResolver().resolve(props)
- expect(result.toolFeatureFlags?.['mcp-sql-schema-discovery']).toBe(true)
+ expect(result.toolFeatureFlags?.['dev-forced-flag']).toBe(true)
})
it('captures consumer from a later request when initialize omitted the header', async () => {
@@ -334,25 +327,3 @@ describe('RequestStateResolver MCP client contexts', () => {
expect(mockSessionStore.get('mcpConsumer')).toBe('posthog-code')
})
})
-
-describe('RequestStateResolver SQL schema-discovery flag', () => {
- beforeEach(() => {
- mockSessionStore.clear()
- mockTokenStore.clear()
- vi.mocked(evaluateFeatureFlags).mockResolvedValue({})
- })
-
- // The flag steers discovery instructions toward SQL but is prompt-only — it must NOT
- // remove read-data-warehouse-schema from the tool set. Guards against re-introducing
- // tool gating here; the tool stays advertised/callable whether the flag is on or off.
- it.each([true, false])('keeps read-data-warehouse-schema available when the flag is %s', async (flagOn) => {
- vi.mocked(evaluateFeatureFlags).mockResolvedValueOnce({ 'mcp-sql-schema-discovery': flagOn })
- const resolver = makeResolverWithTools(['read-data-warehouse-schema', 'execute-sql'])
-
- const result = await resolver.resolve(makeProps())
-
- const names = result.allTools.map((t) => t.name)
- expect(names).toContain('read-data-warehouse-schema')
- expect(names).toContain('execute-sql')
- })
-})
diff --git a/services/mcp/tests/tools/dataWarehouseSchema.integration.test.ts b/services/mcp/tests/tools/dataWarehouseSchema.integration.test.ts
deleted file mode 100644
index 61f9c69c3254..000000000000
--- a/services/mcp/tests/tools/dataWarehouseSchema.integration.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { afterEach, beforeAll, describe, expect, it } from 'vitest'
-
-import {
- type CreatedResources,
- TEST_ORG_ID,
- TEST_PROJECT_ID,
- cleanupResources,
- createTestClient,
- createTestContext,
- setActiveProjectAndOrg,
- validateEnvironmentVariables,
-} from '@/shared/test-utils'
-import readDataWarehouseSchemaTool from '@/tools/posthogAiTools/readDataWarehouseSchema'
-import type { Context } from '@/tools/types'
-
-describe('read-data-warehouse-schema', { concurrent: false }, () => {
- let context: Context
- const createdResources: CreatedResources = {
- featureFlags: [],
- insights: [],
- dashboards: [],
- surveys: [],
- actions: [],
- cohorts: [],
- }
-
- beforeAll(async () => {
- validateEnvironmentVariables()
- const client = createTestClient()
- context = createTestContext(client)
- await setActiveProjectAndOrg(context, TEST_PROJECT_ID!, TEST_ORG_ID!)
- })
-
- afterEach(async () => {
- await cleanupResources(context.api, TEST_PROJECT_ID!, createdResources)
- })
-
- const tool = readDataWarehouseSchemaTool()
-
- it('should return core PostHog table schemas', async () => {
- const result = await tool.handler(context, {})
-
- expect(typeof result).toBe('string')
- expect(result).toContain('# Core PostHog tables')
- expect(result).toContain('## Table `events`')
- expect(result).toContain('## Table `persons`')
- })
-
- it('should include sessions and groups tables', async () => {
- const result = await tool.handler(context, {})
-
- expect(result).toContain('sessions')
- expect(result).toContain('groups')
- })
-})
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
deleted file mode 100644
index f53202e0ac3d..000000000000
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "name": "exec",
- "title": "PostHog analytics, dashboards, insights, feature flags & more",
- "description": "### Using the `posthog` tool\n\nPostHog: dashboards, insights, funnels, SQL, experiments, surveys, replay, error tracking, flags.\n\nPass CLI-style commands in the `command` parameter for all PostHog interactions.\n\n**MANDATORY — HARD REQUIREMENTS**\n\n1. Discover tools first with `search` or `tools`.\n2. Run `info <tool_name>` BEFORE every `call <tool_name> <json>`.\n\nBLOCKING, like reading a file before editing it. Tool names and schemas are NOT predictable — never assume.\n\n**Commands (in order):**\n\n```text\n# 1. Discover (preferred: focused regex over name/title/description)\nposthog:exec({ \"command\": \"search <regex>\" })\nposthog:exec({ \"command\": \"tools\" }) # fallback: list all\n\n# 2. Check description + top-level schema (REQUIRED before call)\nposthog:exec({ \"command\": \"info <tool_name>\" })\n\n# 3. Drill into complex fields — REQUIRED for any field with a `hint`\nposthog:exec({ \"command\": \"schema <tool_name> <field_path>\" })\n\n# 4. Call the tool\nposthog:exec({ \"command\": \"call <tool_name> <json_input>\" })\nposthog:exec({ \"command\": \"call --json <tool_name> <json_input>\" })\n```\n\n**Schema drill-down:**\n\n- `info` returns the full schema if it fits the token budget; otherwise it auto-summarizes (names, types, required, enums, defaults) and attaches `hint` entries pointing to `schema <tool> <path>` for complex fields.\n- `schema <tool>` (no path) returns the summarized top-level schema.\n- `schema <tool> <path>` resolves a dot path, descending through:\n - object `properties` (e.g. `query.source`)\n - array `items` — numeric segments step into items (`events.0.properties`), or jump to a property on the item type (`events.id`)\n - `anyOf`/`oneOf` — numeric segment picks a variant by index, or a property name matches any object variant defining it\n- Oversized sub-schemas are also summarized with a `note` to drill further.\n- Unknown paths return an error listing available child paths.\n\n**Not supported:**\n\n- `search` matches tool metadata only, not input schemas.\n- No pattern-based field projection — drill one path at a time.",
- "annotations": {
- "destructiveHint": false,
- "idempotentHint": false,
- "openWorldHint": true,
- "readOnlyHint": false
- },
- "scopes": [],
- "inputSchema": {
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "type": "object",
- "properties": {
- "command": {
- "type": "string",
- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- agent\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch-export\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox-reports\n- inbox-source-configs\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
- }
- },
- "required": ["command"]
- }
-}
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index 12c73ac6f275..ac97413c7657 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -220,17 +220,16 @@ When you do use `execute-sql`, run `info execute-sql` first for the full discove
"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.
-Required order on every run, no shortcuts:
+Required order on every run, no shortcuts — schema first, every run:
-1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.
-2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.
-3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.
-4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.
+1. Confirm the table's columns with an `execute-sql` against `system.information_schema.columns`, e.g. `SELECT column_name, data_type, description FROM system.information_schema.columns WHERE table_name = 'system.insights'`. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — query the schema.
+2. `execute-sql` against `system.*` — uses only columns confirmed in step 1.
+3. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.
<bad-example>
User: rename / find / list … (any `system.*` question)
-Assistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]
-WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.
+Assistant: [Calls `execute-sql` against `system.insights` without first confirming its columns via `system.information_schema.columns` — OR checks the schema partway through, only after several `execute-sql` calls thrashed]
+WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against a `system.*` entity table MUST be preceded by an `execute-sql` against `system.information_schema.columns` for that table in the same run. Skipping or postponing the schema check is a hard violation.
</bad-example>
#### Available insight query tools
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 48d345ebe2de..e05ebf17c464 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -84,17 +84,16 @@ When you do use `execute-sql`, run `info execute-sql` first for the full discove
"find / which / do we have / what's our X chart" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.
-Required order on every run, no shortcuts:
+Required order on every run, no shortcuts — schema first, every run:
-1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.
-2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.
-3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.
-4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.
+1. Confirm the table's columns with an `execute-sql` against `system.information_schema.columns`, e.g. `SELECT column_name, data_type, description FROM system.information_schema.columns WHERE table_name = 'system.insights'`. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — query the schema.
+2. `execute-sql` against `system.*` — uses only columns confirmed in step 1.
+3. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.
<bad-example>
User: rename / find / list … (any `system.*` question)
-Assistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]
-WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.
+Assistant: [Calls `execute-sql` against `system.insights` without first confirming its columns via `system.information_schema.columns` — OR checks the schema partway through, only after several `execute-sql` calls thrashed]
+WRONG — the rule is "schema first, every run, no shortcuts." Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against a `system.*` entity table MUST be preceded by an `execute-sql` against `system.information_schema.columns` for that table in the same run. Skipping or postponing the schema check is a hard violation.
</bad-example>
#### Available insight query tools
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-warehouse-schema.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-warehouse-schema.json
deleted file mode 100644
index 1aa70955ef87..000000000000
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/read-data-warehouse-schema.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "description": "No input required. Returns core data warehouse schemas.",
- "properties": {},
- "type": "object"
-}
diff --git a/services/mcp/tests/unit/feature-flag-overrides.test.ts b/services/mcp/tests/unit/feature-flag-overrides.test.ts
index aeeb076d0583..a2845ddfdfaf 100644
--- a/services/mcp/tests/unit/feature-flag-overrides.test.ts
+++ b/services/mcp/tests/unit/feature-flag-overrides.test.ts
@@ -21,14 +21,14 @@ describe('resolveFeatureFlagOverrides', () => {
})
it('parses the env JSON object with boolean and variant values', () => {
- process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-sql-schema-discovery': true, 'some-flag': 'variant-a' })
- expect(resolveFeatureFlagOverrides()).toEqual({ 'mcp-sql-schema-discovery': true, 'some-flag': 'variant-a' })
+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'dev-forced-flag': true, 'some-flag': 'variant-a' })
+ expect(resolveFeatureFlagOverrides()).toEqual({ 'dev-forced-flag': true, 'some-flag': 'variant-a' })
})
it('lets a per-request override win over the env var', () => {
- process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-sql-schema-discovery': false })
- expect(resolveFeatureFlagOverrides(JSON.stringify({ 'mcp-sql-schema-discovery': true }))).toEqual({
- 'mcp-sql-schema-discovery': true,
+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'dev-forced-flag': false })
+ expect(resolveFeatureFlagOverrides(JSON.stringify({ 'dev-forced-flag': true }))).toEqual({
+ 'dev-forced-flag': true,
})
})
@@ -40,13 +40,13 @@ describe('resolveFeatureFlagOverrides', () => {
it('is a no-op in production, even with overrides set', () => {
process.env.NODE_ENV = 'production'
- process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-sql-schema-discovery': true })
+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'dev-forced-flag': true })
expect(resolveFeatureFlagOverrides(JSON.stringify({ x: true }))).toEqual({})
})
it('fails closed when NODE_ENV is unset, even with overrides set', () => {
delete process.env.NODE_ENV
- process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'mcp-sql-schema-discovery': true })
+ process.env.FEATURE_FLAG_OVERRIDES = JSON.stringify({ 'dev-forced-flag': true })
expect(resolveFeatureFlagOverrides(JSON.stringify({ x: true }))).toEqual({})
})
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index 370c9f0dd6a1..9a494989b8c5 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -60,15 +60,15 @@ describe('buildToolDomainsBlock', () => {
it('keeps a singleton tool whole but collapses siblings to a shared root', () => {
const tools = [
{ name: 'execute-sql', category: 'SQL' },
- { name: 'read-data-schema', category: 'Data schema' },
- { name: 'read-data-warehouse-schema', category: 'Data schema' },
+ { name: 'external-data-schemas-list', category: 'Data warehouse' },
+ { name: 'external-data-sources-list', category: 'Data warehouse' },
]
const result = buildToolDomainsBlock(tools)
expect(result).toContain('- execute-sql')
- // read-data-* siblings collapse to their shared prefix, not listed verbatim
- expect(result).toContain('- read-data')
- expect(result).not.toContain('- read-data-schema')
- expect(result).not.toContain('- read-data-warehouse-schema')
+ // external-data-* siblings collapse to their shared prefix, not listed verbatim
+ expect(result).toContain('- external-data')
+ expect(result).not.toContain('- external-data-schemas-list')
+ expect(result).not.toContain('- external-data-sources-list')
})
it('splits an oversized family into sub-family roots, one level deep', () => {
diff --git a/services/mcp/tests/unit/schema-discovery-flag.test.ts b/services/mcp/tests/unit/schema-discovery-flag.test.ts
deleted file mode 100644
index bb2697ae8b37..000000000000
--- a/services/mcp/tests/unit/schema-discovery-flag.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, it } from 'vitest'
-
-import { InstructionsBuilder } from '@/hono/instructions'
-import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructions-formatter'
-import { SQL_SCHEMA_DISCOVERY_FEATURE_FLAG } from '@/tools/posthogAiTools/readDataWarehouseSchema'
-
-// The `mcp-sql-schema-discovery` flag is prompt-only: when on, no instruction names
-// `read-data-warehouse-schema` and discovery is steered through
-// `system.information_schema.*`. When off, the legacy tool-based discovery stays.
-describe('mcp-sql-schema-discovery flag gating', () => {
- const ctx: InstructionsContext = {
- guidelines: 'some guidelines',
- tools: [
- { name: 'execute-sql', category: 'SQL' },
- { name: 'read-data-warehouse-schema', category: 'Data schema' },
- ],
- }
-
- describe('execute-sql description (InstructionsBuilder.formatExecuteSqlDescription)', () => {
- const builder = new InstructionsBuilder('some guidelines')
-
- it.each([undefined, {}, { [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: false }])(
- 'names read-data-warehouse-schema when the flag is off (%o)',
- (featureFlags) => {
- const result = builder.formatExecuteSqlDescription(featureFlags)
- expect(result).toContain('read-data-warehouse-schema')
- expect(result).not.toContain('system.information_schema')
- }
- )
-
- it('routes through system.information_schema and never names the tool when the flag is on', () => {
- const result = builder.formatExecuteSqlDescription({ [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: true })
- expect(result).toContain('system.information_schema')
- expect(result).not.toContain('read-data-warehouse-schema')
- })
- })
-
- describe('entity discovery section (InstructionsFormatter)', () => {
- const formatter = new InstructionsFormatter()
- const renderBothModes = (c: InstructionsContext): string[] => [
- formatter.buildToolsInstructions(c),
- formatter.buildExecCommandReference(c, { stripEnvContext: false }),
- ]
-
- it('names read-data-warehouse-schema in both modes when the flag is off', () => {
- const [toolsMode, cliMode] = renderBothModes(ctx)
- expect(toolsMode).toContain('read-data-warehouse-schema')
- expect(toolsMode).not.toContain('system.information_schema')
- expect(cliMode).toContain('read-data-warehouse-schema')
- expect(cliMode).not.toContain('system.information_schema')
- })
-
- it('routes through system.information_schema in both modes when the flag is on', () => {
- const [toolsMode, cliMode] = renderBothModes({
- ...ctx,
- featureFlags: { [SQL_SCHEMA_DISCOVERY_FEATURE_FLAG]: true },
- })
- expect(toolsMode).toContain('system.information_schema')
- expect(toolsMode).not.toContain('read-data-warehouse-schema')
- expect(cliMode).toContain('system.information_schema')
- expect(cliMode).not.toContain('read-data-warehouse-schema')
- })
- })
-})
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index bda1713c0fab..78821a1b5ab9 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -190,26 +190,6 @@ describe('Tool Filtering - Tools Allowlist', () => {
expect(toolsWithoutFlags).not.toContain('agent-feedback')
})
- it('should hide read-data-warehouse-schema when mcp-sql-schema-discovery is on (disable gate)', () => {
- // SQL information_schema discovery replaces the tool while the flag is on.
- const withFlagOn = getToolsForFeatures({
- tools: ['read-data-warehouse-schema'],
- featureFlags: { 'mcp-sql-schema-discovery': true },
- })
- expect(withFlagOn).not.toContain('read-data-warehouse-schema')
-
- // Off / unevaluated → the tool stays available (disable default is "show").
- expect(getToolsForFeatures({ tools: ['read-data-warehouse-schema'] })).toContain(
- 'read-data-warehouse-schema'
- )
- expect(
- getToolsForFeatures({
- tools: ['read-data-warehouse-schema'],
- featureFlags: { 'mcp-sql-schema-discovery': false },
- })
- ).toContain('read-data-warehouse-schema')
- })
-
it('should union with features (OR) when both are provided', () => {
const tools = getToolsForFeatures({ features: ['flags'], tools: ['dashboard-get'] })
@@ -776,12 +756,11 @@ describe('Tool Filtering - Feature Flags', () => {
'field-notes',
'mcp-analytics',
'metrics',
- 'mcp-sql-schema-discovery',
'endpoints-ai-materialization-fix',
'engineering-analytics',
])
)
- expect(flags).toHaveLength(22)
+ expect(flags).toHaveLength(21)
})
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries