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 dead code and correct stale mcp docs (#110159)

Jake Ruth76dd6b4174cd
diff --git a/.agents/skills/implementing-mcp-ui-apps/SKILL.md b/.agents/skills/implementing-mcp-ui-apps/SKILL.md
index 58d52ae353d3..01b7b21c8b63 100644
--- a/.agents/skills/implementing-mcp-ui-apps/SKILL.md
+++ b/.agents/skills/implementing-mcp-ui-apps/SKILL.md
@@ -6,7 +6,7 @@ description: 'Guide for adding MCP UI apps — interactive visualizations that r
# Implementing MCP UI apps
MCP UI apps are interactive React visualizations that render alongside tool results
-in MCP clients (e.g. Claude Desktop). They're built with the Mosaic component library
+in MCP clients (e.g. Claude Desktop). They're built with the Quill component library
and served via Cloudflare Workers Static Assets.
Full reference: [services/mcp/CONTRIBUTING.md](../../../services/mcp/CONTRIBUTING.md).
@@ -39,7 +39,7 @@ are shown as plain text/JSON in the chat.
products/{product}/mcp/
apps/ # React view components (you write these)
EntityView.tsx # Detail view
- EntityListView.tsx # List view (uses ListDetailView from Mosaic)
+ EntityListView.tsx # List view (uses ListDetailView from @posthog/mcp-ui)
index.ts # Barrel exports
tools.yaml # YAML config: ui_apps + tools
@@ -87,7 +87,7 @@ export function MyEntityView({ data }: { data: MyEntityData }): ReactElement {
}
```
-**List view** — uses `ListDetailView` from Mosaic for the list-to-detail state machine:
+**List view** — uses `ListDetailView` from `@posthog/mcp-ui` for the list-to-detail state machine:
```tsx
import { type ReactElement, type ReactNode } from 'react'
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 06487c405c6c..8ecf7e7a7906 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -56,24 +56,9 @@ For lookup tools, return an explicit normal result when absence is an expected a
checking whether an event's session has a recording). Keep invalid inputs, permission failures, and
server failures as tool errors so MCP Analytics measures genuine failures rather than routine misses.
-## Two MCP server versions
+## SQL-first data retrieval
-Clients must support two main capabilities: MCPs and skills.
-MCP support is widespread; however, skills support is still very early
-and mostly coding agents support them.
-To mitigate this, the MCP server ships two versions controlled via the
-`x-posthog-mcp-version: <version_number>` header.
-
-### Legacy MCP (v1)
-
-For clients that don't support skills.
-Exposes the full set of CRUD tools with simple instructions (list, read, create, update, delete).
-
-Primarily oriented toward vibe-coding web tools.
-
-### SQL-first MCP for clients supporting skills (v2)
-
-v2 instructs the agent to read data through a unified HogQL interface
+The MCP server instructs the agent to read data through a unified HogQL interface
(list and get tools are generally excluded),
which unlocks flexibility in data retrieval, search, and manipulation.
Additionally, the consumer has access to a skill that provides schema references and example patterns,
@@ -163,8 +148,6 @@ API scopes and billing access checks still apply.
System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.
Each table must include a `team_id` column for data isolation.
-Use `mcp_version: 1/2` to control availability of retrieval tools in v2 of the MCP.
-
Example from the codebase:
```python
@@ -307,7 +290,6 @@ Product teams own their definitions and control which operations are exposed as
destructive: false
idempotent: true
# --- optional: ---
- mcp_version: 2 # 2 for create/update/delete operations or not available through SQL for retrieval, 1 for read/list if available via HogQL
title: List things # human-friendly title (used in UI)
description: > # instructions for the LLM
Human-friendly description for the LLM.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index feb153be6e75..713df6231c69 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -415,7 +415,7 @@ export const FEATURE_FLAGS = {
MAX_HANDS_FREE: 'max-hands-free', // owner: #team-posthog-ai
MAX_WEB_ANALYTICS_NUDGE: 'posthog-ai-web-analytics-nudge', // owner: @jordanm-posthog #team-web-analytics
MCP_ANALYTICS_INTENT_ROUTING: 'mcp-analytics-intent-routing', // owner: #project-mcp-analytics
- MCP_GATEWAY: 'mcp-gateway', // owner: #team-self-driving — gates the MCP gateway UI AND backend enforcement of built-in agent MCP access (delegated-only installs + restricted sandbox token scope); roll out by organization
+ MCP_GATEWAY: 'mcp-gateway', // owner: #team-context-mcp — gates the MCP gateway UI AND backend enforcement of built-in agent MCP access (delegated-only installs + restricted sandbox token scope); roll out by organization
MEMBER_BILLING_USAGE_SPEND_READ_ACCESS: 'member-billing-usage-spend-read-access', // owner: @pawelcebula #team-billing, grants members read-only access to billing usage/spend tabs; owner-only-billing takes precedence
MESSAGING_SES: 'messaging-ses', // owner #team-workflows
METRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 2264ce273370..5b75f2254b84 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -603,9 +603,7 @@ def get_user_mcp_server_configs(
The `x-posthog-mcp-consumer` header is set on every config so the agent's
identity propagates through the MCP Store proxy to whichever upstream MCP
- the user installed. The PostHog MCP needs this to resolve single-exec mode
- (without it, calls to `exec` fail with "Tool exec not found"); non-PostHog
- upstreams ignore the header.
+ the user installed. Non-PostHog upstreams ignore the header.
Returns an empty list on errors (non-fatal).
"""
diff --git a/services/mcp/README.md b/services/mcp/README.md
index 69bfc78f5b9d..fda02c72d20f 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -440,7 +440,6 @@ Changes in the examples repo will be reflected on the next request.
- `src/` - The MCP server: Hono app (`src/hono/`), tool handlers (`src/tools/`), prompt templates (`src/templates/`)
- `definitions/` - Hand-authored YAML tool definitions (per-product YAML lives at `products/<product>/mcp/` in the monorepo)
- `schema/` - Generated schema files, including `tool-definitions-all.json` (the full tool catalog)
-- `typescript/` - A small shim (`typescript/src/tools/posthogAiTools/`) consumed by posthog-ai
### Development Commands
diff --git a/services/mcp/definitions/prompts/query-traces-list.md b/services/mcp/definitions/prompts/query-traces-list.md
deleted file mode 100644
index c66826ff8635..000000000000
--- a/services/mcp/definitions/prompts/query-traces-list.md
+++ /dev/null
@@ -1,161 +0,0 @@
-List LLM traces to inspect AI/LLM usage across your application. Returns traces with their events, latency, token usage, costs, errors, and other metadata. Use this tool for AI observability — debugging slow generations, investigating errors, analyzing token spend, and auditing LLM behavior.
-
-Use 'read-data-schema' to discover available event properties for filtering (e.g. `$ai_model`, `$ai_provider`).
-
-Examples of use cases include:
-
-- How much are we spending on LLM tokens per day?
-- Which LLM generations are the slowest?
-- Are there any traces with errors in the last 24 hours?
-- What models are being used and how do their costs compare?
-- Show me traces for a specific user to debug their experience.
-- Are there any traces with unusually high token usage?
-
-CRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.
-
-# Data narrowing
-
-## Property filters
-
-Use property filters to narrow results. Only include property filters when they are essential to directly answer the user's question. Avoid adding them if the question can be addressed without additional segmentation and always use the minimum set of property filters needed.
-
-IMPORTANT: Do not check if a property is set unless the user explicitly asks for it.
-
-When using a property filter, you should:
-
-- **Prioritize properties directly related to the context or objective of the user's query.** Common AI properties include `$ai_model`, `$ai_provider`, `$ai_trace_id`, `$ai_latency`, `$ai_input_tokens`, `$ai_output_tokens`, `$ai_total_cost_usd`, `$ai_is_error`.
-- **Ensure that you find both the property group and name.** Property groups should be one of the following: event, person, session, group.
-- After selecting a property, **validate that the property value accurately reflects the intended criteria**.
-- **Find the suitable operator for type** (e.g., `contains`, `is set`).
-- If the operator requires a value, use the `read-data-schema` tool to find the property values.
-
-Infer the property groups from the user's request. If your first guess doesn't yield any results, try to adjust the property group.
-
-Supported operators for the String type are:
-
-- equals (exact)
-- doesn't equal (is_not)
-- contains (icontains)
-- doesn't contain (not_icontains)
-- matches regex (regex)
-- doesn't match regex (not_regex)
-- is set
-- is not set
-
-Supported operators for the Numeric type are:
-
-- equals (exact)
-- doesn't equal (is_not)
-- greater than (gt)
-- less than (lt)
-- is set
-- is not set
-
-Supported operators for the DateTime type are:
-
-- equals (is_date_exact)
-- doesn't equal (is_not for existence check)
-- before (is_date_before)
-- after (is_date_after)
-- is set
-- is not set
-
-Supported operators for the Boolean type are:
-
-- equals
-- doesn't equal
-- is set
-- is not set
-
-All operators take a single value except for `equals` and `doesn't equal` which can take one or more values (as an array).
-
-## Time period
-
-You should not filter events by time using property filters. Instead, use the `dateRange` field. If the question doesn't mention time, use last 7 days as a default time period.
-
-# Traces guidelines
-
-This is a listing tool, not a visualization/insight tool. It returns a paginated list of LLM traces — it does NOT support series, breakdowns, math aggregations, or chart types.
-
-## Response shape
-
-Each trace in the results contains:
-
-- `id` — unique trace ID
-- `traceName` — name of the trace (if set via SDK)
-- `createdAt` — timestamp of the first event in the trace
-- `distinctId` — the person's distinct ID
-- `totalLatency` — total latency in seconds
-- `inputTokens` / `outputTokens` — token counts across all generations in the trace
-- `inputCost` / `outputCost` / `totalCost` — costs in USD
-- `errorCount` — number of errors in the trace
-- `tools` — list of tool names called during the trace
-- `events` — list of direct child events (generations, metrics, feedback)
-
-## Pagination
-
-Use `limit` and `offset` for pagination. The default limit is 100. The response includes a `hasMore` field indicating whether more results are available.
-
-## Filtering
-
-- `filterTestAccounts` — exclude internal/test users
-- `filterSupportTraces` — exclude support impersonation traces
-- `personId` — filter by a specific person UUID
-- `groupKey` + `groupTypeIndex` — filter by a specific group
-- `randomOrder` — use random ordering instead of newest-first (useful for representative sampling)
-
-# Examples
-
-## Recent traces with errors
-
-```json
-{
- "kind": "TracesQuery",
- "dateRange": { "date_from": "-7d" },
- "filterTestAccounts": true,
- "properties": [{ "key": "$ai_is_error", "operator": "exact", "type": "event", "value": ["true"] }],
- "limit": 50
-}
-```
-
-## Traces for a specific model
-
-```json
-{
- "kind": "TracesQuery",
- "dateRange": { "date_from": "-7d" },
- "filterTestAccounts": true,
- "properties": [{ "key": "$ai_model", "operator": "exact", "type": "event", "value": ["gpt-4o"] }]
-}
-```
-
-## Traces for a specific person
-
-```json
-{
- "kind": "TracesQuery",
- "dateRange": { "date_from": "-30d" },
- "personId": "01234567-89ab-cdef-0123-456789abcdef",
- "filterTestAccounts": true
-}
-```
-
-## Random sample of traces (avoids recency bias)
-
-```json
-{
- "kind": "TracesQuery",
- "dateRange": { "date_from": "-30d" },
- "filterTestAccounts": true,
- "randomOrder": true,
- "limit": 20
-}
-```
-
-# Reminders
-
-- Ensure that any properties included are directly relevant to the context and objectives of the user's question. Avoid unnecessary or unrelated details.
-- Avoid overcomplicating the response with excessive property filters. Focus on the simplest solution.
-- This tool returns raw trace data — it does not aggregate or visualize. For aggregated LLM metrics over time (e.g. total token usage per day), use `query-trends` with AI events like `$ai_generation` instead.
-- Use `filterTestAccounts: true` by default to exclude internal users unless the user asks otherwise.
-- The default time range is last 7 days. LLM trace data tends to be recent, so shorter ranges are usually appropriate.
diff --git a/services/mcp/evals/README.md b/services/mcp/evals/README.md
index 0d099b1ce082..954ca5a622ef 100644
--- a/services/mcp/evals/README.md
+++ b/services/mcp/evals/README.md
@@ -1,66 +1,76 @@
-# MCP agent-experience evals
+# MCP evals
-The objective function for improving the MCP server: a fixed benchmark of agent tasks, sampled from real usage, that can be scored against a live MCP server. A change to a tool description, schema, or handler "improves the MCP" only if these scores say so.
-
-Two consumers:
-
-- **Regression protection** — run before/after any change to tool descriptions, schemas, or the catalog.
-- **The improve-my-mcp campaign** — an autoresearch-style loop that proposes a change, re-runs the affected benchmark slice, and only keeps changes that measurably help. Every campaign PR carries before/after scores from this harness as evidence.
+A benchmark of agent tasks for the PostHog MCP server, a script that runs each task's probe call against a live server, and a script that seeds the feature flags some tasks need.
## Layout
-- `benchmark/tasks.yaml` — the task set (v2). Each task is a realistic agent goal with the tools a competent agent should reach for, plus a `fixtures` block naming the entities a run needs in place.
-- `benchmark/schema.ts` — zod schema, loader, and types. `tests/evals/benchmark.test.ts` validates the fixtures against the schema and the live tool catalog, so a tool rename or removal fails CI here instead of silently invalidating the benchmark.
-- `runner/seed.ts` — writes the `fixtures` block to the target project. See [Seeding](#seeding).
+- `benchmark/tasks.yaml` — the task set, plus a `fixtures` block of feature flags that some tasks act on.
+- `benchmark/schema.ts` — the zod schema and loader for `tasks.yaml`.
+- `runner/probe.ts` — runs each task's `probe` against a live MCP server. See [Probe runner](#probe-runner).
+- `runner/results.ts` — the result types and summary for a probe run.
+- `runner/seed.ts` — writes the fixture flags to a PostHog project. See [Seeding](#seeding).
+
+`tests/evals/benchmark.test.ts` runs in CI and checks `tasks.yaml`. Among other checks, it fails when a task names a tool that is not in the MCP tool catalog, when a probe uses a tool that is not read-only, or when a fixture flag is named in no task intent or in more than one.
## Task format
```yaml
- id: flags-list-active # kebab-case, unique
- category: feature-flags # see TASK_CATEGORIES in schema.ts
- intent: 'List all our active feature flags.' # what the agent is asked, phrased like a real request
- expected_tools: [feature-flag-get-all] # what a competent agent should call
- acceptable_tools: [execute-sql] # also fine; no tool-selection penalty
- success_criteria: "Returns the project's active flags by key." # pass condition for the agent-mode judge
- probe: # optional: deterministic call, no LLM needed
+ category: feature-flags # one of TASK_CATEGORIES in schema.ts
+ intent: 'List all our active feature flags.' # the request, phrased like a real user's
+ expected_tools: [feature-flag-get-all] # tools a competent agent should call
+ acceptable_tools: [execute-sql] # other tools that are also a reasonable path
+ success_criteria: "Returns the project's active flags by key." # what a correct answer does
+ probe: # optional: one read-only call the probe runner makes
tool: feature-flag-get-all
args: {}
max_ms: 15000
```
-## Modes
+The probe runner checks `expected_tools` and runs `probe`. No script here scores `intent` or `success_criteria`.
+
+## Probe runner
+
+Run from `services/mcp/`:
-**Probe mode** (deterministic, no LLM): executes each task's `probe` against a live server and validates schemas, latency, and error responses for every referenced tool. Probes must reference read-only tools — the fixture test enforces `readOnlyHint`, and the runner refuses anything else, so a bad fixture cannot mutate project data.
+```bash
+LIVE_MCP_URL=http://localhost:9876 LIVE_MCP_TOKEN=phx_... \
+ pnpm exec tsx evals/runner/probe.ts [--out score.json]
+```
+
+It connects in tools mode, then:
-**Agent mode** (LLM): replays each `intent` through an agent loop against the live server, then scores task success against `success_criteria` (LLM judge) and tool selection against `expected_tools`/`acceptable_tools`.
+1. Lists the tools the server advertises, and reports each task's `expected_tools` or `probe` tool that is missing.
+2. Runs each task's `probe` call and records its status and latency.
+ It refuses a probe whose tool the server does not advertise as read-only, so a bad fixture cannot change project data.
+3. Prints a summary: missing tools, probes passed and failed, and latency p50/p95. `--out` also writes it as JSON.
-Scores per run: task success rate, tool-selection accuracy, schema-validation failure count, tool error rate, retries per task, latency p50/p95, tokens per task.
+The exit code is non-zero when a tool is missing or a probe fails.
## Seeding
-Agent mode mutates state, so it needs state to mutate.
-`fixtures` in `tasks.yaml` declares it, and `runner/seed.ts` writes it:
+Some tasks ask an agent to create or change feature flags.
+The `fixtures` block lists those flags, and `runner/seed.ts` puts them in a known state.
+Run from `services/mcp/`:
```bash
LIVE_POSTHOG_URL=http://localhost:8000 LIVE_MCP_TOKEN=phx_... \
pnpm exec tsx evals/runner/seed.ts [--project 12345]
```
-Run it before every agent-mode run.
-It is idempotent over the keys it owns: it rewrites every flag in `fixtures.feature_flags` and clears the keys in `fixtures.absent_feature_flags`, so those tasks start a second run where they started the first.
-`flag-create-routes-to-experiment` is the exception. The agent picks the key of the flag its experiment manages, so the seeder cannot name that key in `absent_feature_flags`, and the experiment and flag from an earlier run are still there on the next one. Delete them by hand when a rerun needs a clean project.
-Probe mode needs no seeding — probes are read-only.
-
-Two things to get right:
-
-- **Seed the project the MCP session acts on.** Without `--project` the seeder uses the token's current project. Seeding one project while the run scores another looks exactly like a tool-selection regression.
-- **Give each mutating task its own fixture.** Two tasks sharing one flag make the run order-dependent: whichever runs first decides what the next one starts from. `tests/evals/benchmark.test.ts` asserts every fixture key is named in exactly one intent, which catches both a shared fixture and an orphaned one.
+- It creates or updates every flag in `fixtures.feature_flags`, and soft-deletes every key in `fixtures.absent_feature_flags`. Running it again resets those flags.
+- `flag-create-routes-to-experiment` is the exception. The agent picks the key of the flag its experiment manages, so the seeder cannot reset it. Delete that experiment and flag by hand when you need a clean project.
+- It writes through the REST API, not the MCP server, so the tools under test do not build their own starting state.
+- Without `--project` it seeds the token's current project. Seed the project the MCP session acts on.
+- The token needs `feature_flag:write`, plus `user:read` when `--project` is omitted.
+- The exit code is non-zero when any fixture could not be written.
-The seeder talks to the REST API, not to the MCP server, so the tools under test are not also what builds the state they are measured against.
+Probes are read-only, so the probe runner needs no seeding.
## Authoring rules
- Sample intents from real usage (`$mcp_intent` clusters, `query-mcp-tool-sample-intents`) but **paraphrase — never paste customer text verbatim**, and never include PII.
-- Keep the task set stable within a campaign: scores are only comparable across runs of the same benchmark version. Bump `version` on breaking changes to the set.
+- Results are only comparable across runs of the same benchmark `version`. Bump it on breaking changes to the set, together with the version literal in `schema.ts`.
- Weight new tasks toward observed pain: high-error tools, discoverability misses (intents where agents picked the wrong tool), and multi-step chains (resolve id → act).
+- Give each task that changes a flag its own fixture flag, so the result does not depend on task order. The fixture test enforces this.
- A task must be achievable in a seeded demo project — don't write tasks that depend on one specific production dataset.
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.ts
index 4aa834e1c48a..79851c493952 100644
--- a/services/mcp/src/hono/cache/RedisCache.ts
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -21,7 +21,7 @@ const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60 // 7 days
const CLEAR_MAX_ITERATIONS = 50
const CLEAR_SCAN_COUNT = 100
-export type CachePrefix = 'token' | 'user' | 'session'
+export type CachePrefix = 'token' | 'session'
export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {
private redis: RedisLike
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 10f03c529779..eb674bc78932 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -13,7 +13,6 @@ import {
import type { RequestProperties } from '@/lib/request-properties'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
-import { hash } from '@/lib/utils'
import type { Context, Env, SessionScopedState, State } from '@/tools/types'
import { RedisCache, type RedisLike } from './cache/RedisCache'
@@ -34,7 +33,6 @@ const SESSION_CACHE_TTL_SECONDS = 24 * 60 * 60
export class RequestContext {
private tokenCacheInstance: RedisCache<State> | undefined
- private userCacheInstance: RedisCache<State> | undefined
private sessionScopedCacheInstance: RedisCache<SessionScopedState> | undefined
private apiInstance: ApiClient | undefined
private sessionManagerInstance: SessionManager | undefined
@@ -68,13 +66,6 @@ export class RequestContext {
return this.tokenCacheInstance
}
- getUserCache(distinctId: string): RedisCache<State> {
- if (!this.userCacheInstance) {
- this.userCacheInstance = new RedisCache<State>(hash(distinctId), this.redis, 'user')
- }
- return this.userCacheInstance
- }
-
get cache(): RedisCache<State> {
return this.tokenCache
}
diff --git a/services/mcp/src/resources/internals.ts b/services/mcp/src/resources/internals.ts
index e0dcbdc6768c..7275df90688a 100644
--- a/services/mcp/src/resources/internals.ts
+++ b/services/mcp/src/resources/internals.ts
@@ -65,10 +65,6 @@ export function filterValidEntries(entries: readonly ContextMillResource[], arch
})
}
-export function clearResourceCache(): void {
- cachedResources = null
-}
-
/**
* Fetch + unzip + parse the context-mill manifest, returning the filtered
* entries. Does not touch the module-level `cachedResources`; used by the
diff --git a/services/mcp/src/resources/manifest-types.ts b/services/mcp/src/resources/manifest-types.ts
index 119297f4a3e2..ef080fdf0558 100644
--- a/services/mcp/src/resources/manifest-types.ts
+++ b/services/mcp/src/resources/manifest-types.ts
@@ -14,14 +14,6 @@ export interface WorkflowResource {
nextStepUri?: string
}
-export interface ExampleResource {
- id: string
- name: string
- description: string
- file: string
- uri: string
-}
-
export interface DocResource {
id: string
name: string
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 6996c5324376..d20c5ce45f28 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -537,27 +537,6 @@ function isRecordableToolName(name: string, isKnownToolName: (name: string) => b
return isKnownToolName(name) || Object.prototype.hasOwnProperty.call(DEPRECATED_TOOL_REDIRECTS, name)
}
-// Resolves the inner tool an `exec` call targets: given a request, return the
-// inner tool's { name, description } when the agent invoked it via
-// `call <tool> ...`, or undefined otherwise. Lives here (alongside
-// parseExecCallInnerToolName) so callers and tests share one factory.
-export function createExecInnerToolCallResolver(
- allTools: ReadonlyArray<Tool<ZodObjectAny>>
-): (request: unknown) => { name: string; description: string } | undefined {
- return (request: unknown) => {
- const params = (request as { params?: { name?: unknown; arguments?: { command?: unknown } } })?.params
- if (params?.name !== 'exec' || typeof params.arguments?.command !== 'string') {
- return
- }
- const innerName = parseExecCallInnerToolName(params.arguments.command)
- if (!innerName) {
- return
- }
- const tool = allTools.find((t) => t.name === innerName)
- return tool ? { name: tool.name, description: tool.description } : undefined
- }
-}
-
// Tools deleted from the MCP server. When the model attempts to call one,
// surface a targeted redirect to the replacement instead of dumping the full
// tool catalog. Keep the redirect text editorial — schemas don't carry
diff --git a/services/mcp/src/tools/fix-formatresponse-multiline.sh b/services/mcp/src/tools/fix-formatresponse-multiline.sh
deleted file mode 100755
index 5a6c64b024dd..000000000000
--- a/services/mcp/src/tools/fix-formatresponse-multiline.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/bash
-
-# Script to remove formatResponse wrapper from tool files (handles multi-line)
-# Changes: return {
-# content: [{ type: 'text', text: formatResponse(X) }],
-# }
-# To: return X
-
-count=0
-
-for file in $(find . -name "*.ts" -type f); do
- # Check if file contains formatResponse
- if grep -q "formatResponse" "$file"; then
- # Use perl to handle multi-line pattern
- perl -0777 -i -pe 's/return\s*\{\s*content:\s*\[\s*\{\s*type:\s*['\''"]text['\''"]\s*,\s*text:\s*formatResponse\(((?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)\s*\}\s*\]\s*,?\s*\}/return $1/gs' "$file"
-
- if ! grep -q "formatResponse" "$file"; then
- ((count++))
- echo "Updated: $file"
- fi
- fi
-done
-
-echo ""
-echo "Total files updated: $count"
diff --git a/services/mcp/src/tools/fix-formatresponse.sh b/services/mcp/src/tools/fix-formatresponse.sh
deleted file mode 100755
index d3aa6b46aa31..000000000000
--- a/services/mcp/src/tools/fix-formatresponse.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/bash
-
-# Script to remove formatResponse wrapper from tool files
-# Changes: return { content: [{ type: 'text', text: formatResponse(X) }] }
-# To: return X
-
-count=0
-
-for file in $(find . -name "*.ts" -type f); do
- # Check if file contains the pattern we want to change
- if grep -q "formatResponse" "$file"; then
- # Remove the import line
- sed -i.bak "/import.*formatResponse.*from/d" "$file"
-
- # Replace the return pattern - handles single line cases
- perl -i -pe 's/return\s+\{\s*content:\s*\[\s*\{\s*type:\s*['\''"]text['\''"]\s*,\s*text:\s*formatResponse\((.*?)\)\s*\}\s*\]\s*\}/return $1/g' "$file"
-
- # Remove .bak file if no changes were made
- if diff "$file" "$file.bak" > /dev/null 2>&1; then
- rm "$file.bak"
- else
- rm "$file.bak"
- ((count++))
- echo "Updated: $file"
- fi
- fi
-done
-
-echo ""
-echo "Total files updated: $count"
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index c76e0660368f..e935d51b807a 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -45,8 +45,6 @@ export type State = {
mcpProtocolVersion: string | undefined
mcpConsumer: string | undefined
mcpVendorClient: string | undefined
- skillsLearnedAt: number | undefined
- skillsNoSkillsAckAt: number | undefined
} & Record<PrefixedString<'session'>, SessionState> &
Record<PrefixedString<'groupTypes'>, GroupType[] | undefined> &
Record<PrefixedString<'groupTypesFetchedAt'>, number | undefined> &
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index c2444b5f6d9c..26bda540fa53 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -1,14 +1,5 @@
import type { YAxisFormat } from '@posthog/quill-charts'
-import type { AnalyticsMetadata } from '../types'
-
-// Base payload that all tool results share
-interface BasePayload {
- _posthogUrl?: string
- /** Analytics metadata injected by MCP server for user tracking */
- _analytics?: AnalyticsMetadata
-}
-
// ============================================================================
// Query-based visualizations
// ============================================================================
@@ -211,36 +202,6 @@ export interface PathsResultItem {
export type PathsResult = PathsResultItem[]
-// ============================================================================
-// Tool result payloads
-// The visualization type is inferred from the data structure, not a discriminator
-// ============================================================================
-
-export interface TrendsPayload extends BasePayload {
- query: TrendsQuery
- results: TrendsResult
-}
-
-export interface FunnelPayload extends BasePayload {
- query: FunnelsQuery
- results: FunnelResult
-}
-
-export interface LifecyclePayload extends BasePayload {
- query: LifecycleQuery
- results: LifecycleResult
-}
-
-export interface TablePayload extends BasePayload {
- query?: HogQLQuery
- results: HogQLResult
-}
-
-export interface RetentionPayload extends BasePayload {
- query: RetentionQuery
- results: RetentionResult
-}
-
// ============================================================================
// Component props
// ============================================================================
diff --git a/services/mcp/src/ui-apps/types.ts b/services/mcp/src/ui-apps/types.ts
index aa62f363d931..0fb549bd0a1d 100644
--- a/services/mcp/src/ui-apps/types.ts
+++ b/services/mcp/src/ui-apps/types.ts
@@ -48,12 +48,6 @@ export type WithAnalytics<T> = T & {
_analytics?: AnalyticsMetadata
}
-/**
- * Extract the data type from a tool result, excluding analytics metadata.
- * Useful when you want to work with just the payload data without analytics.
- */
-export type ExtractData<T> = Omit<T, '_analytics'>
-
/**
* Type guard to check if a value has analytics metadata.
*/
diff --git a/services/mcp/tests/hono/dispatcher-profile.perf.ts b/services/mcp/tests/hono/dispatcher-profile.perf.ts
index bb7799fcc3b0..083a6e2a5885 100644
--- a/services/mcp/tests/hono/dispatcher-profile.perf.ts
+++ b/services/mcp/tests/hono/dispatcher-profile.perf.ts
@@ -16,7 +16,6 @@ vi.mock('@/resources/internals', () => ({
fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
filterValidEntries: vi.fn().mockReturnValue([]),
loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
- clearResourceCache: vi.fn(),
}))
vi.mock('@/resources', () => ({
diff --git a/services/mcp/tests/hono/setup.ts b/services/mcp/tests/hono/setup.ts
index 17044d536182..c93f999e559d 100644
--- a/services/mcp/tests/hono/setup.ts
+++ b/services/mcp/tests/hono/setup.ts
@@ -82,7 +82,6 @@ vi.mock('@/tools/exec', async () => {
} catch {
return {
createExecTool: vi.fn(() => ({ name: 'posthog', handler: vi.fn() })),
- createExecInnerToolCallResolver: vi.fn(() => () => undefined),
}
}
})
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index 79c821ce2164..99ddf6fd3326 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -12,7 +12,6 @@ vi.mock('@/resources/internals', () => ({
fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
filterValidEntries: vi.fn().mockReturnValue([]),
loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
- clearResourceCache: vi.fn(),
}))
vi.mock('@/resources', () => ({
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 5966408bcbaf..2928413c4800 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -29,7 +29,6 @@ vi.mock('@/resources/internals', () => ({
fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
filterValidEntries: vi.fn().mockReturnValue([]),
loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
- clearResourceCache: vi.fn(),
}))
vi.mock('@/resources', () => ({
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index 600e6e1d6e09..0def915367ac 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -15,7 +15,6 @@ vi.mock('@/resources/internals', () => ({
fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
filterValidEntries: vi.fn().mockReturnValue([]),
loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
- clearResourceCache: vi.fn(),
}))
vi.mock('@/resources', () => ({
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 2a7ae9688edb..d7b2b6f874e7 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -5,7 +5,6 @@ vi.mock('@/resources/internals', () => ({
fetchContextMillResources: vi.fn().mockRejectedValue(new Error('mocked')),
filterValidEntries: vi.fn().mockReturnValue([]),
loadManifestFromArchive: vi.fn().mockReturnValue({ resources: [] }),
- clearResourceCache: vi.fn(),
}))
vi.mock('@/resources', () => ({
diff --git a/services/mcp/typescript/src/tools/posthogAiTools/executeSql.ts b/services/mcp/typescript/src/tools/posthogAiTools/executeSql.ts
deleted file mode 100644
index 321ab1b2e069..000000000000
--- a/services/mcp/typescript/src/tools/posthogAiTools/executeSql.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { z } from 'zod'
-
-import { ExecuteSQLSchema } from '@/schema/tool-inputs'
-import type { Context, ToolBase } from '@/tools/types'
-
-import { invokeMcpTool } from './invokeTool'
-
-const schema = ExecuteSQLSchema
-
-type Params = z.infer<typeof schema>
-
-export const executeSqlHandler: ToolBase<typeof schema>['handler'] = async (context: Context, params: Params) => {
- const result = await invokeMcpTool(context, 'execute_sql', {
- query: params.query,
- truncate: params.truncate ?? true,
- })
-
- if (!result.success) {
- throw new Error(result.content)
- }
-
- return result.content
-}
-
-const tool = (): ToolBase<typeof schema> => ({
- name: 'execute-sql',
- schema,
- handler: executeSqlHandler,
-})
-
-export default tool
diff --git a/services/mcp/typescript/src/tools/posthogAiTools/index.ts b/services/mcp/typescript/src/tools/posthogAiTools/index.ts
deleted file mode 100644
index e866eee3f743..000000000000
--- a/services/mcp/typescript/src/tools/posthogAiTools/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { default as executeSql } from './executeSql'
-export { default as readDataSchema } from './readDataSchema'
-export { invokeMcpTool, type McpToolResult } from './invokeTool'
diff --git a/services/mcp/typescript/src/tools/posthogAiTools/invokeTool.ts b/services/mcp/typescript/src/tools/posthogAiTools/invokeTool.ts
deleted file mode 100644
index 3ebbd0f474b5..000000000000
--- a/services/mcp/typescript/src/tools/posthogAiTools/invokeTool.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { Context } from '@/tools/types'
-
-export interface McpToolResult {
- success: boolean
- content: string
-}
-
-/**
- * Invoke an MCP tool via the PostHog API.
- *
- * @param context - The MCP context containing API client and state
- * @param toolName - Name of the MCP tool to invoke (e.g., 'execute_sql')
- * @param args - Arguments to pass to the tool
- * @returns The tool result with success status and content
- */
-export async function invokeMcpTool(
- context: Context,
- toolName: string,
- args: Record<string, any>
-): Promise<McpToolResult> {
- const projectId = await context.stateManager.getProjectId()
-
- const url = `${context.api.baseUrl}/api/environments/${projectId}/mcp_tools/${toolName}/`
-
- const response = await fetch(url, {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${context.api.config.apiToken}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ args }),
- })
-
- if (!response.ok) {
- const errorText = await response.text()
- let errorMessage: string
- try {
- const errorData = JSON.parse(errorText)
- errorMessage = errorData.content || errorText
- } catch {
- errorMessage = errorText
- }
- return {
- success: false,
- content: `Failed to invoke MCP tool '${toolName}': ${errorMessage}`,
- }
- }
-
- return response.json() as Promise<McpToolResult>
-}
diff --git a/services/mcp/typescript/src/tools/posthogAiTools/readDataSchema.ts b/services/mcp/typescript/src/tools/posthogAiTools/readDataSchema.ts
deleted file mode 100644
index 0cfa2eb41be0..000000000000
--- a/services/mcp/typescript/src/tools/posthogAiTools/readDataSchema.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { z } from 'zod'
-
-import { ReadDataSchemaSchema } from '@/schema/tool-inputs'
-import type { Context, ToolBase } from '@/tools/types'
-
-import { invokeMcpTool } from './invokeTool'
-
-const schema = ReadDataSchemaSchema
-
-type Params = z.infer<typeof schema>
-
-export const readDataSchemaHandler: ToolBase<typeof schema>['handler'] = async (context: Context, params: Params) => {
- const result = await invokeMcpTool(context, 'read_taxonomy', {
- query: params.query,
- })
-
- if (!result.success) {
- throw new Error(result.content)
- }
-
- return result.content
-}
-
-const tool = (): ToolBase<typeof schema> => ({
- name: 'read-data-schema',
- schema,
- handler: readDataSchemaHandler,
-})
-
-export default tool