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.

feat(mcp): derive scopes and annotations, add tools.yaml hooks (#111811)

Julian Bez1aa2183aa49c
diff --git a/.agents/skills/implementing-mcp-tools/SKILL.md b/.agents/skills/implementing-mcp-tools/SKILL.md
index 95dc863640ab..76847e0c05a0 100644
--- a/.agents/skills/implementing-mcp-tools/SKILL.md
+++ b/.agents/skills/implementing-mcp-tools/SKILL.md
@@ -18,7 +18,8 @@ Read the full guide at [docs/published/handbook/engineering/ai/implementing-mcp-
pnpm --filter=@posthog/mcp run scaffold-yaml -- --product your_product \
--output ../../products/your_product/mcp/tools.yaml
-# 2. Configure the YAML — enable tools, add scopes, annotations, descriptions
+# 2. Configure the YAML — enable tools, add descriptions, and annotations for PATCH/POST/PUT
+# (scopes come from the API when omitted)
# Place in products/<product>/mcp/*.yaml (preferred) or services/mcp/definitions/*.yaml
# 3. Add a HogQL system table in posthog/hogql/database/schema/system.py
@@ -149,13 +150,13 @@ tools:
your-tool-name: # kebab-case
operation: operationId_from_openapi
enabled: true
- scopes:
+ # Optional:
+ scopes: # defaults to the scopes the API requires (from the OpenAPI spec)
- your_product:read
- annotations:
+ annotations: # defaults for GET and DELETE; required for PATCH, POST and PUT
readOnly: true
destructive: false
idempotent: true
- # Optional:
title: List things
description: >
Human-friendly description for the LLM.
@@ -178,6 +179,15 @@ tools:
feature_flag_behavior: enable # 'enable' (default) or 'disable'
```
+When `scopes` is omitted, the generator uses the scopes the API requires, so the tool cannot drift from the endpoint.
+Set `scopes` by hand only when the API computes them per request (the generator fails and says so) or to gate a tool more tightly.
+A `scopes` list that misses a scope the API requires prints a warning, and a GitHub annotation on CI.
+`annotations` default to the HTTP method for GET (read-only) and DELETE (destructive).
+PATCH, POST and PUT vary too much (a PATCH can be a soft delete or non-idempotent), so declare `annotations` for them.
+
+When a tool needs custom logic around the request, set `hooks: <path under src/tools/>` and default-export an object with `beforeRequest`, `afterResponse` or `onError` from that module, written `export default { onError } satisfies ToolHooks<Params>` so a typo fails typecheck (see `ToolHooks` in `src/tools/tool-hooks.ts`).
+Use it to read state before a write or to turn a known error into a result, rather than shadowing the generated tool with a hand-written one.
+
Unknown keys are rejected at build time (Zod `.strict()`).
### Gating tools with feature flags
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 8a1737a12682..75fa9135be73 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -18,7 +18,7 @@ see [Writing skills](/handbook/engineering/ai/writing-skills).
pnpm --filter=@posthog/mcp run scaffold-yaml -- --product your_product \
--output ../../products/your_product/mcp/tools.yaml
-# 2. Configure the YAML – enable tools, add scopes, annotations, descriptions
+# 2. Configure the YAML – enable tools, add descriptions, and annotations for PATCH/POST/PUT
# Place in products/<product>/mcp/*.yaml (preferred, e.g. actions, cohorts)
# 3. For read/list tools backed by PostHog database rows, add a HogQL system table
@@ -252,7 +252,8 @@ Product teams own their definitions and control which operations are exposed as
--output ../../products/your_product/mcp/tools.yaml
```
-2. **Configure** the YAML – enable tools, add scopes, annotations, and descriptions.
+2. **Configure** the YAML – enable tools and add descriptions.
+ Scopes come from the API when you omit them. Annotations default for GET and DELETE, so declare them for PATCH, POST and PUT.
Each YAML file has a top-level structure validated by Zod ([`scripts/yaml-config-schema.ts`](https://github.com/PostHog/posthog/blob/master/services/mcp/scripts/yaml-config-schema.ts)):
**Tool names** follow a **`domain-action`** convention in lowercase kebab-case (`[a-z0-9-]`),
@@ -285,14 +286,13 @@ Product teams own their definitions and control which operations are exposed as
domain-action: # e.g. feature-flags-list, experiments-create
operation: your_product_endpoint_list # must match an OpenAPI operationId
enabled: true # false excludes from generation
- # --- required when enabled: ---
- scopes: # API scopes
+ # --- optional: ---
+ scopes: # defaults to the scopes the API requires; a list that misses one warns
- your_product:read
- annotations:
+ annotations: # defaults for GET and DELETE; required for PATCH, POST and PUT
readOnly: true
destructive: false
idempotent: true
- # --- optional: ---
title: List things # human-friendly title (used in UI)
description: > # instructions for the LLM
Human-friendly description for the LLM.
@@ -356,35 +356,34 @@ Product teams own their definitions and control which operations are exposed as
The generated code uses `.extend()` to replace just that field.
See [supported annotations](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations) for the full list.
- #### Hand-written override of a generated tool
+ #### Hooks for custom request logic
The two overrides above reshape a generated tool's schema.
- Neither can change what happens before the request goes out.
+ Neither can change what happens around the request.
`validators` runs as a synchronous `superRefine`, so it cannot await anything;
`inject_body` supplies static values; `rename_params` only renames.
- When a tool has to read current state before writing, export a hand-written tool under the generated tool's own name.
- `mergeToolFactories` gives hand-written entries precedence on a name collision, so the hand-written tool replaces the generated one everywhere:
- the Hono catalog, the CLI, `getToolsFromContext`, and `posthog-connection-call`.
+ When a tool has to read current state before writing, or handle a specific error, set `hooks:` on the tool.
+ The value is a module path relative to `src/tools/`, without the extension:
- `src/tools/featureFlags/updateFeatureFlag.ts` is the reference.
- It spreads the generated tool so the name, schema and any field codegen adds later carry over, replaces only the handler, and delegates back to the generated handler to make the request:
+ ```yaml
+ update-feature-flag:
+ operation: feature_flags_partial_update
+ enabled: true
+ hooks: featureFlags/updateFeatureFlagHooks
+ ```
- ```ts
- const generated = GENERATED_TOOLS['update-feature-flag']!()
+ The module default-exports an object with any of these functions, written `export default { beforeRequest } satisfies ToolHooks<Params>` so a misspelled name fails typecheck:
- return {
- ...generated,
- handler: async (context, params) => {
- const existing = await context.api.request({ method: 'GET', path: `...` })
- return generated.handler(context, { ...params, filters: merge(existing, params.filters) })
- },
- }
- ```
+ - `beforeRequest(context, params)` returns the params the request should use.
+ - `afterResponse(context, params, result)` returns the result to send to the client.
+ - `onError(context, params, error)` returns a result that handles the error, or rethrows it.
- Reach for this only when a read-modify-write is genuinely needed.
- Every override is a name collision that has to stay deliberate, which `tests/unit/tool-name-validation.test.ts` enforces by pinning the set of shadowed names.
- If a second tool needs the same treatment, add support for a `before_request:` hook to the YAML config instead of a second shadow.
+ Codegen wraps the generated handler with them, so the name, schema and metadata stay generated.
+ A `beforeRequest` that throws stops the request, and `onError` does not see that error.
+ `hooks` cannot be combined with `confirmed_action`.
+ `src/tools/featureFlags/updateFeatureFlagHooks.ts` is the reference.
+ Do not shadow a generated tool with a hand-written tool of the same name.
#### Typed-confirm paradigm for destructive tools
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index b24a515615d5..fe3103931a8e 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -972,3 +972,4 @@ tools:
description:
Identifier used to bucket users into rollout percentages and variants — `distinct_id` (user ID, the
default) or `device_id`. Using `device_id` is incompatible with `ensure_experience_continuity=true`.
+ hooks: featureFlags/updateFeatureFlagHooks
diff --git a/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py b/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py
index 8e81008b2717..16772b7ee528 100644
--- a/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_feature_flags_scorers.py
@@ -11,7 +11,6 @@ from posthog.test.base import BaseTest
from django.conf import settings
-import yaml
from parameterized import parameterized
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -98,17 +97,19 @@ def test_flag_lookup_tools_match_mcp_names_the_parser_normalizes(tool: str) -> N
def _declared_tools() -> dict[str, Any]:
- tools_yaml = Path(settings.BASE_DIR) / "products/feature_flags/mcp/tools.yaml"
- return yaml.safe_load(tools_yaml.read_text())["tools"]
+ # tools.yaml may omit annotations (GET, DELETE and PATCH default), so read the generated
+ # definitions, which hold the resolved values for every enabled tool.
+ generated = json.loads(
+ (Path(settings.BASE_DIR) / "services/mcp/schema/generated-tool-definitions.json").read_text()
+ )
+ return {name: spec for name, spec in generated.items() if spec["feature"] == "flags"}
def test_flag_mutation_tools_match_the_declared_write_surface() -> None:
# FLAG_MUTATION_TOOLS is a literal so the guarded set stays a reviewed choice, but a
# write verb added to tools.yaml must not slip past the suite silently. Bind the two.
declared_write_verbs = {
- name
- for name, spec in _declared_tools().items()
- if spec.get("enabled") and spec.get("annotations", {}).get("readOnly") is False
+ name for name, spec in _declared_tools().items() if spec["annotations"]["readOnlyHint"] is False
}
assert FLAG_MUTATION_TOOLS == declared_write_verbs
@@ -127,7 +128,7 @@ def test_read_tool_sets_name_enabled_read_only_tools() -> None:
if spec is None:
assert name in hand_written, name
continue
- assert spec.get("enabled") and spec.get("annotations", {}).get("readOnly") is True, name
+ assert spec["annotations"]["readOnlyHint"] is True, name
class TestFlagStateUnchanged(BaseTest):
diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yaml
index 542f9f3dcc51..d4454b33148d 100644
--- a/products/replay/mcp/tools.yaml
+++ b/products/replay/mcp/tools.yaml
@@ -74,6 +74,7 @@ tools:
`$sdk_debug_recording_script_not_loaded` from the events table (filter by `$session_id` for a specific
session, or sample recent events for project-wide issues).
ui_app: session-recording
+ hooks: replay/sessionRecordingGetHooks
response:
exclude:
- person.properties
diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.ts
index c1f59a208609..39bf072169b9 100644
--- a/services/mcp/scripts/generate-tools.ts
+++ b/services/mcp/scripts/generate-tools.ts
@@ -21,6 +21,7 @@ import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parse as parseYaml } from 'yaml'
+import { hasScope } from '../src/lib/api'
import { discoverDefinitions, isQueryWrappersConfig } from './lib/definitions.mjs'
import { type JsonSchemaRoot, generateZodFromSchemaRef, getEntryVarName } from './lib/json-schema-to-zod'
import {
@@ -37,6 +38,7 @@ const MCP_ROOT = path.resolve(__dirname, '..')
const REPO_ROOT = path.resolve(MCP_ROOT, '../..')
const DEFINITIONS_DIR = path.resolve(MCP_ROOT, 'definitions')
const PRODUCTS_DIR = path.resolve(REPO_ROOT, 'products')
+const TOOLS_SRC_DIR = path.resolve(MCP_ROOT, 'src/tools')
const GENERATED_DIR = path.resolve(MCP_ROOT, 'src/tools/generated')
const DEFINITIONS_JSON_PATH = path.resolve(MCP_ROOT, 'schema/generated-tool-definitions.json')
const ALL_DEFINITIONS_JSON_PATH = path.resolve(MCP_ROOT, 'schema/tool-definitions-all.json')
@@ -87,6 +89,8 @@ interface OpenApiSchema {
interface OpenApiOperation {
operationId: string
+ /** Scopes the API requires, written by `posthog/api/documentation.py`. */
+ security?: Array<Record<string, string[]>>
parameters?: OpenApiParam[]
requestBody?: {
content?: {
@@ -1070,6 +1074,17 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar
// ------------------------------------------------------------------
// Code generation for a single tool
+
+// The underscore keeps the alias apart from factory names, which are camelCase without underscores.
+function hooksVarName(toolName: string): string {
+ return `hooks_${toCamelCase(toolName)}`
+}
+
+/** Emits the handler expression, wrapped with the tool's `hooks:` module when it has one. */
+function renderHandler(config: ToolConfig, toolName: string, handlerFn: string): string {
+ return config.hooks ? `withToolHooks(${hooksVarName(toolName)}, ${handlerFn})` : handlerFn
+}
+
// ------------------------------------------------------------------
function generateToolCode(
@@ -1343,8 +1358,12 @@ function generateToolCode(
const toolBody = `{
name: '${toolName}',
schema: ${schemaName}(),
- handler: async (context: Context, ${paramsName}: z.infer<ReturnType<typeof ${schemaName}>>) => {
-${handlerBody} },
+ handler: ${renderHandler(
+ config,
+ toolName,
+ `async (context: Context, ${paramsName}: z.infer<ReturnType<typeof ${schemaName}>>) => {
+${handlerBody} }`
+ )},
}`
const factoryBody = appKey ? `withUiApp('${appKey}', ${toolBody})` : `(${toolBody})`
@@ -1658,8 +1677,12 @@ const ${schemaName} = () => ${baseSchemaExpr}
const ${factoryName} = (): ToolBase<ReturnType<typeof ${schemaName}>, ${customResultType}> => ({
name: '${toolName}',
schema: ${schemaName}(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof ${schemaName}>>) => {
-${handlerBody} },
+ handler: ${renderHandler(
+ config,
+ toolName,
+ `async (context: Context, params: z.infer<ReturnType<typeof ${schemaName}>>) => {
+${handlerBody} }`
+ )},
})
`
@@ -1685,6 +1708,80 @@ ${handlerBody} },
}
}
+// ------------------------------------------------------------------
+// Scope and annotation resolution
+// ------------------------------------------------------------------
+
+type ToolAnnotations = EnabledToolConfig['annotations']
+
+// Only methods whose behavior is the same for every endpoint get defaults.
+// PATCH, POST and PUT vary too much (partial update vs. soft delete, search vs. create vs. upsert),
+// so authors declare them.
+const ANNOTATION_DEFAULTS_BY_METHOD: Record<string, ToolAnnotations> = {
+ GET: { readOnly: true, destructive: false, idempotent: true },
+ DELETE: { readOnly: false, destructive: true, idempotent: true },
+}
+
+function getSpecScopes(operation: OpenApiOperation): string[] {
+ const scopes = new Set<string>()
+ for (const requirement of operation.security ?? []) {
+ for (const requirementScopes of Object.values(requirement)) {
+ for (const scope of requirementScopes) {
+ scopes.add(scope)
+ }
+ }
+ }
+ return [...scopes]
+}
+
+/** YAML `scopes` win. Without them, the scopes the API itself requires are used. */
+function resolveToolScopes(name: string, config: ToolConfig, resolved: ResolvedOperation): string[] {
+ if (config.scopes?.length) {
+ return config.scopes
+ }
+ const specScopes = getSpecScopes(resolved.operation)
+ if (specScopes.length === 0) {
+ throw new Error(
+ `Enabled tool "${name}" has no "scopes" and the OpenAPI spec lists none for "${resolved.operation.operationId}" ` +
+ `(the API computes them per request). Add "scopes" to the tool's YAML by hand.`
+ )
+ }
+ return specScopes
+}
+
+/** YAML `annotations` win. Without them, GET and DELETE get fixed defaults. */
+function resolveToolAnnotations(name: string, config: ToolConfig, method: string): ToolAnnotations {
+ if (config.annotations) {
+ return config.annotations
+ }
+ const defaults = ANNOTATION_DEFAULTS_BY_METHOD[method]
+ if (!defaults) {
+ throw new Error(
+ `Enabled tool "${name}" is missing required "annotations". ` +
+ `${method} endpoints have no defaults, so declare readOnly, destructive and idempotent in the tool's YAML.`
+ )
+ }
+ return { ...defaults }
+}
+
+/** Scopes the API requires that the YAML list leaves out. A `:write` scope covers `:read`, as at runtime. Empty when the YAML has no list or the spec has none. */
+function findMissingSpecScopes(config: ToolConfig, resolved: ResolvedOperation): string[] {
+ if (!config.scopes?.length) {
+ return []
+ }
+ return getSpecScopes(resolved.operation).filter((scope) => !hasScope(config.scopes ?? [], scope))
+}
+
+function reportMissingSpecScopes(name: string, yamlLabel: string, missingScopes: string[]): void {
+ const message =
+ `Tool "${name}" does not list the scope(s) the API requires: ${missingScopes.join(', ')}. ` +
+ `A token without them sees the tool and then gets a 403. Add them to "scopes" or drop "scopes" to use the API's.`
+ process.stdout.write(`WARNING ${yamlLabel}: ${message}\n`)
+ if (process.env.GITHUB_ACTIONS === 'true') {
+ process.stdout.write(`::warning file=${yamlLabel}::${message}\n`)
+ }
+}
+
// ------------------------------------------------------------------
// Generate a full category file
// ------------------------------------------------------------------
@@ -1707,14 +1804,6 @@ function generateCategoryFile(
if (!config.enabled) {
continue
}
- if (!config.scopes?.length) {
- console.error(`Enabled tool "${name}" is missing required "scopes"`)
- process.exit(1)
- }
- if (!config.annotations) {
- console.error(`Enabled tool "${name}" is missing required "annotations"`)
- process.exit(1)
- }
const resolved = findOperation(spec, config.operation)
if (!resolved) {
console.error(
@@ -1723,7 +1812,31 @@ function generateCategoryFile(
)
process.exit(1)
}
- enabledTools.push([name, config as EnabledToolConfig, resolved])
+ if (config.hooks && !fs.existsSync(path.join(TOOLS_SRC_DIR, `${config.hooks}.ts`))) {
+ console.error(
+ `Enabled tool "${name}": hooks module "${config.hooks}" not found. ` +
+ `Expected services/mcp/src/tools/${config.hooks}.ts. Fix "hooks:" in the tool's YAML or create the module.`
+ )
+ process.exit(1)
+ }
+ const missingScopes = findMissingSpecScopes(config, resolved)
+ if (missingScopes.length > 0) {
+ reportMissingSpecScopes(name, fileName, missingScopes)
+ }
+ try {
+ enabledTools.push([
+ name,
+ {
+ ...config,
+ scopes: resolveToolScopes(name, config, resolved),
+ annotations: resolveToolAnnotations(name, config, resolved.method),
+ },
+ resolved,
+ ])
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error))
+ process.exit(1)
+ }
}
// Collect enabled query wrappers from the optional wrappers section
@@ -1968,6 +2081,15 @@ function generateCategoryFile(
toolUtilsImportLine = `import type { ${toolUtilsTypeImports.join(', ')} } from '@/tools/tool-utils'\n`
}
+ const hookedTools = enabledTools.filter(([, toolConfig]) => toolConfig.hooks)
+ const hooksImportLines =
+ hookedTools.length > 0
+ ? `import { withToolHooks } from '@/tools/tool-hooks'\n` +
+ hookedTools
+ .map(([name, toolConfig]) => `import ${hooksVarName(name)} from '@/tools/${toolConfig.hooks}'\n`)
+ .join('')
+ : ''
+
const wrapperImportLine =
enabledWrappers.length > 0 ? `import { createQueryWrapper } from '@/tools/query-wrapper-factory'\n` : ''
@@ -1981,7 +2103,7 @@ function generateCategoryFile(
import { z } from 'zod'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${castHelpersImportLine}${wrapperImportLine}${confirmedActionImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}
+${toolUtilsImportLine ? `${toolUtilsImportLine}` : ''}${schemasImportLine}${withUiAppImportLine}${toolInputsImportLine}${castHelpersImportLine}${wrapperImportLine}${hooksImportLines}${confirmedActionImportLine}${orvalImportLine}${schemaRefCode}${toolCodes.join('')}${wrapperSchemasCode}
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
${mapEntries}
}
@@ -2501,6 +2623,11 @@ export {
generateQueryWrapperDefinitionsJson,
generateQueryWrapperFile,
generateToolCode,
+ findMissingSpecScopes,
+ getSpecScopes,
+ reportMissingSpecScopes,
+ resolveToolAnnotations,
+ resolveToolScopes,
}
export type { OpenApiSpec, ResolvedOperation }
diff --git a/services/mcp/scripts/yaml-config-schema.ts b/services/mcp/scripts/yaml-config-schema.ts
index bc1672c6c98b..5138ec8710cc 100644
--- a/services/mcp/scripts/yaml-config-schema.ts
+++ b/services/mcp/scripts/yaml-config-schema.ts
@@ -153,6 +153,15 @@ export const ToolConfigSchema = z
required_when_set: z.record(z.string(), z.array(z.string())).optional(),
/** References a key in ui_apps. */
ui_app: z.string().optional(),
+ /**
+ * Module with custom request logic, relative to `src/tools/` and without extension
+ * (e.g. `featureFlags/updateFeatureFlagHooks`). Its default export is an object with
+ * `beforeRequest`, `afterResponse` and `onError`; see `ToolHooks` in `src/tools/tool-hooks.ts`.
+ */
+ hooks: z
+ .string()
+ .regex(/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/, 'hooks must be a path like "featureFlags/myToolHooks"')
+ .optional(),
/**
* When true or a string, the tool issues PATCH instead of DELETE.
* `true` sends `{ deleted: true }` (for ForbidDestroyModel endpoints).
@@ -336,6 +345,13 @@ export const ToolConfigSchema = z
'`confirmed_action` cannot be combined with `ui_app` yet — the codegen does not wrap the generated -execute factory with withUiApp. Drop one or extend buildConfirmedActionFactories to opt in.',
path: ['confirmed_action'],
})
+ // The confirmed-action codegen builds its own prepare/execute handlers, so hooks would
+ // wrap neither of them.
+ .refine((data) => !(data.confirmed_action && data.hooks), {
+ message:
+ '`confirmed_action` cannot be combined with `hooks` yet — the prepare and execute handlers are not wrapped.',
+ path: ['confirmed_action'],
+ })
export type ToolConfig = z.infer<typeof ToolConfigSchema>
diff --git a/services/mcp/src/tools/README.md b/services/mcp/src/tools/README.md
index 8de748a4baa7..f8164db1f79b 100644
--- a/services/mcp/src/tools/README.md
+++ b/services/mcp/src/tools/README.md
@@ -4,6 +4,7 @@ This guide covers hand-written tools only.
Most tools are generated from `products/<product>/mcp/tools.yaml`.
For those, follow the [implementing MCP tools skill](../../../../.agents/skills/implementing-mcp-tools/SKILL.md) and the [handbook guide](../../../../docs/published/handbook/engineering/ai/implementing-mcp-tools.md).
+To change a generated tool's request or error handling, use `hooks:` in its tools.yaml instead of a hand-written tool with the same name.
Write a tool by hand only when codegen cannot express it.
Examples are tools that call several endpoints or reshape the response.
Existing hand-written tools live in the folders next to this file, for example `featureFlags/`.
diff --git a/services/mcp/src/tools/featureFlags/updateFeatureFlag.ts b/services/mcp/src/tools/featureFlags/updateFeatureFlag.ts
deleted file mode 100644
index 60e64542fde8..000000000000
--- a/services/mcp/src/tools/featureFlags/updateFeatureFlag.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Hand-written override of generated `update-feature-flag`. It intercepts only
- * `filters`, to preserve group targeting (PostHog/posthog#46501), and delegates
- * everything else to the codegen factory. Re-sync is needed only if the generated
- * tool name or the `filters` param shape changes.
- *
- * Title, description, and scopes still resolve from the generated
- * `update-feature-flag` entry, not from this file.
- */
-import type { Schemas } from '@/api/generated'
-import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'
-import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-
-import { preserveGroupTargetingFilters, type FlagFilters } from './preserveGroupTargeting'
-
-type UpdateParams = {
- id: number | string
- filters?: FlagFilters
- [key: string]: unknown
-}
-
-export default function updateFeatureFlagPreservingGroups(): ToolBase<ZodObjectAny> {
- const generated = GENERATED_TOOLS['update-feature-flag']!()
-
- return {
- // Spreading the generated tool carries over any field codegen adds later.
- ...generated,
- handler: async (context: Context, params: UpdateParams) => {
- if (params.filters === undefined) {
- return generated.handler(context, params)
- }
-
- // No try/catch: a failed GET must abort before the PATCH. PATCHing raw
- // filters without the merge is what silently demotes group flags.
- const projectId = await context.stateManager.getProjectId()
- const existing = await context.api.request<Schemas.FeatureFlag>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,
- })
- const existingFilters = (existing?.filters ?? undefined) as FlagFilters | undefined
- const mergedFilters = preserveGroupTargetingFilters(existingFilters, params.filters)
-
- return generated.handler(context, { ...params, filters: mergedFilters })
- },
- }
-}
diff --git a/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts b/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts
new file mode 100644
index 000000000000..006121b7c1a2
--- /dev/null
+++ b/services/mcp/src/tools/featureFlags/updateFeatureFlagHooks.ts
@@ -0,0 +1,36 @@
+/**
+ * Hooks for the generated `update-feature-flag` tool. They intercept only `filters`, to
+ * preserve group targeting (PostHog/posthog#46501), and leave everything else to the
+ * generated handler. Re-sync is needed only if the `filters` param shape changes.
+ */
+import type { Schemas } from '@/api/generated'
+import type { ToolHooks } from '@/tools/tool-hooks'
+import type { Context } from '@/tools/types'
+
+import { preserveGroupTargetingFilters, type FlagFilters } from './preserveGroupTargeting'
+
+type UpdateParams = {
+ id: number | string
+ filters?: FlagFilters | null
+ [key: string]: unknown
+}
+
+async function beforeRequest<T extends UpdateParams>(context: Context, params: T): Promise<T> {
+ if (params.filters === undefined) {
+ return params
+ }
+
+ // No try/catch: a failed GET must abort before the PATCH. PATCHing raw
+ // filters without the merge is what silently demotes group flags.
+ const projectId = await context.stateManager.getProjectId()
+ const existing = await context.api.request<Schemas.FeatureFlag>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,
+ })
+ const existingFilters = (existing?.filters ?? undefined) as FlagFilters | undefined
+ const mergedFilters = preserveGroupTargetingFilters(existingFilters, params.filters)
+
+ return { ...params, filters: mergedFilters }
+}
+
+export default { beforeRequest } satisfies ToolHooks<UpdateParams>
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index 9c0b9c18f34e..88d8df12dd49 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -6,6 +6,8 @@ import * as orvalSchemas from '@/generated/feature_flags/api'
import { withUiApp } from '@/resources/ui-apps'
import { validateDistinctIdPersonIdExclusive } from '@/schema/tool-inputs'
import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'
+import hooks_updateFeatureFlag from '@/tools/featureFlags/updateFeatureFlagHooks'
+import { withToolHooks } from '@/tools/tool-hooks'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -1007,49 +1009,52 @@ const updateFeatureFlag = (): ToolBase<
> => ({
name: 'update-feature-flag',
schema: UpdateFeatureFlagSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof UpdateFeatureFlagSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.key !== undefined) {
- body['key'] = params.key
- }
- if (params.name !== undefined) {
- body['name'] = params.name
- }
- if (params.filters !== undefined) {
- body['filters'] = params.filters
- }
- if (params.active !== undefined) {
- body['active'] = params.active
- }
- if (params.archived !== undefined) {
- body['archived'] = params.archived
- }
- if (params.tags !== undefined) {
- body['tags'] = params.tags
- }
- if (params.evaluation_contexts !== undefined) {
- body['evaluation_contexts'] = params.evaluation_contexts
- }
- if (params.is_remote_configuration !== undefined) {
- body['is_remote_configuration'] = params.is_remote_configuration
- }
- if (params.ensure_experience_continuity !== undefined) {
- body['ensure_experience_continuity'] = params.ensure_experience_continuity
- }
- if (params.evaluation_runtime !== undefined) {
- body['evaluation_runtime'] = params.evaluation_runtime
- }
- if (params.bucketing_identifier !== undefined) {
- body['bucketing_identifier'] = params.bucketing_identifier
+ handler: withToolHooks(
+ hooks_updateFeatureFlag,
+ async (context: Context, params: z.infer<ReturnType<typeof UpdateFeatureFlagSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.key !== undefined) {
+ body['key'] = params.key
+ }
+ if (params.name !== undefined) {
+ body['name'] = params.name
+ }
+ if (params.filters !== undefined) {
+ body['filters'] = params.filters
+ }
+ if (params.active !== undefined) {
+ body['active'] = params.active
+ }
+ if (params.archived !== undefined) {
+ body['archived'] = params.archived
+ }
+ if (params.tags !== undefined) {
+ body['tags'] = params.tags
+ }
+ if (params.evaluation_contexts !== undefined) {
+ body['evaluation_contexts'] = params.evaluation_contexts
+ }
+ if (params.is_remote_configuration !== undefined) {
+ body['is_remote_configuration'] = params.is_remote_configuration
+ }
+ if (params.ensure_experience_continuity !== undefined) {
+ body['ensure_experience_continuity'] = params.ensure_experience_continuity
+ }
+ if (params.evaluation_runtime !== undefined) {
+ body['evaluation_runtime'] = params.evaluation_runtime
+ }
+ if (params.bucketing_identifier !== undefined) {
+ body['bucketing_identifier'] = params.bucketing_identifier
+ }
+ const result = await context.api.request<Schemas.FeatureFlag>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/feature_flags/${result.id}`)
}
- const result = await context.api.request<Schemas.FeatureFlag>({
- method: 'PATCH',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/`,
- body,
- })
- return await withPostHogUrl(context, result, `/feature_flags/${result.id}`)
- },
+ ),
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
diff --git a/services/mcp/src/tools/generated/replay.ts b/services/mcp/src/tools/generated/replay.ts
index 71c1f9129a1f..16e7cdbf0326 100644
--- a/services/mcp/src/tools/generated/replay.ts
+++ b/services/mcp/src/tools/generated/replay.ts
@@ -5,6 +5,8 @@ import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/replay/api'
import { withUiApp } from '@/resources/ui-apps'
import { createQueryWrapper } from '@/tools/query-wrapper-factory'
+import hooks_sessionRecordingGet from '@/tools/replay/sessionRecordingGetHooks'
+import { withToolHooks } from '@/tools/tool-hooks'
import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -67,15 +69,18 @@ const sessionRecordingGet = (): ToolBase<
withUiApp('session-recording', {
name: 'session-recording-get',
schema: SessionRecordingGetSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof SessionRecordingGetSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.SessionRecording>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recordings/${encodeURIComponent(String(params.id))}/`,
- })
- const filtered = omitResponseFields(result, ['person.properties']) as typeof result
- return await withPostHogUrl(context, filtered, `/replay/${filtered.id}`)
- },
+ handler: withToolHooks(
+ hooks_sessionRecordingGet,
+ async (context: Context, params: z.infer<ReturnType<typeof SessionRecordingGetSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SessionRecording>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/session_recordings/${encodeURIComponent(String(params.id))}/`,
+ })
+ const filtered = omitResponseFields(result, ['person.properties']) as typeof result
+ return await withPostHogUrl(context, filtered, `/replay/${filtered.id}`)
+ }
+ ),
})
const SessionRecordingPlaylistCreateSchema = () => {
diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.ts
index b744c8dbd884..8b6a2baf062c 100644
--- a/services/mcp/src/tools/index.ts
+++ b/services/mcp/src/tools/index.ts
@@ -12,7 +12,6 @@ import experimentGetByFlagKey from './experiments/getByFlagKey'
import getExperimentResults from './experiments/getResults'
// Feature flags
import featureFlagGetDefinitionByKey from './featureFlags/getDefinitionByKey'
-import updateFeatureFlagPreservingGroups from './featureFlags/updateFeatureFlag'
// Feedback
import submitFeedback from './feedback/submit'
// Generated tools (from definitions/*.yaml)
@@ -54,8 +53,6 @@ import setActiveProject from './projects/setActive'
import updateEventDefinition from './projects/updateEventDefinition'
import updatePathCleaning from './projects/updatePathCleaning'
import updatePropertyDefinition from './projects/updatePropertyDefinition'
-// Replay
-import getSessionRecording from './replay/getSessionRecording'
// Skills (deprecation aliases for the llma-skill-* → skill-* rename)
import { SKILL_DEPRECATED_ALIASES } from './skills/deprecatedAliases'
import { tasksArtifactsList, tasksCommentsList, tasksCommentsRetrieve } from './tasksContext'
@@ -92,7 +89,6 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
// Feature flags (get-definition-by-key is hand-written; get-definition by numeric id is codegen)
'feature-flag-get-definition-by-key': featureFlagGetDefinitionByKey,
- 'update-feature-flag': updateFeatureFlagPreservingGroups,
'path-cleaning-rules-update': updatePathCleaning,
@@ -137,9 +133,6 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {
[EXECUTE_SQL_TOOL_NAME]: executeSql,
'read-data-schema': readDataSchema,
- // Replay
- 'session-recording-get': getSessionRecording,
-
// Data warehouse (custom handlers for non-standard request shapes)
'external-data-sources-db-schema': externalDataSourcesDbSchema,
'external-data-sources-preview-resource': externalDataSourcesPreview,
diff --git a/services/mcp/src/tools/replay/getSessionRecording.ts b/services/mcp/src/tools/replay/getSessionRecording.ts
deleted file mode 100644
index 99afb6f709f7..000000000000
--- a/services/mcp/src/tools/replay/getSessionRecording.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { PostHogApiError } from '@/lib/errors'
-import { GENERATED_TOOLS } from '@/tools/generated/replay'
-import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
-
-const getSessionRecording = (): ToolBase<ZodObjectAny> => {
- const tool = GENERATED_TOOLS['session-recording-get']!()
-
- return {
- ...tool,
- handler: async (context: Context, params: { id: string }) => {
- try {
- return await tool.handler(context, params)
- } catch (error) {
- if (
- error instanceof PostHogApiError &&
- error.status === 404 &&
- error.method === 'GET' &&
- error.url.split('?')[0]?.endsWith(`/session_recordings/${encodeURIComponent(params.id)}/`) &&
- isRecordingNotFound(error.body)
- ) {
- return {
- found: false as const,
- id: params.id,
- reason: 'recording_not_found' as const,
- message: 'No session recording is available for this ID in the active project.',
- }
- }
- throw error
- }
- },
- }
-}
-
-function isRecordingNotFound(body: string): boolean {
- try {
- return JSON.parse(body)?.detail === 'Recording not found'
- } catch {
- return false
- }
-}
-
-export default getSessionRecording
diff --git a/services/mcp/src/tools/replay/sessionRecordingGetHooks.ts b/services/mcp/src/tools/replay/sessionRecordingGetHooks.ts
new file mode 100644
index 000000000000..988dc909a5e4
--- /dev/null
+++ b/services/mcp/src/tools/replay/sessionRecordingGetHooks.ts
@@ -0,0 +1,32 @@
+import { PostHogApiError } from '@/lib/errors'
+import type { ToolHooks } from '@/tools/tool-hooks'
+import type { Context } from '@/tools/types'
+
+// Turns the API's "Recording not found" 404 into a result the agent can read, instead of a tool error.
+function onError(_context: Context, params: { id: string }, error: unknown): unknown {
+ if (
+ error instanceof PostHogApiError &&
+ error.status === 404 &&
+ error.method === 'GET' &&
+ error.url.split('?')[0]?.endsWith(`/session_recordings/${encodeURIComponent(params.id)}/`) &&
+ isRecordingNotFound(error.body)
+ ) {
+ return {
+ found: false as const,
+ id: params.id,
+ reason: 'recording_not_found' as const,
+ message: 'No session recording is available for this ID in the active project.',
+ }
+ }
+ throw error
+}
+
+function isRecordingNotFound(body: string): boolean {
+ try {
+ return JSON.parse(body)?.detail === 'Recording not found'
+ } catch {
+ return false
+ }
+}
+
+export default { onError } satisfies ToolHooks<{ id: string }>
diff --git a/services/mcp/src/tools/tool-hooks.ts b/services/mcp/src/tools/tool-hooks.ts
new file mode 100644
index 000000000000..bf6f00b6cf7d
--- /dev/null
+++ b/services/mcp/src/tools/tool-hooks.ts
@@ -0,0 +1,42 @@
+import type { Context } from '@/tools/types'
+
+/**
+ * Optional custom logic around a generated tool's request, declared per tool with
+ * `hooks:` in tools.yaml. Methods are declared with method syntax so a hook module can
+ * type `params` more narrowly than the generated schema.
+ *
+ * A hook module default-exports its hooks with `satisfies ToolHooks<...>`, so a misspelled
+ * hook name is a compile error instead of a hook that never runs.
+ */
+export interface ToolHooks<TParams = never> {
+ /** Runs before the request. Return the params the request should use. */
+ beforeRequest?(context: Context, params: TParams): TParams | Promise<TParams>
+ /** Runs after a successful request. Return the result to send to the client. */
+ afterResponse?(context: Context, params: TParams, result: unknown): unknown
+ /** Runs when the request fails. Return a result to handle the error, or rethrow it to keep it. */
+ onError?(context: Context, params: TParams, error: unknown): unknown
+}
+
+/**
+ * Wraps a generated handler: beforeRequest, then the handler, then afterResponse.
+ * A failed beforeRequest aborts before the request is sent and skips onError.
+ */
+export function withToolHooks<TParams, TResult>(
+ hooks: ToolHooks<TParams>,
+ handler: (context: Context, params: TParams) => Promise<TResult>
+): (context: Context, params: TParams) => Promise<TResult> {
+ return async (context, params) => {
+ const requestParams = hooks.beforeRequest ? await hooks.beforeRequest(context, params) : params
+ let result: TResult
+ try {
+ result = await handler(context, requestParams)
+ } catch (error) {
+ if (!hooks.onError) {
+ throw error
+ }
+ // Hooks may return a result the generated type does not describe, such as a "not found" payload.
+ return (await hooks.onError(context, requestParams, error)) as TResult
+ }
+ return hooks.afterResponse ? ((await hooks.afterResponse(context, requestParams, result)) as TResult) : result
+ }
+}
diff --git a/services/mcp/tests/tools/sessionReplays.integration.test.ts b/services/mcp/tests/tools/sessionReplays.integration.test.ts
index 80e16a2bd631..74192bf05d4b 100644
--- a/services/mcp/tests/tools/sessionReplays.integration.test.ts
+++ b/services/mcp/tests/tools/sessionReplays.integration.test.ts
@@ -11,7 +11,6 @@ import {
validateEnvironmentVariables,
} from '@/shared/test-utils'
import { GENERATED_TOOLS } from '@/tools/generated/replay'
-import getSessionRecording from '@/tools/replay/getSessionRecording'
import type { Context } from '@/tools/types'
describe('Session Replays', { concurrent: false }, () => {
@@ -26,7 +25,7 @@ describe('Session Replays', { concurrent: false }, () => {
describe('Session Recordings', () => {
const queryListTool = GENERATED_TOOLS['query-session-recordings-list']!()
- const getTool = getSessionRecording()
+ const getTool = GENERATED_TOOLS['session-recording-get']!()
describe('query-session-recordings-list tool', () => {
it('should return results with pagination info', async () => {
diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.ts
index 70cc141d1592..9ba86009cb99 100644
--- a/services/mcp/tests/unit/generate-tools.test.ts
+++ b/services/mcp/tests/unit/generate-tools.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildResponseFilter,
@@ -2437,3 +2437,222 @@ describe('generateCategoryFile with a missing operation', () => {
vi.restoreAllMocks()
})
})
+
+describe('derived scopes and annotations', () => {
+ const readAndWrite = [{ PersonalAPIKeyAuth: ['thing:read', 'thing:write'] }]
+
+ function specWith(method: string, security?: Array<Record<string, string[]>>): OpenApiSpec {
+ return makeSpec({
+ paths: {
+ '/api/projects/{project_id}/things/': {
+ [method.toLowerCase()]: { operationId: 'things_op', parameters: [], security },
+ },
+ },
+ })
+ }
+
+ function generate(spec: OpenApiSpec, tool: Partial<ToolConfig>): ReturnType<typeof generateCategoryFile> {
+ const category = {
+ ...defaultCategory,
+ tools: { 'thing-op': { operation: 'things_op', enabled: true, ...tool } as ToolConfig },
+ }
+ return generateCategoryFile(category, 'products/things/mcp/tools.yaml', 'things', spec, new Set(), () => ({
+ definitions: {},
+ }))
+ }
+
+ function generateAndCaptureExit(spec: OpenApiSpec, tool: Partial<ToolConfig>): string {
+ const errors: string[] = []
+ vi.spyOn(console, 'error').mockImplementation((message: string) => {
+ errors.push(message)
+ })
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit')
+ }) as never)
+ expect(() => generate(spec, tool)).toThrow('exit')
+ return errors.join('\n')
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
+ })
+
+ it.each([
+ {
+ name: 'takes scopes from the spec when the YAML has none',
+ security: readAndWrite,
+ yamlScopes: undefined,
+ expected: ['thing:read', 'thing:write'],
+ },
+ {
+ name: 'dedupes scopes repeated across security entries',
+ security: [{ PersonalAPIKeyAuth: ['thing:read'] }, { PersonalAPIKeyAuth: ['thing:read'] }],
+ yamlScopes: undefined,
+ expected: ['thing:read'],
+ },
+ {
+ name: 'prefers explicit YAML scopes over the spec',
+ security: readAndWrite,
+ yamlScopes: ['thing:read'],
+ expected: ['thing:read'],
+ },
+ ])('scopes: $name', ({ security, yamlScopes, expected }) => {
+ const { enabledTools } = generate(specWith('GET', security), { scopes: yamlScopes })
+
+ expect(enabledTools[0]?.[1].scopes).toEqual(expected)
+ })
+
+ it.each([
+ { name: 'no security block', security: undefined },
+ { name: 'an empty security requirement', security: [{}] },
+ ])('scopes: fails when the YAML has none and the spec has $name', ({ security }) => {
+ expect(generateAndCaptureExit(specWith('GET', security), {})).toMatch(/Add "scopes" to the tool's YAML/)
+ })
+
+ it.each([
+ { method: 'GET', expected: { readOnly: true, destructive: false, idempotent: true } },
+ { method: 'DELETE', expected: { readOnly: false, destructive: true, idempotent: true } },
+ ])('annotations: $method defaults to $expected', ({ method, expected }) => {
+ const { enabledTools } = generate(specWith(method, readAndWrite), {})
+
+ expect(enabledTools[0]?.[1].annotations).toEqual(expected)
+ })
+
+ it.each(['PATCH', 'POST', 'PUT'])('annotations: %s without annotations fails', (method) => {
+ expect(generateAndCaptureExit(specWith(method, readAndWrite), {})).toMatch(
+ new RegExp(`${method} endpoints have no defaults`)
+ )
+ })
+
+ it('annotations: explicit YAML wins over the method default', () => {
+ const explicit = { readOnly: false, destructive: true, idempotent: false }
+
+ const { enabledTools } = generate(specWith('GET', readAndWrite), { annotations: explicit })
+
+ expect(enabledTools[0]?.[1].annotations).toEqual(explicit)
+ })
+
+ describe('scope coverage warning', () => {
+ function captureStdout(): string[] {
+ const lines: string[] = []
+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
+ lines.push(String(chunk))
+ return true
+ })
+ return lines
+ }
+
+ it.each([
+ { name: 'YAML misses a spec scope', yamlScopes: ['thing:read'], warns: true },
+ {
+ name: 'YAML is broader than the spec',
+ yamlScopes: ['thing:read', 'thing:write', 'thing:admin'],
+ warns: false,
+ },
+ { name: 'YAML has no scopes', yamlScopes: undefined, warns: false },
+ ])('$name -> warns: $warns', ({ yamlScopes, warns }) => {
+ const lines = captureStdout()
+
+ generate(specWith('GET', readAndWrite), { scopes: yamlScopes })
+
+ const output = lines.join('')
+ expect(output.includes('thing:write')).toBe(warns)
+ if (warns) {
+ expect(output).toContain('Tool "thing-op"')
+ expect(output).toContain('products/things/mcp/tools.yaml')
+ }
+ })
+
+ it('treats a write scope as covering a spec read scope', () => {
+ const lines = captureStdout()
+
+ generate(specWith('GET', [{ PersonalAPIKeyAuth: ['thing:read'] }]), { scopes: ['thing:write'] })
+
+ expect(lines.join('')).toBe('')
+ })
+
+ it('skips tools whose spec declares no scopes', () => {
+ const lines = captureStdout()
+
+ generate(specWith('GET', undefined), { scopes: ['thing:read'] })
+
+ expect(lines.join('')).toBe('')
+ })
+
+ it.each([
+ { githubActions: 'true', annotated: true },
+ { githubActions: 'false', annotated: false },
+ ])('emits a GitHub annotation only on CI (GITHUB_ACTIONS=$githubActions)', ({ githubActions, annotated }) => {
+ vi.stubEnv('GITHUB_ACTIONS', githubActions)
+ const lines = captureStdout()
+
+ generate(specWith('GET', readAndWrite), { scopes: ['thing:read'] })
+
+ expect(lines.join('').includes('::warning file=products/things/mcp/tools.yaml::')).toBe(annotated)
+ })
+ })
+})
+
+describe('hooks', () => {
+ const spec = makeSpec({
+ paths: {
+ '/api/projects/{project_id}/things/': {
+ get: { operationId: 'things_list', parameters: [], security: [{ PersonalAPIKeyAuth: ['thing:read'] }] },
+ },
+ },
+ })
+
+ function generate(tool: Partial<ToolConfig>): ReturnType<typeof generateCategoryFile> {
+ const category = {
+ ...defaultCategory,
+ tools: { 'thing-list': { operation: 'things_list', enabled: true, ...tool } as ToolConfig },
+ }
+ return generateCategoryFile(category, 'products/things/mcp/tools.yaml', 'things', spec, new Set(), () => ({
+ definitions: {},
+ }))
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ it('imports the hooks module and wraps the handler', () => {
+ const { code } = generate({ hooks: 'tool-hooks' })
+
+ expect(code).toContain("import hooks_thingList from '@/tools/tool-hooks'")
+ expect(code).toContain("import { withToolHooks } from '@/tools/tool-hooks'")
+ expect(code).toMatch(/handler: withToolHooks\(\s*hooks_thingList,\s*async \(context: Context/)
+ })
+
+ it('leaves tools without hooks unwrapped', () => {
+ const { code } = generate({})
+
+ expect(code).not.toContain('withToolHooks')
+ expect(code).toContain('handler: async (context: Context')
+ })
+
+ it('fails when the hooks module does not exist', () => {
+ const errors: string[] = []
+ vi.spyOn(console, 'error').mockImplementation((message: string) => {
+ errors.push(message)
+ })
+ vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit')
+ }) as never)
+
+ expect(() => generate({ hooks: 'nowhere/missingHooks' })).toThrow('exit')
+ expect(errors.join('\n')).toMatch(/hooks module "nowhere\/missingHooks" not found/)
+ })
+
+ it('rejects hooks combined with confirmed_action', () => {
+ const result = ToolConfigSchema.safeParse({
+ operation: 'things_list',
+ enabled: true,
+ hooks: 'tool-hooks',
+ confirmed_action: {},
+ })
+
+ expect(result.success).toBe(false)
+ })
+})
diff --git a/services/mcp/tests/unit/session-recording-get.test.ts b/services/mcp/tests/unit/session-recording-get.test.ts
index 21a1ed95876f..d647b407c7d7 100644
--- a/services/mcp/tests/unit/session-recording-get.test.ts
+++ b/services/mcp/tests/unit/session-recording-get.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { PostHogApiError } from '@/lib/errors'
-import getSessionRecording from '@/tools/replay/getSessionRecording'
+import { GENERATED_TOOLS } from '@/tools/generated/replay'
import type { Context } from '@/tools/types'
const recordingUrl = 'https://us.posthog.com/api/projects/42/session_recordings/session-123/'
@@ -21,7 +21,7 @@ function apiError(status: number, url = recordingUrl, body = ''): PostHogApiErro
}
describe('session-recording-get', () => {
- const tool = getSessionRecording()
+ const tool = GENERATED_TOOLS['session-recording-get']!()
it('preserves the generated tool schema and UI app metadata', () => {
expect(tool.name).toBe('session-recording-get')
diff --git a/services/mcp/tests/unit/tool-hooks.test.ts b/services/mcp/tests/unit/tool-hooks.test.ts
new file mode 100644
index 000000000000..931e4927e517
--- /dev/null
+++ b/services/mcp/tests/unit/tool-hooks.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { withToolHooks } from '@/tools/tool-hooks'
+import type { Context } from '@/tools/types'
+
+const context = {} as Context
+
+describe('withToolHooks', () => {
+ it('runs beforeRequest, the handler with its params, then afterResponse', async () => {
+ const handler = vi.fn(async (_context: Context, params: { n: number }) => ({ doubled: params.n * 2 }))
+ const wrapped = withToolHooks(
+ {
+ beforeRequest: (_context, params) => ({ n: params.n + 1 }),
+ afterResponse: (_context, params, result) => ({ result, sent: params }),
+ },
+ handler
+ )
+
+ await expect(wrapped(context, { n: 1 })).resolves.toEqual({ result: { doubled: 4 }, sent: { n: 2 } })
+ })
+
+ it.each([
+ { name: 'onError returns a result', onError: () => 'handled', expected: 'handled' },
+ {
+ name: 'onError rethrows',
+ onError: (_context: Context, _params: unknown, error: unknown) => {
+ throw error
+ },
+ expected: undefined,
+ },
+ { name: 'no onError', onError: undefined, expected: undefined },
+ ])('request failure: $name', async ({ onError, expected }) => {
+ const failure = new Error('boom')
+ const wrapped = withToolHooks({ onError }, async () => {
+ throw failure
+ })
+
+ if (expected === undefined) {
+ await expect(wrapped(context, {})).rejects.toBe(failure)
+ } else {
+ await expect(wrapped(context, {})).resolves.toBe(expected)
+ }
+ })
+
+ it('does not send the request or call onError when beforeRequest fails', async () => {
+ const handler = vi.fn()
+ const onError = vi.fn()
+ const wrapped = withToolHooks(
+ {
+ beforeRequest: () => {
+ throw new Error('lookup failed')
+ },
+ onError,
+ },
+ handler
+ )
+
+ await expect(wrapped(context, {})).rejects.toThrow('lookup failed')
+ expect(handler).not.toHaveBeenCalled()
+ expect(onError).not.toHaveBeenCalled()
+ })
+})
diff --git a/services/mcp/tests/unit/tool-name-validation.test.ts b/services/mcp/tests/unit/tool-name-validation.test.ts
index 2ac4ba7048d7..95dddd40ae84 100644
--- a/services/mcp/tests/unit/tool-name-validation.test.ts
+++ b/services/mcp/tests/unit/tool-name-validation.test.ts
@@ -10,11 +10,12 @@ describe('Tool name validation', () => {
const allTools = mergeToolFactories({ generated: GENERATED_TOOL_MAP, handwritten: TOOL_MAP })
// A hand-written tool that shares a generated tool's name shadows it everywhere, so a
- // newly generated tool colliding with one would silently replace it.
- it('shadows only the generated tools it means to', () => {
+ // newly generated tool colliding with one would silently replace it. To customize a
+ // generated tool, use `hooks:` in tools.yaml instead of shadowing it.
+ it('shadows no generated tools', () => {
const shadowed = Object.keys(TOOL_MAP).filter((name) => name in GENERATED_TOOL_MAP)
- expect(shadowed.sort()).toEqual(['session-recording-get', 'update-feature-flag'])
+ expect(shadowed.sort()).toEqual([])
})
it.each(Object.keys(allTools))('%s — name matches map key, length, and pattern', (mapKey) => {
diff --git a/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts
index 99e902760095..df59d1233b70 100644
--- a/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts
+++ b/services/mcp/tests/unit/update-feature-flag-preserving-groups.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
-import updateFeatureFlagPreservingGroups from '@/tools/featureFlags/updateFeatureFlag'
+import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'
import type { Context } from '@/tools/types'
type ApiRequestArgs = { method: string; path: string; body?: unknown }
@@ -29,7 +29,7 @@ function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {
}
describe('update-feature-flag preserving groups', () => {
- const tool = updateFeatureFlagPreservingGroups()
+ const tool = GENERATED_TOOLS['update-feature-flag']!()
it('GETs existing flag, merges group fields into filters, then PATCHes', async () => {
const existing = {