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.

fix(mcp): validate before no-data notice (#122685)

Fernando Gomes473cc381ba18
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index beb6d021d7b9..d04a1097034b 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -32,6 +32,7 @@ import {
buildNoDataInstallNotice,
githubConnectUrl,
MCP_NO_DATA_INSTALL_NOTICE_FLAG,
+ NoDataInstallNoticeError,
type NoDataNoticeMode,
prependNoDataNotice,
resolveNoDataNoticeMode,
@@ -97,6 +98,7 @@ interface ExecMetricState {
/** Which kind of skill lookup missed, when the dispatcher rewrote a 404. */
skillLookupMissKind: SkillLookupMissKind | undefined
resultEmpty: boolean
+ noDataNotice: { mode: NoDataNoticeMode; text: string } | undefined
}
/**
@@ -341,12 +343,32 @@ export class ToolExecutor {
return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }
}
+ const tool = preBuilt.build()
+ const rawToolArgs = (callParams.arguments ?? {}) as Record<string, unknown>
+ const firstPass = tool.schema.safeParse(rawToolArgs, { reportInput: true })
+ const rewrapped = firstPass.success
+ ? undefined
+ : repairArgumentNesting(firstPass.error, rawToolArgs, tool.schema)
+ const validation = rewrapped ? tool.schema.safeParse(rewrapped, { reportInput: true }) : firstPass
+ if (!validation.success) {
+ return this.callTool(
+ {
+ name: toolName,
+ schema: tool.schema,
+ handler: (ctx, args) => tool.handler(ctx, args),
+ _meta: tool._meta,
+ },
+ callParams,
+ state,
+ analyticsMeta
+ )
+ }
+
const noDataNotice = await this.noDataInstallNotice(toolName, state)
if (noDataNotice?.mode === 'block') {
return this.returnNoDataNotice(toolName, noDataNotice.text, state, {}, analyticsMeta)
}
- const tool = preBuilt.build()
const result = await this.callTool(
{
name: toolName,
@@ -625,25 +647,7 @@ export class ToolExecutor {
state: ResolvedState,
analyticsMeta?: ToolCallAnalyticsMeta
): Promise<unknown> {
- const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>
- const innerToolName =
- typeof toolArgs.command === 'string' ? parseExecCallInnerToolName(toolArgs.command) : undefined
- const noDataNotice = innerToolName ? await this.noDataInstallNotice(innerToolName, state) : undefined
- if (!innerToolName || !noDataNotice) {
- return this.runExecTool(params, state, analyticsMeta)
- }
- if (noDataNotice.mode === 'block') {
- const execShape = execCommandAnalyticsProperties(toolArgs, state)
- return this.returnNoDataNotice(
- innerToolName,
- noDataNotice.text,
- state,
- { ...execShape, ...execInputShapeAnalyticsProperties(toolArgs, execShape, state) },
- analyticsMeta
- )
- }
- const result = await this.runExecTool(params, { ...state, noDataAction: 'warned' }, analyticsMeta)
- return prependNoDataNotice(result, noDataNotice.text)
+ return this.runExecTool(params, state, analyticsMeta)
}
private async runExecTool(
@@ -657,6 +661,7 @@ export class ToolExecutor {
innerFailure: undefined,
skillLookupMissKind: undefined,
resultEmpty: false,
+ noDataNotice: undefined,
}
const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)
@@ -745,7 +750,7 @@ export class ToolExecutor {
execToolName(),
duration,
failureShape !== undefined,
- state,
+ execMetrics.noDataNotice ? { ...state, noDataAction: 'warned' } : state,
{
...execShape,
...execInputShape,
@@ -763,9 +768,18 @@ export class ToolExecutor {
this.servedToolDescription(execToolName())
)
- return response
+ return execMetrics.noDataNotice ? prependNoDataNotice(response, execMetrics.noDataNotice.text) : response
} catch (error: unknown) {
const metricTool = execToolName()
+ if (error instanceof NoDataInstallNoticeError) {
+ return this.returnNoDataNotice(
+ error.toolName,
+ error.text,
+ state,
+ { ...execShape, ...execInputShape },
+ analyticsMeta
+ )
+ }
const classification = classifyToolError(error, metricTool)
if (!execMetrics.innerToolName) {
// Match the inner-tool path, which labels rejected input `validation_error`.
@@ -998,6 +1012,13 @@ export class ToolExecutor {
trackCommand: (meta) => {
execMetrics.commandMeta = { ...execMetrics.commandMeta, ...meta }
},
+ beforeValidatedCall: async (toolName) => {
+ const noDataNotice = await this.noDataInstallNotice(toolName, state)
+ if (noDataNotice?.mode === 'block') {
+ throw new NoDataInstallNoticeError(toolName, noDataNotice.text)
+ }
+ execMetrics.noDataNotice = noDataNotice
+ },
}
)
diff --git a/services/mcp/src/lib/no-data-guard.ts b/services/mcp/src/lib/no-data-guard.ts
index 659a5eb39f37..73784b6effaa 100644
--- a/services/mcp/src/lib/no-data-guard.ts
+++ b/services/mcp/src/lib/no-data-guard.ts
@@ -4,6 +4,16 @@ export const MCP_NO_DATA_INSTALL_NOTICE_FLAG = 'mcp-no-data-install-notice'
export type NoDataNoticeMode = 'warn' | 'block'
export type NoDataAction = 'warned' | 'blocked'
+export class NoDataInstallNoticeError extends Error {
+ constructor(
+ public readonly toolName: string,
+ public readonly text: string
+ ) {
+ super(text)
+ this.name = 'NoDataInstallNoticeError'
+ }
+}
+
export function noDataNoticeMode(variant: FlagValue): NoDataNoticeMode | undefined {
return variant === 'warn' || variant === 'block' ? variant : undefined
}
@@ -66,7 +76,12 @@ export function buildNoDataInstallNotice({
// A separate content block keeps the tool's own text intact, so a `--json` result still parses.
export function prependNoDataNotice(result: unknown, notice: string): unknown {
- if (typeof result !== 'object' || result === null || !Array.isArray((result as { content?: unknown }).content)) {
+ if (
+ typeof result !== 'object' ||
+ result === null ||
+ (result as { isError?: unknown }).isError === true ||
+ !Array.isArray((result as { content?: unknown }).content)
+ ) {
return result
}
const withContent = result as { content: unknown[] }
diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.ts
index 132675ec544e..4dcd550ec6b5 100644
--- a/services/mcp/src/tools/exec.ts
+++ b/services/mcp/src/tools/exec.ts
@@ -263,6 +263,7 @@ export interface ExecToolOptions {
* set is refused as `tool_not_granted`, so the agent does not search for another way to reach it.
*/
heldTools?: ReadonlySet<string>
+ beforeValidatedCall?: (toolName: string, input: Record<string, unknown>) => Promise<void>
}
const CALL_USAGE = 'Usage: call [--json] [--confirm] <tool_name> [json_input]'
@@ -2119,6 +2120,7 @@ export function createExecTool(
}
const ignoredKeys = findIgnoredInputKeys(input, validation.data, toolSchema)
input = validation.data as Record<string, unknown>
+ await options.beforeValidatedCall?.(tool.name, input)
const startedAt = Date.now()
let result: unknown
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 1d37405a49e8..8adf22ace4bb 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -264,8 +264,6 @@ describe('ToolExecutor', () => {
it.each<Row>([
{ mode: 'direct', tool: 'query-trends', ...block, outcome: 'blocked' },
{ mode: 'exec', tool: 'query-trends', ...block, outcome: 'blocked' },
- { mode: 'direct', tool: 'query-trends', ...warn, outcome: 'warned' },
- { mode: 'exec', tool: 'query-trends', ...warn, outcome: 'warned' },
// Direct mode, because exec looks up every roster entry in the static tool registry,
// and `wizard-install-start` may not be registered there.
{ mode: 'direct', tool: 'query-trends', ...block, withInstallTool: true, outcome: 'blocked' },
@@ -275,11 +273,6 @@ describe('ToolExecutor', () => {
{ mode: 'direct', tool: 'query-trends', projectHasData: undefined, variant: 'block', outcome: 'none' },
{ mode: 'exec', tool: 'docs-search', ...block, outcome: 'none' },
{ mode: 'exec', tool: 'docs-search', ...warn, outcome: 'none' },
- { mode: 'direct', tool: 'query-logs', ...block, outcome: 'blocked' },
- { mode: 'direct', tool: 'execute-sql', ...block, hasWarehouseData: false, outcome: 'blocked' },
- { mode: 'exec', tool: 'execute-sql', ...block, hasWarehouseData: true, outcome: 'none' },
- { mode: 'exec', tool: 'execute-sql', ...warn, hasWarehouseData: true, outcome: 'none' },
- { mode: 'exec', tool: 'execute-sql', ...block, hasWarehouseData: undefined, outcome: 'none' },
{ mode: 'exec', tool: 'query-trends', ...block, overrides: { isImpersonated: true }, outcome: 'none' },
{ mode: 'direct', tool: 'query-trends', ...warn, overrides: { isImpersonated: true }, outcome: 'none' },
{
@@ -318,10 +311,12 @@ describe('ToolExecutor', () => {
} as any,
...overrides,
})
+ const argumentsForTool =
+ tool === 'query-trends' ? { series: [{ kind: 'EventsNode', event: '$pageview' }] } : {}
const call =
mode === 'exec'
- ? { name: 'exec', arguments: { command: `call ${tool} {}` } }
- : { name: tool, arguments: {} }
+ ? { name: 'exec', arguments: { command: `call ${tool} ${JSON.stringify(argumentsForTool)}` } }
+ : { name: tool, arguments: argumentsForTool }
const result = (await executor.handleToolCall(call, state)) as any
const text: string = result.content?.[0]?.text ?? ''
@@ -344,6 +339,34 @@ describe('ToolExecutor', () => {
}
}
)
+
+ it.each([
+ ['direct', 'warn'],
+ ['direct', 'block'],
+ ['exec', 'warn'],
+ ['exec', 'block'],
+ ])('returns the validation error before the no-data notice for a %s %s call', async (mode, variant) => {
+ const tool = 'query-trends'
+ const roster = catalog.getFilteredTools({ scopes: ['*'] }).filter((entry) => entry.name === tool)
+ const baseContext = makeToolExecutorState([]).context
+ const state = makeToolExecutorState(roster, {
+ useSingleExec: mode === 'exec',
+ projectHasData: false,
+ toolFeatureFlags: { [MCP_NO_DATA_INSTALL_NOTICE_FLAG]: variant },
+ context: {
+ ...baseContext,
+ stateManager: { getProjectId: vi.fn().mockResolvedValue('7') },
+ } as any,
+ })
+ const call =
+ mode === 'exec'
+ ? { name: 'exec', arguments: { command: `call ${tool} {}` } }
+ : { name: tool, arguments: {} }
+
+ const result = (await executor.handleToolCall(call, state)) as any
+
+ expect(result.content[0].text).not.toContain("hasn't received any events yet")
+ })
})
describe('handleToolsList', () => {