:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): add feedback-submit tool for agent feedback (#57261)
posthog[bot]df79f92ea062
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 424f9d7f2ffc..743316798ed5 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -119,6 +119,23 @@"readOnlyHint": true}},+ "agent-feedback": {+ "description": "Optional: submit structured feedback about your experience using this PostHog MCP server. Reach for this tool when something stood out — friction, a surprise, a missing capability, an unhelpful error, or a tool that worked particularly well. Skip it for routine tasks where nothing is worth flagging. Feedback goes directly to the PostHog team and is the primary signal we use to improve tool descriptions, input schemas, response formats, and instructions for agents like you. Be specific and quote tool names, parameters, and error messages where possible. Do not include user PII or sensitive query content. IMPORTANT: submitting feedback does NOT mean your work is done — keep going and finish the user's task using the other available tools. This tool is for reporting your experience to the PostHog team, not for ending the conversation.",+ "category": "Feedback",+ "feature": "feedback",+ "summary": "Optional: submit feedback about the PostHog MCP server.",+ "title": "Submit agent feedback",+ "required_scopes": [],+ "new_mcp": true,+ "always_available": true,+ "feature_flag": "mcp-feedback-tool",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false,+ "readOnlyHint": true+ }+ },"alert-create": {"description": "Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For threshold alerts: set condition (absolute_value, relative_increase, relative_decrease) and threshold configuration with bounds. For anomaly detection: set detector_config with a detector type (zscore, mad, iqr, threshold, copod, ecod, hbos, isolation_forest, knn, lof, ocsvm, pca) and parameters like threshold (sensitivity 0-1, default 0.9) and window size. Ensemble detectors combine 2+ sub-detectors with AND/OR logic. Requires an insight ID and at least one subscribed user.\nNote: subscribed_users only controls email recipients. For Slack or HTTPS webhook delivery, see the recipe on cdp-functions-create — it covers integration lookup (integrations-channels-retrieve), dedupe (cdp-functions-list filtered by alert id, limit=1000), and the exact filters/inputs shape to pass.","category": "Alerts",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex c9167b3971c0..8da32a876daa 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -1,4 +1,21 @@{+ "agent-feedback": {+ "description": "Optional: submit structured feedback about your experience using this PostHog MCP server. Reach for this tool when something stood out — friction, a surprise, a missing capability, an unhelpful error, or a tool that worked particularly well. Skip it for routine tasks where nothing is worth flagging. Feedback goes directly to the PostHog team and is the primary signal we use to improve tool descriptions, input schemas, response formats, and instructions for agents like you. Be specific and quote tool names, parameters, and error messages where possible. Do not include user PII or sensitive query content. IMPORTANT: submitting feedback does NOT mean your work is done — keep going and finish the user's task using the other available tools. This tool is for reporting your experience to the PostHog team, not for ending the conversation.",+ "category": "Feedback",+ "feature": "feedback",+ "summary": "Optional: submit feedback about the PostHog MCP server.",+ "title": "Submit agent feedback",+ "required_scopes": [],+ "new_mcp": true,+ "always_available": true,+ "feature_flag": "mcp-feedback-tool",+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": false,+ "readOnlyHint": true+ }+ },"experiment-results-get": {"description": "Get comprehensive experiment results including all metrics data (primary and secondary) and exposure data. This tool fetches the experiment details and executes the necessary queries to get complete experiment results. Only works with new experiments (not legacy experiments).","category": "Experiments",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 0451a2024c48..4beb3e7ab2b1 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -824,6 +824,64 @@"type": "string","description": "The source type name (e.g. \"Postgres\", \"MySQL\", \"Stripe\"). Use external-data-sources-wizard to see available types and their required fields."},+ "FeedbackSubmitSchema": {+ "type": "object",+ "properties": {+ "summary": {+ "type": "string",+ "minLength": 1,+ "description": "A one-sentence headline summarising your feedback (e.g. \"query-trends descriptions made it hard to choose between trends and funnels\")."+ },+ "sentiment": {+ "type": "string",+ "enum": ["positive", "negative", "mixed"],+ "description": "Your overall impression of the MCP server for this task. Use \"positive\" if it helped you, \"negative\" if it blocked you, \"mixed\" for a bit of both."+ },+ "category": {+ "type": "string",+ "enum": [+ "tool_correctness",+ "tool_description",+ "tool_input_schema",+ "tool_output_format",+ "missing_tool",+ "instructions_clarity",+ "performance",+ "error_message",+ "other"+ ],+ "description": "The single category that best describes the dominant theme of this feedback. Pick \"missing_tool\" if a capability was absent, \"tool_description\" if the tool docs were unclear, \"tool_input_schema\" if input args were confusing, \"tool_output_format\" if the response was hard to consume, \"instructions_clarity\" if these MCP instructions were unclear, \"tool_correctness\" if a tool returned wrong data, \"error_message\" if an error was unhelpful, \"performance\" if latency was the issue."+ },+ "task_completed": {+ "type": "boolean",+ "description": "Were you able to complete the user's task using PostHog MCP tools? Be honest — \"false\" is just as useful as \"true\"."+ },+ "tools_used": {+ "description": "The tool names you called while working on the user's task (e.g. [\"read-data-schema\", \"query-trends\"]). Helps us correlate feedback to specific tools.",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "friction_points": {+ "description": "Concrete points of friction, confusion, or surprise — what slowed you down or made you guess. Quote the exact tool name, parameter, or error text where possible.",+ "type": "string"+ },+ "suggested_improvement": {+ "description": "The single most impactful change you would make to the MCP server right now. Be specific (e.g. \"add a `filters` example to query-funnel's description\").",+ "type": "string"+ },+ "user_request": {+ "description": "A short, anonymised paraphrase of what the user originally asked you to do. Do not include PII, customer names, or sensitive query content.",+ "type": "string"+ },+ "details": {+ "description": "Any additional context that doesn't fit the other fields.",+ "type": "string"+ }+ },+ "required": ["summary", "sentiment", "category", "task_completed"]+ },"HogQLSchemaInputSchema": {"type": "object","properties": {diff --git a/services/mcp/src/lib/analytics.ts b/services/mcp/src/lib/analytics.tsindex cbdf973cac1c..14247538da5c 100644--- a/services/mcp/src/lib/analytics.ts+++ b/services/mcp/src/lib/analytics.ts@@ -8,6 +8,7 @@ export enum AnalyticsEvent {MCP_PROJECT_SWITCHED = 'mcp project switched',MCP_ORGANIZATION_SWITCHED = 'mcp organization switched',MCP_TOOL_CALLED = 'mcp_tool_called', // matching mcpcat+ MCP_FEEDBACK_SUBMITTED = 'mcp feedback submitted',}export type MCPAnalyticsContext = {diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.tsindex 9d5d8a545f6b..6c3f5271cc70 100644--- a/services/mcp/src/mcp.ts+++ b/services/mcp/src/mcp.ts@@ -334,7 +334,9 @@ export class MCP extends McpAgent<Env> {}}- private async getAnalyticsContextSafe(context: Context): Promise<MCPAnalyticsContext | undefined> {+ private async getAnalyticsContextSafe(+ context: Pick<Context, 'stateManager'>+ ): Promise<MCPAnalyticsContext | undefined> {try {return await context.stateManager.getAnalyticsContext()} catch {@@ -455,14 +457,20 @@ export class MCP extends McpAgent<Env> {async getContext(): Promise<Context> {const api = await this.api()- return {+ const stateManager = new StateManager(this.cache, api)+ const partialContext: Omit<Context, 'trackEvent'> = {api,cache: this.cache,env: this.env,- stateManager: new StateManager(this.cache, api),+ stateManager,sessionManager: this.sessionManager,getDistinctId: () => this.getDistinctId(),}+ const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {+ const analyticsContext = await this.getAnalyticsContextSafe(partialContext)+ await this.trackEvent(event, properties, analyticsContext ? { context: analyticsContext } : undefined)+ }+ return { ...partialContext, trackEvent }}async init(): Promise<void> {diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex dcbc29409f94..5834764a5623 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -84,6 +84,65 @@ export const DocumentationSearchSchema = z.object({query: z.string(),})+export const FeedbackSubmitSchema = z.object({+ summary: z+ .string()+ .min(1)+ .describe(+ 'A one-sentence headline summarising your feedback (e.g. "query-trends descriptions made it hard to choose between trends and funnels").'+ ),+ sentiment: z+ .enum(['positive', 'negative', 'mixed'])+ .describe(+ 'Your overall impression of the MCP server for this task. Use "positive" if it helped you, "negative" if it blocked you, "mixed" for a bit of both.'+ ),+ category: z+ .enum([+ 'tool_correctness',+ 'tool_description',+ 'tool_input_schema',+ 'tool_output_format',+ 'missing_tool',+ 'instructions_clarity',+ 'performance',+ 'error_message',+ 'other',+ ])+ .describe(+ 'The single category that best describes the dominant theme of this feedback. Pick "missing_tool" if a capability was absent, "tool_description" if the tool docs were unclear, "tool_input_schema" if input args were confusing, "tool_output_format" if the response was hard to consume, "instructions_clarity" if these MCP instructions were unclear, "tool_correctness" if a tool returned wrong data, "error_message" if an error was unhelpful, "performance" if latency was the issue.'+ ),+ task_completed: z+ .boolean()+ .describe(+ 'Were you able to complete the user\'s task using PostHog MCP tools? Be honest — "false" is just as useful as "true".'+ ),+ tools_used: z+ .array(z.string())+ .optional()+ .describe(+ 'The tool names you called while working on the user\'s task (e.g. ["read-data-schema", "query-trends"]). Helps us correlate feedback to specific tools.'+ ),+ friction_points: z+ .string()+ .optional()+ .describe(+ 'Concrete points of friction, confusion, or surprise — what slowed you down or made you guess. Quote the exact tool name, parameter, or error text where possible.'+ ),+ suggested_improvement: z+ .string()+ .optional()+ .describe(+ 'The single most impactful change you would make to the MCP server right now. Be specific (e.g. "add a `filters` example to query-funnel\'s description").'+ ),+ user_request: z+ .string()+ .optional()+ .describe(+ 'A short, anonymised paraphrase of what the user originally asked you to do. Do not include PII, customer names, or sensitive query content.'+ ),+ details: z.string().optional().describe("Any additional context that doesn't fit the other fields."),+})+export const ExperimentResultsGetSchema = z.object({id: z.number().describe('The ID of the experiment to get comprehensive results for'),refresh: zdiff --git a/services/mcp/src/templates/instructions-v1.md b/services/mcp/src/templates/instructions-v1.mdindex 02cd3740d805..efb066118b85 100644--- a/services/mcp/src/templates/instructions-v1.md+++ b/services/mcp/src/templates/instructions-v1.md@@ -1,3 +1,4 @@- You are a helpful assistant that can query PostHog API.- If 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.- If 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.+- The `agent-feedback` tool is available if you'd like to leave optional feedback about this MCP server (unclear tool descriptions, surprising schemas, missing capabilities, unhelpful errors, or things that worked well). It is entirely optional — skip it for routine tasks where nothing stood out. When you do use it, be specific and do not include user PII or sensitive query content. Submitting feedback is not a way to end your turn: keep working on the user's task afterward using the other available tools.diff --git a/services/mcp/src/templates/instructions-v2.md b/services/mcp/src/templates/instructions-v2.mdindex a5deb91528a1..bed6164f415f 100644--- a/services/mcp/src/templates/instructions-v2.md+++ b/services/mcp/src/templates/instructions-v2.md@@ -33,6 +33,25 @@ If you get errors due to permissions being denied, check that you have the correIf 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.+### Sharing feedback on this MCP server (optional)++The `agent-feedback` tool may be available if you'd like to leave optional feedback about this MCP server. It is the primary signal we use to improve tool descriptions, input schemas, response formats, and these instructions for agents like you. Use it when something stands out — but only when you have something specific to say. There is no expectation to call it after every task; skip it for routine work where nothing is worth flagging.++Good moments to consider it:++- A tool description was unclear or ambiguous and you had to guess.+- An input schema was confusing or surprising.+- A response format was hard to consume or contained too much / too little data.+- A tool returned wrong, incomplete, or unexpected results.+- An error message was unhelpful or didn't explain how to recover.+- A capability was missing entirely and you had to work around it.+- These instructions led you down the wrong path.+- A tool worked particularly well — concrete praise is just as useful as criticism.++If you do submit, be specific: quote tool names, parameter names, and error text where possible. Use `task_completed: false` when you couldn't finish the user's request — that signal is at least as valuable as success. Do not include user PII or sensitive query content in any feedback field.++Submitting feedback is **not** a way to end your turn or skip work. It is a side report to the PostHog team about your experience with the tools — after calling it, keep going and finish the user's task using the other available tools.+### Tool searchPostHog tools have lowercase kebab-case naming and always have a domain.@@ -57,6 +76,8 @@ Available domains (the list is incomplete):Typical action names: list/retrieve/get/create/update/delete/query.Example regex for search: execute-sql or experiment.+(`agent-feedback` is not a domain — it's a single standalone tool, see "Sharing feedback on this MCP server" above. It may not be available for all clients.)+{defined_groups}{metadata}diff --git a/services/mcp/src/tools/feedback/submit.ts b/services/mcp/src/tools/feedback/submit.tsnew file mode 100644index 000000000000..b7aeaf856eb6--- /dev/null+++ b/services/mcp/src/tools/feedback/submit.ts@@ -0,0 +1,63 @@+import type { z } from 'zod'++import { AnalyticsEvent } from '@/lib/analytics'+import { FeedbackSubmitSchema } from '@/schema/tool-inputs'+import type { Context, ToolBase } from '@/tools/types'++const schema = FeedbackSubmitSchema++type Params = z.infer<typeof schema>++type Result = {+ received: boolean+ summary: string+ sentiment: Params['sentiment']+ category: Params['category']+ message: string+}++const RESPONSE_MESSAGE =+ 'Thank you for the feedback — it has been recorded and will be reviewed by the PostHog team. ' ++ "Submitting feedback does not mean your work is done: keep going and finish the user's task " ++ 'using the other available tools.'++export const submitFeedbackHandler: ToolBase<typeof schema, Result>['handler'] = async (+ context: Context,+ params: Params+) => {+ // `context.trackEvent` is itself best-effort (the MCP-class implementation wraps+ // analytics in its own try/catch). The outer try/catch here defends against any+ // unexpected throw on the way *to* trackEvent (e.g. a future refactor) so the+ // agent never sees this tool fail because of an analytics issue.+ try {+ await context.trackEvent(AnalyticsEvent.MCP_FEEDBACK_SUBMITTED, {+ feedback_summary: params.summary,+ feedback_sentiment: params.sentiment,+ feedback_category: params.category,+ feedback_task_completed: params.task_completed,+ feedback_tools_used: params.tools_used,+ feedback_friction_points: params.friction_points,+ feedback_suggested_improvement: params.suggested_improvement,+ feedback_user_request: params.user_request,+ feedback_details: params.details,+ })+ } catch {+ // Analytics is non-fatal — never surface as a tool failure.+ }++ return {+ received: true,+ summary: params.summary,+ sentiment: params.sentiment,+ category: params.category,+ message: RESPONSE_MESSAGE,+ }+}++const tool = (): ToolBase<typeof schema, Result> => ({+ name: 'agent-feedback',+ schema,+ handler: submitFeedbackHandler,+})++export default tooldiff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 55d2d5b66f34..bd01f434a9dc 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -5,6 +5,8 @@ import debugMcpUiApps from './debug/debugMcpUiApps'// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)import getExperimentResults from './experiments/getResults'import experimentListDeprecated from './experiments/listDeprecated'+// Feedback+import submitFeedback from './feedback/submit'// Generated tools (from definitions/*.yaml)import { GENERATED_TOOL_MAP } from './generated'// Insights@@ -78,6 +80,9 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// Debug'debug-mcp-ui-apps': debugMcpUiApps,+ // Feedback+ 'agent-feedback': submitFeedback,+// PostHog AI tools'execute-sql': executeSql,'read-data-schema': readDataSchema,diff --git a/services/mcp/src/tools/toolDefinitions.ts b/services/mcp/src/tools/toolDefinitions.tsindex 1586491e21a9..4d7c1046646d 100644--- a/services/mcp/src/tools/toolDefinitions.ts+++ b/services/mcp/src/tools/toolDefinitions.ts@@ -19,6 +19,14 @@ export const ToolDefinitionSchema = z.object({feature_flag_behavior: z.enum(['enable', 'disable']).optional(),/** One-line selection hint surfaced in the system prompt's query tool catalog. */system_prompt_hint: z.string().optional(),+ /**+ * When true, the tool is exposed even when the client passes a `features`+ * or `tools` allowlist that wouldn't otherwise match. Reserved for+ * cross-cutting utility tools (e.g. feedback) that should remain+ * discoverable to every client without forcing them to opt in.+ * Other filters (readOnly, AI consent, feature flags, scopes) still apply.+ */+ always_available: z.boolean().optional(),annotations: z.object({destructiveHint: z.boolean(),idempotentHint: z.boolean(),@@ -121,6 +129,8 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {// Filter by features and/or tools allowlist (OR union).// When both are provided, a tool is included if it matches a feature category OR is in the tools list.// Normalize hyphens to underscores so that both "error-tracking" and "error_tracking" match.+ // Tools marked `always_available` bypass this allowlist so utility tools+ // (e.g. feedback) stay discoverable for every client.const hasFeatures = features && features.length > 0const hasTools = tools && tools.length > 0if (hasFeatures || hasTools) {@@ -128,6 +138,9 @@ export function getToolsForFeatures(options?: ToolFilterOptions): string[] {const allowedTools = hasTools ? new Set(tools) : nullentries = entries.filter(([toolName, definition]) => {+ if (definition.always_available) {+ return true+ }const matchesFeature = normalizedFeatures? definition.feature && normalizedFeatures.has(normalizeFeatureName(definition.feature)): falsediff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.tsindex 72a9f832d8fb..0a4b44d6039f 100644--- a/services/mcp/src/tools/types.ts+++ b/services/mcp/src/tools/types.ts@@ -2,6 +2,7 @@ import type { z } from 'zod'import type { ApiClient, GroupType } from '@/api/client'import type { Schemas } from '@/api/generated'+import type { AnalyticsEvent } from '@/lib/analytics'import type { ScopedCache } from '@/lib/cache/ScopedCache'import type { SessionManager } from '@/lib/SessionManager'import type { StateManager } from '@/lib/StateManager'@@ -83,6 +84,14 @@ export type Context = {* exec wrapper) can attach `_analytics` without depending on the MCP class.*/getDistinctId: () => Promise<string>+ /**+ * Capture a PostHog analytics event with the same context (mcp_client_name,+ * session id, $groups, etc.) that the MCP class attaches to its own events.+ * Best-effort — never throws and silently swallows failures so analytics+ * cannot fail a tool call. Workspace context is auto-resolved from the+ * stateManager when not provided.+ */+ trackEvent: (event: AnalyticsEvent, properties?: Record<string, unknown>) => Promise<void>}export type Tool<TSchema extends z.ZodType = z.ZodType, TResult = unknown> = {diff --git a/services/mcp/tests/integration/feature-routing.test.ts b/services/mcp/tests/integration/feature-routing.test.tsindex fb9ad73deccd..1063f60083bd 100644--- a/services/mcp/tests/integration/feature-routing.test.ts+++ b/services/mcp/tests/integration/feature-routing.test.ts@@ -21,6 +21,7 @@ const createMockContext = (): Context => ({} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},})describe('Feature Routing Integration', () => {diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.tsindex bad8725a120f..33e77fb32648 100644--- a/services/mcp/tests/shared/test-utils.ts+++ b/services/mcp/tests/shared/test-utils.ts@@ -53,6 +53,7 @@ export function createTestContext(client: ApiClient): Context {stateManager,sessionManager: new SessionManager(cache),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}return contextdiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/agent-feedback.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/agent-feedback.jsonnew file mode 100644index 000000000000..2ec89ee4299b--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/agent-feedback.json@@ -0,0 +1,59 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "category": {+ "description": "The single category that best describes the dominant theme of this feedback. Pick \"missing_tool\" if a capability was absent, \"tool_description\" if the tool docs were unclear, \"tool_input_schema\" if input args were confusing, \"tool_output_format\" if the response was hard to consume, \"instructions_clarity\" if these MCP instructions were unclear, \"tool_correctness\" if a tool returned wrong data, \"error_message\" if an error was unhelpful, \"performance\" if latency was the issue.",+ "enum": [+ "tool_correctness",+ "tool_description",+ "tool_input_schema",+ "tool_output_format",+ "missing_tool",+ "instructions_clarity",+ "performance",+ "error_message",+ "other"+ ],+ "type": "string"+ },+ "details": {+ "description": "Any additional context that doesn't fit the other fields.",+ "type": "string"+ },+ "friction_points": {+ "description": "Concrete points of friction, confusion, or surprise — what slowed you down or made you guess. Quote the exact tool name, parameter, or error text where possible.",+ "type": "string"+ },+ "sentiment": {+ "description": "Your overall impression of the MCP server for this task. Use \"positive\" if it helped you, \"negative\" if it blocked you, \"mixed\" for a bit of both.",+ "enum": ["positive", "negative", "mixed"],+ "type": "string"+ },+ "suggested_improvement": {+ "description": "The single most impactful change you would make to the MCP server right now. Be specific (e.g. \"add a `filters` example to query-funnel's description\").",+ "type": "string"+ },+ "summary": {+ "description": "A one-sentence headline summarising your feedback (e.g. \"query-trends descriptions made it hard to choose between trends and funnels\").",+ "minLength": 1,+ "type": "string"+ },+ "task_completed": {+ "description": "Were you able to complete the user's task using PostHog MCP tools? Be honest — \"false\" is just as useful as \"true\".",+ "type": "boolean"+ },+ "tools_used": {+ "description": "The tool names you called while working on the user's task (e.g. [\"read-data-schema\", \"query-trends\"]). Helps us correlate feedback to specific tools.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "user_request": {+ "description": "A short, anonymised paraphrase of what the user originally asked you to do. Do not include PII, customer names, or sensitive query content.",+ "type": "string"+ }+ },+ "required": ["summary", "sentiment", "category", "task_completed"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/custom-tool-handlers.test.ts b/services/mcp/tests/unit/custom-tool-handlers.test.tsindex e9137fc232fb..8a84f93599c6 100644--- a/services/mcp/tests/unit/custom-tool-handlers.test.ts+++ b/services/mcp/tests/unit/custom-tool-handlers.test.ts@@ -12,6 +12,7 @@ function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {sessionManager: {} as any,cache: {} as any,getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}}diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex d560886cdbac..ed1133747c37 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -287,6 +287,7 @@ describe('exec tool', () => {} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex e0efa0be920f..2e8b8607186f 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -11,6 +11,16 @@ import {} from '@/tools/toolDefinitions'import type { Context } from '@/tools/types'+/**+ * Returns every tool name that opts in to `always_available: true`.+ * Tests use this to assert that filtered results never drop these tools,+ * without hard-coding the exact set (which grows as utility tools are added).+ */+const collectAlwaysAvailableToolNames = (version?: number): string[] =>+ Object.entries(getToolDefinitions(version))+ .filter(([_, def]: [string, ToolDefinition]) => def.always_available === true)+ .map(([name]) => name)+describe('Tool Filtering - Features', () => {const featureTests = [{@@ -126,16 +136,54 @@ describe('Tool Filtering - Tools Allowlist', () => {expect(withEmptyTools).toEqual(allTools)})- it('should return only specified tools', () => {- const tools = getToolsForFeatures({ tools: ['dashboard-get', 'dashboard-create'] })+ it('should return only specified tools (plus always_available tools when enabled)', () => {+ const tools = getToolsForFeatures({+ tools: ['dashboard-get', 'dashboard-create'],+ featureFlags: { 'mcp-feedback-tool': true },+ })expect(tools).toContain('dashboard-get')expect(tools).toContain('dashboard-create')- expect(tools).toHaveLength(2)++ // always_available tools are included alongside the allowlist regardless of order+ // (when their gating feature flag is enabled).+ const alwaysAvailableTools = collectAlwaysAvailableToolNames()+ expect(tools).toContain('agent-feedback')++ // Every extra tool beyond the explicit allowlist must be always_available.+ const extras = tools.filter((name) => !['dashboard-get', 'dashboard-create'].includes(name))+ for (const extra of extras) {+ expect(alwaysAvailableTools).toContain(extra)+ }+ })++ it('should return only always_available tools for nonexistent tool names', () => {+ const tools = getToolsForFeatures({+ tools: ['nonexistent-tool'],+ featureFlags: { 'mcp-feedback-tool': true },+ })+ const alwaysAvailableTools = collectAlwaysAvailableToolNames()++ // The result is exactly the always_available set (order-independent).+ expect(tools).toContain('agent-feedback')+ expect(new Set(tools)).toEqual(new Set(alwaysAvailableTools))})- it('should return empty array for nonexistent tool names', () => {- const tools = getToolsForFeatures({ tools: ['nonexistent-tool'] })- expect(tools).toEqual([])+ it('should always include agent-feedback even when feature filter matches no tools', () => {+ const tools = getToolsForFeatures({+ features: ['nonexistent-feature'],+ featureFlags: { 'mcp-feedback-tool': true },+ })+ expect(tools).toContain('agent-feedback')+ })++ it('should hide agent-feedback when its gating feature flag is off', () => {+ // Flag explicitly off — tool is hidden even though it's always_available.+ const toolsWithFlagOff = getToolsForFeatures({ featureFlags: { 'mcp-feedback-tool': false } })+ expect(toolsWithFlagOff).not.toContain('agent-feedback')++ // No flags evaluated at all — also hidden (default behavior is `enable`).+ const toolsWithoutFlags = getToolsForFeatures({})+ expect(toolsWithoutFlags).not.toContain('agent-feedback')})it('should union with features (OR) when both are provided', () => {@@ -207,6 +255,7 @@ const createMockContext = (scopes: string[]): Context => ({} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},})describe('Tool Filtering - API Scopes', () => {@@ -273,25 +322,44 @@ describe('Tool Filtering - API Scopes', () => {it('should return only tools with no required scopes when user has no matching scopes', async () => {const context = createMockContext(['some:unknown'])- const tools = await getToolsFromContext(context)+ const tools = await getToolsFromContext(context, { featureFlags: { 'mcp-feedback-tool': true } })const toolNames = tools.map((t) => t.name)- // Only debug tool should be available since it has no required scopes+ // Only tools with no required scopes (or that bypass scope checks) should be available.expect(toolNames).toContain('debug-mcp-ui-apps')- expect(tools).toHaveLength(1)+ expect(toolNames).toContain('agent-feedback')+ expectAllToolsHaveNoRequiredScopes(toolNames)})it('should return only tools with no required scopes when user has empty scopes', async () => {const context = createMockContext([])- const tools = await getToolsFromContext(context)+ const tools = await getToolsFromContext(context, { featureFlags: { 'mcp-feedback-tool': true } })const toolNames = tools.map((t) => t.name)- // Only debug tool should be available since it has no required scopesexpect(toolNames).toContain('debug-mcp-ui-apps')- expect(tools).toHaveLength(1)+ expect(toolNames).toContain('agent-feedback')+ expectAllToolsHaveNoRequiredScopes(toolNames)})})+/**+ * Asserts that every tool in `toolNames` has an empty `required_scopes` array+ * in its definition. Used by the "user has no scopes" tests so they don't+ * break when a new no-scope utility tool is added.+ */+function expectAllToolsHaveNoRequiredScopes(toolNames: string[]): void {+ const definitions = getToolDefinitions()+ for (const name of toolNames) {+ const def = definitions[name]+ if (def === undefined) {+ // Hand-written tools like `insight-query` aren't always present in+ // the static definitions; the scope filter handles them separately.+ continue+ }+ expect(def.required_scopes).toEqual([])+ }+}+describe('OAUTH_SCOPES_SUPPORTED completeness', () => {it('should include every scope referenced in tool definitions', () => {const supportedScopes = new Set<string>(OAUTH_SCOPES_SUPPORTED)@@ -419,6 +487,7 @@ describe('Tool Filtering - AI Consent', () => {} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}const tools = await getToolsFromContext(context)const toolNames = tools.map((t) => t.name)@@ -444,6 +513,7 @@ describe('Tool Filtering - AI Consent', () => {} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}const tools = await getToolsFromContext(context)const toolNames = tools.map((t) => t.name)@@ -564,10 +634,16 @@ describe('Tool Filtering - Feature Flags', () => {it('getRequiredFeatureFlags should return flags used by current definitions', () => {const flags = getRequiredFeatureFlags()+ // Includes the gating flag for agent-feedback alongside the other gated tools.expect(flags).toEqual(- expect.arrayContaining(['logs-alerting', 'replay-video-based-summarization', 'visual-review'])+ expect.arrayContaining([+ 'logs-alerting',+ 'replay-video-based-summarization',+ 'visual-review',+ 'mcp-feedback-tool',+ ]))- expect(flags).toHaveLength(3)+ expect(flags).toHaveLength(4)})// Test the filtering logic with a direct unit test approach usingdiff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex bc9370569ae9..de65d5df1c76 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -27,6 +27,7 @@ function createMockContext(): Context {} as any,sessionManager: new SessionManager({} as any),getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},}}@@ -105,10 +106,14 @@ describe('Tool schema snapshots', () => {it('snapshots runtime tool schemas as common + version deltas', async () => {const shouldUpdateSnapshots = isSnapshotUpdateAll()const root = path.resolve(__dirname, '__snapshots__', 'tool-schemas')- const v1Tools = [...(await getToolsFromContext(context, { version: 1 }))].sort((a, b) =>+ // Enable the agent-feedback gating flag so its snapshot is captured. Other flag-gated+ // tools (logs-alerts, visual-review) remain excluded so this test stays scoped to the+ // tool surface that was previously snapshotted.+ const featureFlags = { 'mcp-feedback-tool': true }+ const v1Tools = [...(await getToolsFromContext(context, { version: 1, featureFlags }))].sort((a, b) =>a.name.localeCompare(b.name))- const v2Tools = [...(await getToolsFromContext(context, { version: 2 }))].sort((a, b) =>+ const v2Tools = [...(await getToolsFromContext(context, { version: 2, featureFlags }))].sort((a, b) =>a.name.localeCompare(b.name))