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): name the missing scopes and target file in scaffold-yaml hints (#113101)

Julian Bez5d5d86d1967b
diff --git a/services/mcp/scripts/scaffold-yaml.ts b/services/mcp/scripts/scaffold-yaml.ts
index db3846f07e6e..1c16cc999330 100644
--- a/services/mcp/scripts/scaffold-yaml.ts
+++ b/services/mcp/scripts/scaffold-yaml.ts
@@ -49,7 +49,9 @@ interface OpenApiOperation {
summary?: string
description?: string
deprecated?: boolean
+ security?: Array<Record<string, string[]>>
'x-product'?: string[]
+ 'x-request-dependent-scopes'?: boolean
}
interface OpenApiSpec {
@@ -62,6 +64,8 @@ interface DiscoveredOperation {
path: string
summary?: string | undefined
description?: string | undefined
+ /** Codegen cannot take the scopes from the spec, so the YAML entry must list them. */
+ needsExplicitScopes: boolean
}
// A file other than the product's default `--add` target needs `--file`, or the command fails or writes to tools.yaml.
@@ -149,6 +153,11 @@ function findOperationsByProduct(spec: OpenApiSpec, product: string): Discovered
path: urlPath,
summary: op.summary,
description: op.description,
+ needsExplicitScopes:
+ Boolean(op['x-request-dependent-scopes']) ||
+ !(op.security ?? []).some((requirement) =>
+ Object.values(requirement).some((scopes) => scopes.length > 0)
+ ),
})
}
}
@@ -389,7 +398,22 @@ function oneLine(text: string | undefined, maxLength: number): string {
return flat.length > maxLength ? `${flat.slice(0, maxLength - 1)}…` : flat
}
-function formatCandidates(candidates: DiscoveredOperation[], product: string): string {
+function productDefinitionFiles(product: string): string[] {
+ const files: string[] = []
+ const mcpDir = path.join(PRODUCTS_DIR, product, 'mcp')
+ if (fs.existsSync(mcpDir)) {
+ files.push(...fs.readdirSync(mcpDir).map((file) => path.join(mcpDir, file)))
+ }
+ files.push(path.join(DEFINITIONS_DIR, `${product}.yaml`), path.join(DEFINITIONS_DIR, `${product}.yml`))
+ return files.filter((file) => /\.ya?ml$/.test(file) && fs.existsSync(file)).sort()
+}
+
+function formatCandidates(
+ candidates: DiscoveredOperation[],
+ product: string,
+ productFiles: string[],
+ defaultFile: string | undefined
+): string {
if (candidates.length === 0) {
return `Every OpenAPI operation of "${product}" already has a YAML entry.\n`
}
@@ -403,7 +427,14 @@ function formatCandidates(candidates: DiscoveredOperation[], product: string): s
`${candidates.length} operation(s) of "${product}" have no YAML entry:\n` +
lines.map((line) => ` ${line}\n`).join('') +
`\nAdd one as an enabled tool:\n` +
- ` pnpm --filter=@posthog/mcp run scaffold-yaml -- --add <operationId> --product ${product}\n`
+ ` pnpm --filter=@posthog/mcp run scaffold-yaml -- --add <operationId> --product ${product}\n` +
+ // Without --file the entry lands in the default file, and codegen builds its links from that file's url_prefix.
+ (productFiles.some((file) => file !== defaultFile)
+ ? (defaultFile
+ ? `Add --file <path> to write it to another file of "${product}":\n`
+ : `"${product}" has no tools.yaml, so add --file <path>:\n`) +
+ productFiles.map((file) => ` ${path.relative(MCP_ROOT, file)}\n`).join('')
+ : '')
)
}
@@ -440,7 +471,9 @@ function buildAddedTool(
// Title and description fall back to the spec in codegen, so the entry only overrides them when needed.
const entry: Record<string, unknown> = { operation: operationId, enabled: true }
- return { toolName, op, entry }
+ // The entry names this exact variant, so its scopes decide the next-step hints.
+ const selected = rawOps.find((candidate) => candidate.operationId === operationId) ?? op
+ return { toolName, op: selected, entry }
}
function defaultProductFile(product: string): string | undefined {
@@ -585,6 +618,19 @@ function syncAll(spec: OpenApiSpec): void {
}
}
+function formatAddNextSteps(op: DiscoveredOperation): string {
+ const steps = [
+ 'check the title and description the API gives the tool, set them in the YAML if they do not read well for an agent',
+ ]
+ if (!['GET', 'DELETE'].includes(op.method)) {
+ steps.push(`add annotations (required for ${op.method})`)
+ }
+ if (op.needsExplicitScopes) {
+ steps.push('add "scopes" (required: the API picks the scopes per request, so the spec cannot supply them)')
+ }
+ return `Next: ${steps.join(', ')}, then run hogli build:openapi to generate the tool.\n`
+}
+
function addTool(spec: OpenApiSpec, product: string, operationId: string, filePath: string | undefined): void {
const targetFile = filePath ? path.resolve(MCP_ROOT, filePath) : defaultProductFile(product)
if (!targetFile || !fs.existsSync(targetFile)) {
@@ -612,13 +658,7 @@ function addTool(spec: OpenApiSpec, product: string, operationId: string, filePa
const label = path.relative(REPO_ROOT, targetFile)
process.stdout.write(`Added "${added.toolName}" (${added.op.method} ${added.op.path}) to ${label}.\n`)
- process.stdout.write(
- 'Next: check the title and description the API gives the tool, set them in the YAML if they do not read well for an agent'
- )
- if (!['GET', 'DELETE'].includes(added.op.method)) {
- process.stdout.write(`, add annotations (required for ${added.op.method})`)
- }
- process.stdout.write(', then run hogli build:openapi to generate the tool.\n')
+ process.stdout.write(formatAddNextSteps(added.op))
}
const USAGE = `Usage: scaffold-yaml --product <name> [--output <file>] create or re-sync one product file
@@ -677,7 +717,9 @@ function main(): void {
process.exit(1)
}
const candidates = findCandidates(spec, product, collectClaims().baseIds)
- process.stdout.write(formatCandidates(candidates, product))
+ process.stdout.write(
+ formatCandidates(candidates, product, productDefinitionFiles(product), defaultProductFile(product))
+ )
return
}
@@ -724,7 +766,7 @@ function main(): void {
formatWithPrettier([resolvedOutput])
}
-export { buildAddedTool, findCandidates, mergeWithExisting, renderCategoryYaml }
+export { buildAddedTool, findCandidates, formatAddNextSteps, formatCandidates, mergeWithExisting, renderCategoryYaml }
export type { Claims, OpenApiSpec }
function stripExt(filePath: string): string {
diff --git a/services/mcp/tests/unit/scaffold-yaml.test.ts b/services/mcp/tests/unit/scaffold-yaml.test.ts
index 672b40a4057e..f2b3db6e6f82 100644
--- a/services/mcp/tests/unit/scaffold-yaml.test.ts
+++ b/services/mcp/tests/unit/scaffold-yaml.test.ts
@@ -2,7 +2,14 @@ import path from 'path'
import { describe, expect, it } from 'vitest'
import { parse as parseYaml } from 'yaml'
-import { buildAddedTool, findCandidates, mergeWithExisting, renderCategoryYaml } from '../../scripts/scaffold-yaml'
+import {
+ buildAddedTool,
+ findCandidates,
+ formatAddNextSteps,
+ formatCandidates,
+ mergeWithExisting,
+ renderCategoryYaml,
+} from '../../scripts/scaffold-yaml'
import type { Claims, OpenApiSpec } from '../../scripts/scaffold-yaml'
import { CategoryConfigSchema } from '../../scripts/yaml-config-schema'
import type { CategoryConfig } from '../../scripts/yaml-config-schema'
@@ -43,8 +50,18 @@ function validIds(product: string): Set<string> {
}
const thingsOps = [
- { operationId: 'things_list', method: 'GET', path: '/api/projects/{project_id}/things/' },
- { operationId: 'things_create', method: 'POST', path: '/api/projects/{project_id}/things/' },
+ {
+ operationId: 'things_list',
+ method: 'GET',
+ path: '/api/projects/{project_id}/things/',
+ needsExplicitScopes: false,
+ },
+ {
+ operationId: 'things_create',
+ method: 'POST',
+ path: '/api/projects/{project_id}/things/',
+ needsExplicitScopes: false,
+ },
]
describe('scaffold-yaml', () => {
@@ -127,6 +144,65 @@ describe('scaffold-yaml', () => {
})
})
+ it.each([
+ {
+ name: 'the spec lists scopes',
+ operation: { security: [{ PersonalAPIKeyAuth: ['thing:read'] }] },
+ asks: false,
+ },
+ { name: 'the spec lists no scopes', operation: {}, asks: true },
+ {
+ name: 'the API picks the scopes per request',
+ operation: { security: [{ PersonalAPIKeyAuth: ['thing:read'] }], 'x-request-dependent-scopes': true },
+ asks: true,
+ },
+ {
+ name: 'only the named variant lacks spec scopes',
+ operation: {},
+ asks: true,
+ otherVariant: { security: [{ PersonalAPIKeyAuth: ['thing:read'] }] },
+ },
+ ])('asks for scopes after an add when $name', ({ operation, asks, otherVariant }) => {
+ // Dedup prefers the /api/projects/ variant, so the add below names the other one.
+ const scopedSpec: OpenApiSpec = {
+ paths: {
+ '/api/environments/{project_id}/things/': {
+ get: { operationId: 'things_list', 'x-product': ['things'], ...operation },
+ },
+ '/api/projects/{project_id}/things/': {
+ get: { operationId: 'things_list_2', 'x-product': ['things'], ...(otherVariant ?? operation) },
+ },
+ },
+ }
+
+ const { op } = buildAddedTool(scopedSpec, 'things', 'things_list', claims())
+
+ expect(formatAddNextSteps(op).includes('add "scopes"')).toBe(asks)
+ })
+
+ it.each([
+ { name: 'only the default file', files: ['/repo/products/things/mcp/tools.yaml'], fileHint: null },
+ {
+ name: 'several files',
+ files: ['/repo/products/things/mcp/extras.yaml', '/repo/products/things/mcp/tools.yaml'],
+ fileHint: 'Add --file <path> to write it to another file',
+ },
+ {
+ name: 'one file that is not the default',
+ files: ['/repo/products/things/mcp/extras.yaml'],
+ fileHint: 'has no tools.yaml, so add --file <path>',
+ },
+ ])('offers --file in the candidate list for a product with $name', ({ files, fileHint }) => {
+ const defaultFile = files.find((file) => file.endsWith('/tools.yaml'))
+
+ const output = formatCandidates(findCandidates(spec, 'things', new Set()), 'things', files, defaultFile)
+
+ expect(output.includes('--file')).toBe(fileHint !== null)
+ if (fileHint) {
+ expect(output).toContain(fileHint)
+ }
+ })
+
it.each([
{ name: 'feature_flag', gate: { feature_flag: 'things-beta' } },
{ name: 'feature_entitlement', gate: { feature_entitlement: 'things_paid' } },