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(skills): make tool-reference lint advisory with inline annotations (#63999)

Paul D'Ambrab5b39424a189
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
index 5a55a162e03a..7d221ccae81f 100755
--- a/products/posthog_ai/scripts/build_skills.py
+++ b/products/posthog_ai/scripts/build_skills.py
@@ -31,6 +31,7 @@ import shutil
import zipfile
import argparse
import textwrap
+from dataclasses import dataclass
from pathlib import Path
from typing import Literal, cast
@@ -55,28 +56,17 @@ _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:
+# The reference check is heuristic and advisory: a candidate is only treated as a (stale) reference
+# when it *resembles* a real name — within this many edits of a real tool/skill, or an exact
+# casing miss. Real renames/typos sit at distance 1-2 from the intended name; ordinary hyphenated
+# prose ("highest-error", "per-file") is far from every name. Backticks are not treated as intent
+# (prose uses them for emphasis and field names too), so prose that does not resemble a real name is
+# simply ignored — no name-level allowlist is needed for it. Findings are reported, never blocking.
+_NEAR_MISS_MAX_EDITS = 2
+# SDK / HogQL function names that legitimately appear as code in skills (e.g. `emit_signal(...)`,
+# `get_feature_flag(...)`). They are real identifiers, not stale references, but collide with a
+# tool-name suffix/near-miss, so they are held out of the reference check.
+_SDK_FUNCTION_NAMES = {
"feature_enabled",
"get_feature_flag",
"get_feature_flag_payload",
@@ -96,7 +86,8 @@ _INVOCATION_REFERENCE_RE = re.compile(
_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.
+# in skill prose. The near-miss gate keeps SDK/HogQL examples (e.g. `get_feature_flag(...)`) quiet,
+# since those names do not resemble any MCP tool.
_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]+)+)`")
@@ -123,25 +114,17 @@ def _load_mcp_tool_names(repo_root: Path) -> set[str] | None:
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)]
+@dataclass(frozen=True)
+class ReferenceFinding:
+ source_label: str
+ line: int
+ col: int
+ name: str
+ message: str
def _is_valid_reference(name: str, kind: ReferenceKind, tool_names: set[str], skill_names: set[str]) -> bool:
- if name in _REFERENCE_ALLOWLIST:
+ if name in _SDK_FUNCTION_NAMES:
return True
registry = skill_names if kind in ("skill", "skills") else tool_names
if name in registry:
@@ -155,38 +138,107 @@ def _is_valid_reference(name: str, kind: ReferenceKind, tool_names: set[str], sk
return False
-def _did_you_mean(name: str, tool_names: set[str]) -> str:
+def _edit_distance(a: str, b: str) -> int:
+ prev = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ cur = [i]
+ for j, cb in enumerate(b, 1):
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
+ prev = cur
+ return prev[-1]
+
+
+def _reference_suggestions(name: str, registry: set[str]) -> list[str]:
+ """Real names this candidate plausibly meant: exact/suffix matches, else near-misses by edit distance."""
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 ""
+ suffix = sorted(t for t in registry if t == kebab or t.endswith(f"-{kebab}"))
+ if suffix:
+ return suffix
+ near = sorted((_edit_distance(kebab, known), known) for known in registry)
+ return [known for distance, known in near if distance <= _NEAR_MISS_MAX_EDITS]
+
+
+def _did_you_mean(suggestions: list[str]) -> str:
+ return f" — did you mean {' or '.join(suggestions)}?" if suggestions else ""
+
+
+def _line_col(text: str, offset: int) -> tuple[int, int]:
+ return text.count("\n", 0, offset) + 1, offset - text.rfind("\n", 0, offset)
-def _check_tool_references(text: str, source_label: str, tool_names: set[str], skill_names: set[str]) -> list[str]:
+def _check_tool_references(
+ text: str, source_label: str, tool_names: set[str], skill_names: set[str]
+) -> list[ReferenceFinding]:
# 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] = []
+ # a phrase) is one finding, but the same stale name in another skill file needs its own.
+ findings: list[ReferenceFinding] = []
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):
+ def report(offset: int, name: str, message: str) -> None:
+ if name in reported:
+ return
+ reported.add(name)
+ line, col = _line_col(text, offset)
+ findings.append(ReferenceFinding(source_label, line, col, name, message))
+
+ # "X tool/skill". Resemblance to a real name is the only signal we trust — backticks in prose
+ # mean emphasis or a field name as often as a reference, so they are not treated as intent.
+ for m in _PHRASE_REFERENCE_RE.finditer(text):
+ name, kind = m.group(1), cast("ReferenceKind", m.group(2))
+ if _is_valid_reference(name, kind, tool_names, skill_names):
+ continue
+ suggestions = _reference_suggestions(name, skill_names if kind in ("skill", "skills") else tool_names)
+ if suggestions:
+ report(
+ m.start(1),
+ name,
+ f"'{name}' looks like a {kind.rstrip('s')} but none exists{_did_you_mean(suggestions)}",
+ )
+ # "via `X`": one concrete thing, but not whether tool or skill — check tools (a family prefix
+ # like `feature-flag` is not invocable) plus exact skill names.
+ for m in _INVOCATION_REFERENCE_RE.finditer(text):
+ if _ENTITY_NOUN_RE.match(text, m.end()):
+ continue
+ name = m.group(1)
+ if _is_valid_reference(name, "tool", tool_names, skill_names) or name in skill_names:
+ continue
+ suggestions = _reference_suggestions(name, tool_names)
+ if suggestions:
+ report(m.start(1), name, f"'{name}' looks like a tool but none exists{_did_you_mean(suggestions)}")
+ for m in _CALL_REFERENCE_RE.finditer(text):
+ name = m.group(1)
+ if _is_valid_reference(name, "tool", tool_names, skill_names):
+ continue
+ suggestions = _reference_suggestions(name, tool_names)
+ if suggestions:
+ report(m.start(1), name, f"'{name}' looks like a tool but none exists{_did_you_mean(suggestions)}")
+ for m in _SNAKE_CASE_REFERENCE_RE.finditer(text):
+ name = m.group(1)
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
+ report(m.start(1), name, f"'{name}' has wrong casing — the tool is named {name.replace('_', '-')}")
+ return findings
+
+
+def _emit_reference_findings(findings: list[ReferenceFinding]) -> None:
+ """Surface advisory reference findings without failing the lint.
+
+ In GitHub Actions, emit a workflow warning command so each finding renders as an annotation on
+ the offending line in the PR diff; locally, print a plain ``file:line:col`` warning.
+ """
+ if not findings:
+ return
+ in_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
+ for f in findings:
+ if in_github_actions:
+ print(
+ f"::warning file={f.source_label},line={f.line},col={f.col},title=Possible stale reference::{f.message}"
+ )
+ else:
+ print(f"{f.source_label}:{f.line}:{f.col}: warning: {f.message}", file=sys.stderr)
+ print(
+ f"\nNote: {len(findings)} possible stale tool/skill reference(s) flagged above (advisory, not blocking).",
+ file=sys.stderr,
+ )
def _create_jinja_env(**extra_globals: object) -> Environment:
@@ -514,6 +566,7 @@ class SkillBuilder:
"""
skills = self.discoverer.discover()
errors: list[str] = []
+ reference_findings: list[ReferenceFinding] = []
seen: dict[str, DiscoveredSkill] = {}
for skill in skills:
@@ -557,7 +610,9 @@ class SkillBuilder:
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))
+ reference_findings.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()
@@ -567,6 +622,11 @@ class SkillBuilder:
except ValueError as e:
errors.append(str(e))
+ # Tool/skill reference findings are advisory: they are surfaced (as CI annotations on the
+ # offending line, or plain warnings locally) but never fail the lint, because the check is a
+ # heuristic that can misfire on prose.
+ _emit_reference_findings(reference_findings)
+
if errors:
for err in errors:
print(f"ERROR: {err}", file=sys.stderr)
diff --git a/products/posthog_ai/scripts/test/test_build_skills.py b/products/posthog_ai/scripts/test/test_build_skills.py
index 8d18cc120d0f..e2bc2917790b 100644
--- a/products/posthog_ai/scripts/test/test_build_skills.py
+++ b/products/posthog_ai/scripts/test/test_build_skills.py
@@ -636,6 +636,7 @@ _REF_TOOLS = {
"external-data-schemas-partial-update",
"read-data-schema",
"signals-scout-runs-list",
+ "signals-scout-emit-signal",
}
_REF_SKILLS = {"finding-experiments", "creating-experiments"}
@@ -644,49 +645,68 @@ _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"]),
+ ("load the finding-experiment skill first", ["finding-experiment"]),
("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 `experiment_results_summary` tool", []),
+ ("load the `managing-unicorns` skill first", []),
+ ("query it via `does-not-exist-here`", []),
+ ('fetch the entity via `read_data("experiments", id)`', []),
("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", []),
+ ("rank by the highest-error tool first", []),
("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', []),
+ ('then `emit_signal("anomaly", ...)` from the SDK', []),
],
ids=[
- "renamed-tool",
- "fictional-snake-case-tool",
+ "renamed-tool-near-miss",
+ "renamed-skill-near-miss",
"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",
+ "one-finding-when-phrase-and-casing-rules-overlap",
+ "fictional-backticked-tool-no-resemblance",
+ "fictional-backticked-skill-no-resemblance",
+ "fictional-invocation-no-resemblance",
+ "sdk-call-syntax-no-resemblance",
"exact-tool-name",
"suffix-shorthand",
"plural-family-reference",
- "allowlisted-prose",
+ "bare-prose-adjective-per-file",
+ "bare-prose-adjective-highest-error",
"capitalized-prose-no-mid-word-match",
"entity-noun-after-backticks",
"existing-skill",
"skill-name-in-invocation-context",
- "allowlisted-sdk-call",
+ "sdk-call-distinct-name",
+ "sdk-call-colliding-with-tool-suffix",
],
)
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
+ findings = _check_tool_references(text, "test", _REF_TOOLS, _REF_SKILLS)
+ assert [f.name for f in findings] == 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 error
+ "text,expected_suggestion",
+ [
+ ("use the launch or ship_variant tools instead", "did you mean experiment-ship-variant"),
+ ("search flags with the feature-flags-get-all tool first", "did you mean feature-flag-get-all"),
+ ],
+)
+def test_check_tool_references_suggests_real_tool(text: str, expected_suggestion: str) -> None:
+ (finding,) = _check_tool_references(text, "test", _REF_TOOLS, _REF_SKILLS)
+ assert expected_suggestion in finding.message
+
+
+def test_check_tool_references_reports_line_and_column() -> None:
+ text = "intro line\nsearch with the feature-flags-get-all tool here\n"
+ (finding,) = _check_tool_references(text, "skill.md", _REF_TOOLS, _REF_SKILLS)
+ assert (finding.line, finding.col) == (2, 17)
+ assert finding.name == "feature-flags-get-all"
diff --git a/services/mcp/scripts/lib/tool-references.ts b/services/mcp/scripts/lib/tool-references.ts
index 1955656d4646..d593f9e0159e 100644
--- a/services/mcp/scripts/lib/tool-references.ts
+++ b/services/mcp/scripts/lib/tool-references.ts
@@ -1,7 +1,13 @@
/**
* 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.
+ * or "load the X skill" that resemble a real tool/skill name but don't resolve. Name-level
+ * only: this cannot validate documented schemas or tool behavior.
+ *
+ * The check is heuristic and advisory (callers surface findings, they never block): a candidate
+ * is only flagged when it *resembles* a real name — within NEAR_MISS_MAX_EDITS of one, or an exact
+ * casing miss. Backticks are not treated as intent (prose uses them for emphasis and field names
+ * too), so anything that doesn't resemble a real name is ignored and no name-level allowlist is
+ * needed.
*
* 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
@@ -10,35 +16,20 @@
* examples in tool descriptions.
*/
+// Tool-name validation (length/pattern) findings — kept blocking by the caller.
export type Violation = { source: string; tool: string; reason: string }
+// A heuristic, advisory reference finding, located on the offending line so the caller can render
+// it as an inline annotation.
+export type ReferenceFinding = { source: string; line: number; col: number; name: string; message: 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
- 'secrets-and-integrations', // agent-platform runtime skill (secret-editor deep-link contract), not a repo skill
- '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
- 'secrets-and-integrations', // agent platform skill, lives on feature branch until GA
-])
+// A candidate is only treated as a (stale) reference when it is within this many edits of a real
+// name. Real renames/typos sit at distance 1-2 from the intended tool; ordinary hyphenated prose
+// ("highest-error", "per-file") is far from every name and so is ignored.
+const NEAR_MISS_MAX_EDITS = 2
// "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
@@ -50,33 +41,13 @@ const ENTITY_NOUN_AFTER = /^\s+(?:feature|flag|event|property|properties|column|
// 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 lineCol(text: string, offset: number): { line: number; col: number } {
+ const before = text.slice(0, offset)
+ const lastNewline = before.lastIndexOf('\n')
+ return { line: (before.match(/\n/g)?.length ?? 0) + 1, col: offset - lastNewline }
}
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
@@ -98,10 +69,34 @@ function isValidReference(name: string, kind: ReferenceKind, toolNames: Set<stri
return false
}
-function didYouMean(name: string, toolNames: Set<string>): string {
+function editDistance(a: string, b: string): number {
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i)
+ for (let i = 1; i <= a.length; i++) {
+ const cur = [i]
+ for (let j = 1; j <= b.length; j++) {
+ cur.push(Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1)))
+ }
+ prev = cur
+ }
+ return prev[b.length]!
+}
+
+// Real names this candidate plausibly meant: exact/suffix matches, else near-misses by edit distance.
+function referenceSuggestions(name: string, registry: 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 ')}?` : ''
+ const suffix = [...registry].filter((t) => t === kebab || t.endsWith(`-${kebab}`)).sort()
+ if (suffix.length > 0) {
+ return suffix
+ }
+ return [...registry]
+ .map((known) => ({ known, distance: editDistance(kebab, known) }))
+ .filter(({ distance }) => distance <= NEAR_MISS_MAX_EDITS)
+ .sort((a, b) => a.distance - b.distance || a.known.localeCompare(b.known))
+ .map(({ known }) => known)
+}
+
+function didYouMean(suggestions: string[]): string {
+ return suggestions.length > 0 ? ` — did you mean ${suggestions.join(' or ')}?` : ''
}
export function checkReferencesInText(
@@ -110,34 +105,62 @@ export function checkReferencesInText(
toolNames: Set<string>,
skillNames: Set<string>,
seen: Set<string>,
- violations: Violation[]
+ findings: ReferenceFinding[]
): 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 => {
+ // is one finding. First report wins, so callers scan hand-editable sources first.
+ const report = (offset: number, name: string, message: string): void => {
if (seen.has(name)) {
return
}
seen.add(name)
- violations.push({ source, tool: name, reason })
+ const { line, col } = lineCol(text, offset)
+ findings.push({ source, line, col, name, message })
}
- for (const { name, kind } of findPhraseReferences(text)) {
- if (!isValidReference(name, kind, toolNames, skillNames)) {
- report(name, `references nonexistent ${kind.replace(/s$/, '')}${didYouMean(name, toolNames)}`)
+ // "X tool/skill". Resemblance to a real name is the only signal we trust — backticks in prose
+ // mean emphasis or a field name as often as a reference, so they are not treated as intent.
+ for (const match of text.matchAll(PHRASE_REFERENCE)) {
+ const name = match[1]!
+ const kind = match[2] as ReferenceKind
+ if (isValidReference(name, kind, toolNames, skillNames)) {
+ continue
+ }
+ const registry = kind === 'skill' || kind === 'skills' ? skillNames : toolNames
+ const suggestions = referenceSuggestions(name, registry)
+ if (suggestions.length > 0) {
+ // The match begins at the optional leading backtick, then the name.
+ const offset = match.index + (match[0].startsWith('`') ? 1 : 0)
+ report(
+ offset,
+ name,
+ `'${name}' looks like a ${kind.replace(/s$/, '')} but none exists${didYouMean(suggestions)}`
+ )
}
}
- // "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)}`)
+ // "via `X`": one concrete thing, but not whether tool or skill — check tools (a family prefix
+ // like `feature-flag` is not invocable) plus exact skill names.
+ for (const match of text.matchAll(INVOCATION_REFERENCE)) {
+ if (ENTITY_NOUN_AFTER.test(text.slice(match.index + match[0].length))) {
+ continue
+ }
+ const name = match[1]!
+ if (isValidReference(name, 'tool', toolNames, skillNames) || skillNames.has(name)) {
+ continue
+ }
+ const suggestions = referenceSuggestions(name, toolNames)
+ if (suggestions.length > 0) {
+ // The name sits just after the first backtick in the match.
+ const offset = match.index + match[0].indexOf('`') + 1
+ report(offset, name, `'${name}' looks like a tool but none exists${didYouMean(suggestions)}`)
}
}
- for (const name of findBacktickedSnakeCase(text)) {
+ for (const match of text.matchAll(SNAKE_CASE_REFERENCE)) {
+ const name = match[1]!
if (!toolNames.has(name) && toolNames.has(name.replace(/_/g, '-'))) {
- report(name, `wrong casing — the tool is named ${name.replace(/_/g, '-')}`)
+ const offset = match.index + 1 // skip the opening backtick
+ report(offset, name, `'${name}' has 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.ts
index c833235141d6..af6d00480a4b 100644
--- a/services/mcp/scripts/lint-tool-names.ts
+++ b/services/mcp/scripts/lint-tool-names.ts
@@ -27,7 +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 { checkReferencesInText, type ReferenceFinding, type Violation } from './lib/tool-references'
import {
CategoryConfigSchema,
MAX_TOOL_NAME_LENGTH,
@@ -128,15 +128,15 @@ function discoverSkillNames(): Set<string> {
return skillNames
}
-function validateToolReferences(violations: Violation[], toolNames: Set<string>): void {
+function collectToolReferenceFindings(findings: ReferenceFinding[], 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.
+ // YAML sources first so findings 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)
+ checkReferencesInText(fs.readFileSync(def.filePath, 'utf-8'), label, toolNames, skillNames, seen, findings)
}
if (fs.existsSync(SCHEMA_DIR)) {
@@ -151,13 +151,14 @@ function validateToolReferences(violations: Violation[], toolNames: Set<string>)
toolNames,
skillNames,
seen,
- violations
+ findings
)
}
}
// 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.
+ // means the fix belongs in a Django serializer, followed by regeneration. The label stays a
+ // clean repo-relative path so the CI annotation lands on the file.
const snapshotsDir = path.resolve(MCP_ROOT, 'tests', 'unit', '__snapshots__', 'tool-schemas')
if (fs.existsSync(snapshotsDir)) {
for (const file of fs.readdirSync(snapshotsDir)) {
@@ -165,12 +166,33 @@ function validateToolReferences(violations: Violation[], toolNames: Set<string>)
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)
+ const label = path.relative(REPO_ROOT, filePath)
+ checkReferencesInText(fs.readFileSync(filePath, 'utf-8'), label, toolNames, skillNames, seen, findings)
}
}
}
+// Reference findings are advisory: surface them (as CI annotations on the offending line, or plain
+// warnings locally) but never fail the lint, because the check is a heuristic that can misfire.
+function emitReferenceFindings(findings: ReferenceFinding[]): void {
+ if (findings.length === 0) {
+ return
+ }
+ const inGithubActions = process.env.GITHUB_ACTIONS === 'true'
+ for (const f of findings) {
+ if (inGithubActions) {
+ process.stdout.write(
+ `::warning file=${f.source},line=${f.line},col=${f.col},title=Possible stale reference::${f.message}\n`
+ )
+ } else {
+ process.stderr.write(`${f.source}:${f.line}:${f.col}: warning: ${f.message}\n`)
+ }
+ }
+ process.stderr.write(
+ `\nNote: ${findings.length} possible stale tool/skill reference(s) flagged above (advisory, not blocking).\n`
+ )
+}
+
function main(): void {
const violations: Violation[] = []
let hasErrors = false
@@ -182,24 +204,24 @@ function main(): void {
hasErrors = validateJsonDefinitions(jsonFile, violations, knownToolNames) || hasErrors
}
- validateToolReferences(violations, knownToolNames)
+ const referenceFindings: ReferenceFinding[] = []
+ collectToolReferenceFindings(referenceFindings, knownToolNames)
+ emitReferenceFindings(referenceFindings)
if (violations.length === 0) {
if (!hasErrors) {
process.stdout.write(
- `All tool names pass validation (max ${MAX_TOOL_NAME_LENGTH} chars, pattern ${TOOL_NAME_PATTERN}) and all tool/skill references resolve.\n`
+ `All tool names pass validation (max ${MAX_TOOL_NAME_LENGTH} chars, pattern ${TOOL_NAME_PATTERN}).\n`
)
}
return
}
- process.stderr.write(`Found ${violations.length} tool name / reference violation(s):\n\n`)
+ process.stderr.write(`Found ${violations.length} tool name 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/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.stderr.write(`\nTo fix: shorten or rename the tool name to satisfy the length/pattern constraints.\n`)
process.exitCode = 1
}
diff --git a/services/mcp/tests/unit/tool-references.test.ts b/services/mcp/tests/unit/tool-references.test.ts
index 3b19a9c88e60..5003430dd5f6 100644
--- a/services/mcp/tests/unit/tool-references.test.ts
+++ b/services/mcp/tests/unit/tool-references.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
-import { checkReferencesInText, type Violation } from '../../scripts/lib/tool-references'
+import { checkReferencesInText, type ReferenceFinding } from '../../scripts/lib/tool-references'
const TOOLS = new Set([
'execute-sql',
@@ -12,45 +12,68 @@ const TOOLS = new Set([
])
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
+function flagged(text: string): ReferenceFinding[] {
+ const findings: ReferenceFinding[] = []
+ checkReferencesInText(text, 'test', TOOLS, SKILLS, new Set(), findings)
+ return findings
}
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']],
+ [
+ 'renamed tool (near-miss)',
+ 'search flags with the feature-flags-get-all tool first',
+ ['feature-flags-get-all'],
+ ],
+ ['renamed skill (near-miss)', 'load the finding-experiment skill first', ['finding-experiment']],
['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']],
+ ['one finding when phrase and casing rules overlap', 'use the `execute_sql` tool', ['execute_sql']],
+ // Backticks are not intent: a backticked name that resembles nothing real is left alone.
+ ['fictional backticked tool, no resemblance', 'Use the `experiment_results_summary` tool', []],
+ ['fictional backticked skill, no resemblance', 'load the `managing-unicorns` skill first', []],
+ ['fictional invocation, no resemblance', 'query it via `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', []],
+ ['bare prose adjective (per-file)', 'this is a per-file tool for editing', []],
+ ['bare prose adjective (highest-error)', 'rank by the highest-error tool first', []],
['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)
+ expect(flagged(text).map((f) => f.name)).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.each([
+ [
+ 'suffix and casing matches',
+ 'use the launch or ship_variant tools instead',
+ 'did you mean experiment-ship-variant',
+ ],
+ [
+ 'bare near-miss rename',
+ 'search flags with the feature-flags-get-all tool first',
+ 'did you mean feature-flag-get-all',
+ ],
+ ])('suggests the real tool for %s', (_description, text, expectedSuggestion) => {
+ const [finding] = flagged(text)
+ expect(finding?.message).toContain(expectedSuggestion)
+ })
+
+ it('locates the finding on the offending line and column', () => {
+ const [finding] = flagged('intro line\nsearch with the feature-flags-get-all tool here')
+ expect(finding).toMatchObject({ line: 2, col: 17, name: 'feature-flags-get-all' })
})
- it('dedupes repeated violations across texts via the shared seen set', () => {
- const violations: Violation[] = []
+ it('dedupes repeated findings across texts via the shared seen set', () => {
+ const findings: ReferenceFinding[] = []
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')
+ checkReferencesInText('use the feature-flags-get-all tool', 'a', TOOLS, SKILLS, seen, findings)
+ checkReferencesInText('use the feature-flags-get-all tool', 'b', TOOLS, SKILLS, seen, findings)
+ expect(findings).toHaveLength(1)
+ expect(findings[0]?.source).toBe('a')
})
})