: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
chore(mcp): validate / lint help-text tool references against the registry (#63274)
Marcel Poelkerab9d52ba8487
diff --git a/.github/workflows/ci-agent-skills.yml b/.github/workflows/ci-agent-skills.ymlindex d5ba71ac3e5a..78660ef91391 100644--- a/.github/workflows/ci-agent-skills.yml+++ b/.github/workflows/ci-agent-skills.yml@@ -48,6 +48,7 @@ jobs:- 'products/*/backend/max_tools.py'- 'products/posthog_ai/**'- '.github/workflows/ci-agent-skills.yml'+ - 'services/mcp/schema/**'check-skills:name: Check agent skillsdiff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.pyindex 16f24108ed92..5a55a162e03a 100755--- a/products/posthog_ai/scripts/build_skills.py+++ b/products/posthog_ai/scripts/build_skills.py@@ -26,11 +26,13 @@ from __future__ import annotationsimport osimport reimport sys+import jsonimport shutilimport zipfileimport argparseimport textwrapfrom pathlib import Path+from typing import Literal, castimport yamlfrom jinja2 import Environment, StrictUndefined, TemplateSyntaxError@@ -46,6 +48,146 @@ _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)_BINARY_CHECK_SIZE = 8192_ALLOWED_SUBDIRS = {"references", "scripts"}+# Tool/skill reference linting: skills must only reference MCP tools and skills that exist.+# The valid tool names come from the checked-in MCP schema registries (kept in sync with the+# sources by the schema drift check in ci-mcp.yml). Mirrors lint-tool-names.ts in services/mcp.+_MCP_SCHEMA_FILES = (+ "services/mcp/schema/tool-definitions.json",+ "services/mcp/schema/generated-tool-definitions.json",+)+# Hyphenated/underscored prose that reads like a tool/skill reference but isn't one.+_REFERENCE_ALLOWLIST = {+ "per-file", # "a per-file tool"+ "follow-up", # "a follow-up tool"+ "pre-approved", # "list of pre-approved tools"+ "built-in", # "a built-in tool"+ "heavily-used", # "a heavily-used tool"+ "harness-level", # "a harness-level tool"+ "product-specific", # "a product-specific tool"+ "time-to-merge", # "there is no aggregate time-to-merge tool"+ "web-search", # LLM web search, not a PostHog MCP tool+ "comma-separated",+ "skills-store", # the Skills store feature ("the skills-store tools")+ "llma-alerts", # skills-store skill, not in this repo+ "text-embedding-3-small-1536", # embedding model name+ "deep-dive", # "a deep-dive skill"+ "team-shared",+ "per-team",+ "per-session", # adjective in "per-session tool calls", not a tool name+ "multi-file",+ "document-window", # shorthand for the business-knowledge-document-window-retrieve tool+ # SDK / HogQL functions legitimately shown with call syntax in skills:+ "feature_enabled",+ "get_feature_flag",+ "get_feature_flag_payload",+ "get_feature_flag_result",+ "get_all_flags",+ "get_all_flags_and_payloads",+ "apply_path_cleaning",+ "emit_signal",+}+# "use the X tool", "load the `X` skill" — kebab or snake candidate followed by tool/skill.+_PHRASE_REFERENCE_RE = re.compile(r"(?<![A-Za-z0-9_`-])`?([a-z0-9]+(?:[_-][a-z0-9]+)+)`?\s+(tools?|skills?)\b")+# "via `X`", "use `X`" — kebab-only (snake here is usually a field/SDK name, not a tool).+_INVOCATION_REFERENCE_RE = re.compile(+ r"\b(?:via|use|using|call|calling)\s+(?:the\s+)?`([a-z0-9]+(?:-[a-z0-9]+)+)`(?!\s*(?:tools?|skills?)\b)"+)+# A noun right after the backticked name means it's not a tool reference ("via the `x` feature flag").+_ENTITY_NOUN_RE = re.compile(r"\s+(?:feature|flag|event|property|properties|column|field|table|key|filter)s?\b")+# Backticked call syntax, e.g. `read_data("experiments", id)` — tool invocations written as calls.+# Deliberately skills-only (no equivalent in tool-references.ts): call-style references occur only+# in skill prose, and the SDK/HogQL allowlist entries above exist to absorb this rule's false positives.+_CALL_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:[_-][a-z0-9]+)+)\(")+# Backticked snake_case whose kebab form is a real tool — wrong casing.+_SNAKE_CASE_REFERENCE_RE = re.compile(r"`([a-z0-9]+(?:_[a-z0-9]+)+)`")+++def _load_mcp_tool_names(repo_root: Path) -> set[str] | None:+ """Load valid MCP tool names from the checked-in schema registries.++ Returns None if no registry is available so the reference check can be skipped+ (keeps the lint runnable in checkouts without the MCP service).+ """+ names: set[str] = set()+ found = False+ for rel_path in _MCP_SCHEMA_FILES:+ schema_file = repo_root / rel_path+ if not schema_file.is_file():+ continue+ found = True+ names.update(json.loads(schema_file.read_text()).keys())+ return names if found else None+++# The kinds produced by the phrase regex alternation `(tools?|skills?)`.+ReferenceKind = Literal["tool", "tools", "skill", "skills"]+++def _find_phrase_references(text: str) -> list[tuple[str, ReferenceKind]]:+ # kind is guaranteed by the `(tools?|skills?)` alternation+ return [(m.group(1), cast("ReferenceKind", m.group(2))) for m in _PHRASE_REFERENCE_RE.finditer(text)]+++def _find_invocation_references(text: str) -> list[str]:+ return [m.group(1) for m in _INVOCATION_REFERENCE_RE.finditer(text) if not _ENTITY_NOUN_RE.match(text, m.end())]+++def _find_call_references(text: str) -> list[str]:+ return [m.group(1) for m in _CALL_REFERENCE_RE.finditer(text)]+++def _find_backticked_snake_case(text: str) -> list[str]:+ return [m.group(1) for m in _SNAKE_CASE_REFERENCE_RE.finditer(text)]+++def _is_valid_reference(name: str, kind: ReferenceKind, tool_names: set[str], skill_names: set[str]) -> bool:+ if name in _REFERENCE_ALLOWLIST:+ return True+ registry = skill_names if kind in ("skill", "skills") else tool_names+ if name in registry:+ return True+ # Shorthand suffix, e.g. "the partial-update tool" for external-data-schemas-partial-update.+ if any(known.endswith(f"-{name}") for known in registry):+ return True+ # Plural family reference, e.g. "the feature-flag tools".+ if kind in ("tools", "skills") and any(known.startswith(f"{name}-") for known in registry):+ return True+ return False+++def _did_you_mean(name: str, tool_names: set[str]) -> str:+ kebab = name.replace("_", "-")+ matches = sorted(t for t in tool_names if t == kebab or t.endswith(f"-{kebab}"))+ return f" — did you mean {' or '.join(matches)}?" if matches else ""+++def _check_tool_references(text: str, source_label: str, tool_names: set[str], skill_names: set[str]) -> list[str]:+ # Dedupe by name within this text only: one name tripping two rules (e.g. wrong casing inside+ # a phrase) is one mistake, but the same stale name in another skill file needs its own report.+ errors: list[str] = []+ reported: set[str] = set()++ def report(name: str, reason: str) -> None:+ if name not in reported:+ reported.add(name)+ errors.append(f"{source_label}: '{name}' {reason}")++ for name, kind in _find_phrase_references(text):+ if not _is_valid_reference(name, kind, tool_names, skill_names):+ report(name, f"references a nonexistent {kind.rstrip('s')}{_did_you_mean(name, tool_names)}")+ # "via `X`" names one concrete thing but not whether it's a tool or skill: check tools with+ # singular kind (a family prefix like `feature-flag` is not invocable), plus exact skill names.+ for name in _find_invocation_references(text):+ if not _is_valid_reference(name, "tool", tool_names, skill_names) and name not in skill_names:+ report(name, f"references a nonexistent tool{_did_you_mean(name, tool_names)}")+ for name in _find_call_references(text):+ if not _is_valid_reference(name, "tool", tool_names, skill_names):+ report(name, f"references a nonexistent tool{_did_you_mean(name, tool_names)}")+ for name in _find_backticked_snake_case(text):+ if name not in tool_names and name.replace("_", "-") in tool_names:+ report(name, f"has wrong casing — the tool is named {name.replace('_', '-')}")+ return errors+def _create_jinja_env(**extra_globals: object) -> Environment:"""Create a Jinja2 Environment with the standard skill rendering settings."""@@ -366,6 +508,7 @@ class SkillBuilder:- Duplicate skill name detection (across products)- Jinja2 syntax validation via parse-only (all .j2 files)- Frontmatter validation for static .md entry points (required: name, description)+ - Tool/skill reference validation in markdown (against the MCP schema registries)Returns True if all checks pass, False otherwise."""@@ -384,6 +527,14 @@ class SkillBuilder:else:seen[skill.name] = skill+ tool_names = _load_mcp_tool_names(self.repo_root)+ if tool_names is None:+ print("WARNING: MCP schema registries not found; skipping tool reference checks.", file=sys.stderr)+ skill_names = set(seen)+ agents_skills_dir = self.repo_root / ".agents" / "skills"+ if agents_skills_dir.is_dir():+ skill_names.update(entry.name for entry in agents_skills_dir.iterdir() if entry.is_dir())+jinja_env = _create_jinja_env()for skill in skills:@@ -405,6 +556,9 @@ class SkillBuilder:except TemplateSyntaxError as e:errors.append(f"Jinja2 syntax error in {source_label}: {e}")+ if tool_names is not None and (file_path.name.endswith(".md") or file_path.name.endswith(".md.j2")):+ errors.extend(_check_tool_references(file_path.read_text(), source_label, tool_names, skill_names))+if skill.source_file.suffix != ".j2":raw = skill.source_file.read_text()source_label = str(skill.source_file.relative_to(self.repo_root))diff --git a/products/posthog_ai/scripts/test/test_build_skills.py b/products/posthog_ai/scripts/test/test_build_skills.pyindex 1c42b8a06be7..8d18cc120d0f 100644--- a/products/posthog_ai/scripts/test/test_build_skills.py+++ b/products/posthog_ai/scripts/test/test_build_skills.py@@ -16,6 +16,7 @@ from products.posthog_ai.scripts.build_skills import (SkillBuilder,SkillDiscoverer,SkillRenderer,+ _check_tool_references,parse_frontmatter,validate_frontmatter,)@@ -626,3 +627,66 @@ def test_init_skill_rejects_missing_product(tmp_path: Path) -> None:builder = SkillBuilder(repo_root=tmp_path, products_dir=tmp_path / "products", output_dir=tmp_path / "output")with pytest.raises(FileNotFoundError, match="does not exist"):builder.init_skill("nonexistent_product", "some-skill")+++_REF_TOOLS = {+ "execute-sql",+ "experiment-ship-variant",+ "feature-flag-get-all",+ "external-data-schemas-partial-update",+ "read-data-schema",+ "signals-scout-runs-list",+}+_REF_SKILLS = {"finding-experiments", "creating-experiments"}+++ "text,expected_names",+ [+ ("search flags with the feature-flags-get-all tool first", ["feature-flags-get-all"]),+ ("Use the `experiment_results_summary` tool", ["experiment_results_summary"]),+ ("use the launch, end, or ship_variant tools instead", ["ship_variant"]),+ ("`execute_sql`: query the experiments table", ["execute_sql"]),+ ("use the `execute_sql` tool", ["execute_sql"]),+ ("load the managing-unicorns skill first", ["managing-unicorns"]),+ ("query it via `does-not-exist-here`", ["does-not-exist-here"]),+ ('fetch the entity via `read_data("experiments", id)`', ["read_data"]),+ ("use the read-data-schema tool to discover events", []),+ ("change the sync type with the `partial-update` tool", []),+ ("browse with the feature-flag tools", []),+ ("this is a per-file tool for editing", []),+ ("Deep-dive skills are useful here", []),+ ("teams enrolled via the `signals-scout` feature flag", []),+ ("load the finding-experiments skill first", []),+ ("resolve the reference via `creating-experiments`", []),+ ('check `get_feature_flag("key", distinct_id)` in the SDK', []),+ ],+ ids=[+ "renamed-tool",+ "fictional-snake-case-tool",+ "snake-case-in-plural-phrase",+ "wrong-casing",+ "one-report-when-phrase-and-casing-rules-overlap",+ "nonexistent-skill",+ "invocation-of-unknown-tool",+ "call-syntax-fictional-tool",+ "exact-tool-name",+ "suffix-shorthand",+ "plural-family-reference",+ "allowlisted-prose",+ "capitalized-prose-no-mid-word-match",+ "entity-noun-after-backticks",+ "existing-skill",+ "skill-name-in-invocation-context",+ "allowlisted-sdk-call",+ ],+)+def test_check_tool_references(text: str, expected_names: list[str]) -> None:+ errors = _check_tool_references(text, "test", _REF_TOOLS, _REF_SKILLS)+ found = [err.split("'")[1] for err in errors]+ assert found == expected_names+++def test_check_tool_references_suggests_real_tool() -> None:+ (error,) = _check_tool_references("use the launch or ship_variant tools instead", "test", _REF_TOOLS, _REF_SKILLS)+ assert "did you mean experiment-ship-variant" in errordiff --git a/services/mcp/scripts/lib/tool-references.ts b/services/mcp/scripts/lib/tool-references.tsnew file mode 100644index 000000000000..4677d539ba1e--- /dev/null+++ b/services/mcp/scripts/lib/tool-references.ts@@ -0,0 +1,141 @@+/**+ * Detection of stale tool/skill references in help texts — phrases like "use the X tool"+ * or "load the X skill" must point at an existing tool/skill. Name-level only: this cannot+ * validate documented schemas or tool behavior.+ *+ * Used by scripts/lint-tool-names.ts. The skills lint (products/posthog_ai/scripts/+ * build_skills.py) implements the same rules for skill markdown, plus one deliberately+ * skills-only rule: call-syntax references like `read_data("experiments", id)` occur+ * only in skill prose, and detecting them here would false-positive on SDK/HogQL code+ * examples in tool descriptions.+ */++export type Violation = { source: string; tool: string; reason: string }++// The kinds produced by the phrase regex alternation `(tools?|skills?)`.+type ReferenceKind = 'tool' | 'tools' | 'skill' | 'skills'++// Hyphenated/underscored prose that reads like a tool/skill reference but isn't one.+const REFERENCE_ALLOWLIST = new Set([+ 'per-file', // "a per-file tool"+ 'follow-up', // "a follow-up tool"+ 'pre-approved', // "list of pre-approved tools"+ 'built-in', // "a built-in tool"+ 'heavily-used', // "a heavily-used tool"+ 'harness-level', // "a harness-level tool"+ 'product-specific', // "a product-specific tool"+ 'time-to-merge', // "there is no aggregate time-to-merge tool"+ 'web-search', // LLM web search, not a PostHog MCP tool+ 'comma-separated',+ 'skills-store', // the Skills store feature ("the skills-store tools")+ 'llma-alerts', // skills-store skill, not in this repo+ 'text-embedding-3-small-1536', // embedding model name+ 'deep-dive', // "a deep-dive skill"+ 'team-shared',+ 'per-team',+ 'per-session', // adjective in "per-session tool calls", not a tool name+ 'multi-file',+ 'document-window', // shorthand for the business-knowledge-document-window-retrieve tool+])++// "use the X tool", "load the `X` skill" — kebab or snake candidate followed by tool/skill.+const PHRASE_REFERENCE = /(?<![A-Za-z0-9_`-])`?([a-z0-9]+(?:[_-][a-z0-9]+)+)`?\s+(tools?|skills?)\b/g+// "via `X`", "use `X`" — kebab-only (snake here is usually a field/SDK name, not a tool).+const INVOCATION_REFERENCE =+ /\b(?:via|use|using|call|calling)\s+(?:the\s+)?`([a-z0-9]+(?:-[a-z0-9]+)+)`(?!\s*(?:tools?|skills?)\b)/g+// A noun right after the backticked name means it's not a tool reference ("via the `x` feature flag").+const ENTITY_NOUN_AFTER = /^\s+(?:feature|flag|event|property|properties|column|field|table|key|filter)s?\b/+// Backticked snake_case whose kebab form is a real tool — wrong casing.+const SNAKE_CASE_REFERENCE = /`([a-z0-9]+(?:_[a-z0-9]+)+)`/g++type PhraseReference = { name: string; kind: ReferenceKind }++function findPhraseReferences(text: string): PhraseReference[] {+ return [...text.matchAll(PHRASE_REFERENCE)].map((match) => ({+ name: match[1]!, // both groups always capture on a match+ kind: match[2] as ReferenceKind, // guaranteed by the `(tools?|skills?)` alternation+ }))+}++function findInvocationReferences(text: string): string[] {+ const names: string[] = []+ for (const match of text.matchAll(INVOCATION_REFERENCE)) {+ if (!ENTITY_NOUN_AFTER.test(text.slice(match.index + match[0].length))) {+ names.push(match[1]!)+ }+ }+ return names+}++function findBacktickedSnakeCase(text: string): string[] {+ return [...text.matchAll(SNAKE_CASE_REFERENCE)].map((match) => match[1]!)+}++function isValidReference(name: string, kind: ReferenceKind, toolNames: Set<string>, skillNames: Set<string>): boolean {+ if (REFERENCE_ALLOWLIST.has(name)) {+ return true+ }+ const registry = kind === 'skill' || kind === 'skills' ? skillNames : toolNames+ if (registry.has(name)) {+ return true+ }+ // Shorthand suffix, e.g. "the partial-update tool" for external-data-schemas-partial-update.+ for (const known of registry) {+ if (known.endsWith(`-${name}`)) {+ return true+ }+ }+ // Plural family reference, e.g. "the feature-flag tools".+ if (kind === 'tools' || kind === 'skills') {+ for (const known of registry) {+ if (known.startsWith(`${name}-`)) {+ return true+ }+ }+ }+ return false+}++function didYouMean(name: string, toolNames: Set<string>): string {+ const kebab = name.replace(/_/g, '-')+ const matches = [...toolNames].filter((t) => t === kebab || t.endsWith(`-${kebab}`))+ return matches.length > 0 ? ` — did you mean ${matches.join(' or ')}?` : ''+}++export function checkReferencesInText(+ text: string,+ source: string,+ toolNames: Set<string>,+ skillNames: Set<string>,+ seen: Set<string>,+ violations: Violation[]+): void {+ // Dedupe by name across all scanned texts: the generated JSONs and snapshots repeat the YAML+ // and serializer texts, and one name tripping two rules (e.g. wrong casing inside a phrase)+ // is one mistake. First report wins, so callers scan hand-editable sources first.+ const report = (name: string, reason: string): void => {+ if (seen.has(name)) {+ return+ }+ seen.add(name)+ violations.push({ source, tool: name, reason })+ }++ for (const { name, kind } of findPhraseReferences(text)) {+ if (!isValidReference(name, kind, toolNames, skillNames)) {+ report(name, `references nonexistent ${kind.replace(/s$/, '')}${didYouMean(name, toolNames)}`)+ }+ }+ // "via `X`" names one concrete thing but not whether it's a tool or skill: check tools with+ // singular kind (a family prefix like `feature-flag` is not invocable), plus exact skill names.+ for (const name of findInvocationReferences(text)) {+ if (!isValidReference(name, 'tool', toolNames, skillNames) && !skillNames.has(name)) {+ report(name, `references nonexistent tool${didYouMean(name, toolNames)}`)+ }+ }+ for (const name of findBacktickedSnakeCase(text)) {+ if (!toolNames.has(name) && toolNames.has(name.replace(/_/g, '-'))) {+ report(name, `wrong casing — the tool is named ${name.replace(/_/g, '-')}`)+ }+ }+}diff --git a/services/mcp/scripts/lint-tool-names.ts b/services/mcp/scripts/lint-tool-names.tsindex 5e9f30434ad3..c833235141d6 100644--- a/services/mcp/scripts/lint-tool-names.ts+++ b/services/mcp/scripts/lint-tool-names.ts@@ -1,6 +1,7 @@#!/usr/bin/env tsx/**- * Lint check: ensures all MCP tool names satisfy length and pattern constraints.+ * Lint check: ensures all MCP tool names satisfy length and pattern constraints,+ * and that descriptions/help texts only reference tools and skills that exist.** Validates tool names from three sources:* 1. YAML definitions (products and services/mcp/definitions)@@ -13,6 +14,11 @@* Pattern: tool names must be lowercase kebab-case ([a-z0-9-], no leading/trailing* hyphens) for cross-client compatibility.*+ * Cross-references: phrases like "use the X tool" or "load the X skill" in tool+ * descriptions (YAML) and field help texts (serializer help_text, surfaced via the+ * generated schema JSONs) must point at an existing tool/skill. This only covers+ * name-level staleness — it cannot validate documented schemas or tool behavior.+ ** Usage:* pnpm --filter=@posthog/mcp lint-tool-names*/@@ -21,6 +27,7 @@ import * as path from 'node:path'import { parse as parseYaml } from 'yaml'import { discoverDefinitions } from './lib/definitions.mjs'+import { checkReferencesInText, type Violation } from './lib/tool-references'import {CategoryConfigSchema,MAX_TOOL_NAME_LENGTH,@@ -34,8 +41,6 @@ const DEFINITIONS_DIR = path.resolve(MCP_ROOT, 'definitions')const PRODUCTS_DIR = path.resolve(REPO_ROOT, 'products')const SCHEMA_DIR = path.resolve(MCP_ROOT, 'schema')-type Violation = { source: string; tool: string; reason: string }-function validateToolName(name: string, source: string, violations: Violation[]): void {if (name.length > MAX_TOOL_NAME_LENGTH) {violations.push({ source, tool: name, reason: `${name.length} chars (max ${MAX_TOOL_NAME_LENGTH})` })@@ -49,7 +54,7 @@ function validateToolName(name: string, source: string, violations: Violation[])}}-function validateYamlDefinitions(violations: Violation[]): boolean {+function validateYamlDefinitions(violations: Violation[], knownToolNames: Set<string>): boolean {const definitions = discoverDefinitions({ definitionsDir: DEFINITIONS_DIR, productsDir: PRODUCTS_DIR })let hasErrors = false@@ -76,6 +81,7 @@ function validateYamlDefinitions(violations: Violation[]): boolean {if (!config.enabled) {continue}+ knownToolNames.add(name)validateToolName(name, label, violations)}}@@ -83,7 +89,7 @@ function validateYamlDefinitions(violations: Violation[]): boolean {return hasErrors}-function validateJsonDefinitions(fileName: string, violations: Violation[]): boolean {+function validateJsonDefinitions(fileName: string, violations: Violation[], knownToolNames: Set<string>): boolean {const filePath = path.resolve(SCHEMA_DIR, fileName)if (!fs.existsSync(filePath)) {return false@@ -92,35 +98,108 @@ function validateJsonDefinitions(fileName: string, violations: Violation[]): booconst content = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as Record<string, unknown>for (const name of Object.keys(content)) {+ knownToolNames.add(name)validateToolName(name, label, violations)}return false}+function discoverSkillNames(): Set<string> {+ const skillNames = new Set<string>()+ const skillRoots = [+ ...fs+ .readdirSync(PRODUCTS_DIR, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => path.join(PRODUCTS_DIR, e.name, 'skills')),+ path.join(REPO_ROOT, '.agents', 'skills'),+ ]+ for (const root of skillRoots) {+ if (!fs.existsSync(root)) {+ continue+ }+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {+ if (entry.isDirectory()) {+ skillNames.add(entry.name)+ } else if (entry.name.endsWith('.md') || entry.name.endsWith('.md.j2')) {+ skillNames.add(entry.name.replace(/\.md(\.j2)?$/, ''))+ }+ }+ }+ return skillNames+}++function validateToolReferences(violations: Violation[], toolNames: Set<string>): void {+ const skillNames = discoverSkillNames()+ const seen = new Set<string>()++ // YAML sources first so violations point at the editable file, not the generated JSON.+ const definitions = discoverDefinitions({ definitionsDir: DEFINITIONS_DIR, productsDir: PRODUCTS_DIR })+ for (const def of definitions) {+ const label = path.relative(REPO_ROOT, def.filePath)+ checkReferencesInText(fs.readFileSync(def.filePath, 'utf-8'), label, toolNames, skillNames, seen, violations)+ }++ if (fs.existsSync(SCHEMA_DIR)) {+ for (const file of fs.readdirSync(SCHEMA_DIR)) {+ if (!file.endsWith('.json')) {+ continue+ }+ const filePath = path.join(SCHEMA_DIR, file)+ checkReferencesInText(+ fs.readFileSync(filePath, 'utf-8'),+ path.relative(REPO_ROOT, filePath),+ toolNames,+ skillNames,+ seen,+ violations+ )+ }+ }++ // The tool-schema snapshots carry serializer help_text (via the OpenAPI spec); a hit here+ // means the fix belongs in a Django serializer, followed by regeneration.+ const snapshotsDir = path.resolve(MCP_ROOT, 'tests', 'unit', '__snapshots__', 'tool-schemas')+ if (fs.existsSync(snapshotsDir)) {+ for (const file of fs.readdirSync(snapshotsDir)) {+ if (!file.endsWith('.json')) {+ continue+ }+ const filePath = path.join(snapshotsDir, file)+ const label = `${path.relative(REPO_ROOT, filePath)} (fix the serializer help_text, then regenerate)`+ checkReferencesInText(fs.readFileSync(filePath, 'utf-8'), label, toolNames, skillNames, seen, violations)+ }+ }+}+function main(): void {const violations: Violation[] = []let hasErrors = false+ const knownToolNames = new Set<string>()- hasErrors = validateYamlDefinitions(violations) || hasErrors+ hasErrors = validateYamlDefinitions(violations, knownToolNames) || hasErrorsfor (const jsonFile of ['tool-definitions.json', 'generated-tool-definitions.json']) {- hasErrors = validateJsonDefinitions(jsonFile, violations) || hasErrors+ hasErrors = validateJsonDefinitions(jsonFile, violations, knownToolNames) || hasErrors}+ validateToolReferences(violations, knownToolNames)+if (violations.length === 0) {if (!hasErrors) {process.stdout.write(- `All tool names pass validation (max ${MAX_TOOL_NAME_LENGTH} chars, pattern ${TOOL_NAME_PATTERN}).\n`+ `All tool names pass validation (max ${MAX_TOOL_NAME_LENGTH} chars, pattern ${TOOL_NAME_PATTERN}) and all tool/skill references resolve.\n`)}return}- process.stderr.write(`Found ${violations.length} tool name violation(s):\n\n`)+ process.stderr.write(`Found ${violations.length} tool name / reference violation(s):\n\n`)for (const v of violations) {process.stderr.write(` ${v.tool}: ${v.reason} (${v.source})\n`)}- process.stderr.write(`\nTo fix: shorten or rename the tool name in the config.\n`)+ process.stderr.write(+ `\nTo fix: shorten/rename the tool name, or correct the stale reference in the description. False positive? Add it to REFERENCE_ALLOWLIST in scripts/lib/tool-references.ts.\n`+ )process.exitCode = 1}diff --git a/services/mcp/tests/unit/tool-references.test.ts b/services/mcp/tests/unit/tool-references.test.tsnew file mode 100644index 000000000000..3b19a9c88e60--- /dev/null+++ b/services/mcp/tests/unit/tool-references.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest'++import { checkReferencesInText, type Violation } from '../../scripts/lib/tool-references'++const TOOLS = new Set([+ 'execute-sql',+ 'experiment-ship-variant',+ 'feature-flag-get-all',+ 'external-data-schemas-partial-update',+ 'read-data-schema',+ 'signals-scout-runs-list',+])+const SKILLS = new Set(['finding-experiments', 'creating-experiments'])++function flagged(text: string): Violation[] {+ const violations: Violation[] = []+ checkReferencesInText(text, 'test', TOOLS, SKILLS, new Set(), violations)+ return violations+}++describe('checkReferencesInText', () => {+ it.each([+ // [description, text, expected flagged names]+ ['renamed tool', 'search flags with the feature-flags-get-all tool first', ['feature-flags-get-all']],+ ['fictional snake_case tool', 'Use the `experiment_results_summary` tool', ['experiment_results_summary']],+ ['snake_case in plural phrase', 'use the launch, end, or ship_variant tools instead', ['ship_variant']],+ ['wrong casing', '`execute_sql`: query the experiments table', ['execute_sql']],+ ['one report when phrase and casing rules overlap', 'use the `execute_sql` tool', ['execute_sql']],+ ['nonexistent skill', 'load the managing-unicorns skill first', ['managing-unicorns']],+ ['invocation of unknown tool', 'query it via `does-not-exist-here`', ['does-not-exist-here']],+ ['exact tool name', 'use the read-data-schema tool to discover events', []],+ ['suffix shorthand', 'change the sync type with the `partial-update` tool', []],+ ['plural family reference', 'browse with the feature-flag tools', []],+ ['allowlisted prose', 'this is a per-file tool for editing', []],+ ['capitalized prose does not match mid-word', 'Deep-dive skills are useful here', []],+ ['entity noun after backticks', 'teams enrolled via the `signals-scout` feature flag', []],+ ['existing skill', 'load the finding-experiments skill first', []],+ ['skill name in invocation context', 'resolve the reference via `creating-experiments`', []],+ ])('%s', (_description, text, expectedNames) => {+ expect(flagged(text).map((v) => v.tool)).toEqual(expectedNames)+ })++ it('suggests the real tool for suffix and casing matches', () => {+ const [violation] = flagged('use the launch or ship_variant tools instead')+ expect(violation?.reason).toContain('did you mean experiment-ship-variant')+ })++ it('dedupes repeated violations across texts via the shared seen set', () => {+ const violations: Violation[] = []+ const seen = new Set<string>()+ checkReferencesInText('use the bogus-name tool', 'a', TOOLS, SKILLS, seen, violations)+ checkReferencesInText('use the bogus-name tool', 'b', TOOLS, SKILLS, seen, violations)+ expect(violations).toHaveLength(1)+ expect(violations[0]?.source).toBe('a')+ })+})