: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
fix(skills): make a skill 404 name the rows skill-list returns (#101549)
posthog[bot]fdc610cae65b
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 3948a919e977..7654ca322503 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,5 +1,6 @@import hashlibfrom collections.abc import Sequence+from difflib import get_close_matchesfrom typing import Any, castfrom urllib.parse import urlencodefrom uuid import UUID@@ -132,7 +133,6 @@ from .skill_services import (delete_skill_file,duplicate_skill,get_active_skill_queryset,- get_latest_skills_queryset,get_skill_by_name_from_db,publish_skill_version,rename_skill,@@ -163,6 +163,11 @@ SKILL_SEARCH_RESULT_LIMIT = 10SKILL_SEARCH_MATCH_LIMIT = 2SKILL_SEARCH_EXCERPT_LENGTH = 300SKILL_SEARCH_TIMEOUT_MS = 5_000+# A 404 offers a few near-miss names, not a listing: `skill-list` is still the way to browse.+MAX_SKILL_NAME_SUGGESTIONS = 3+SKILL_NAME_SUGGESTION_CUTOFF = 0.6+# Ceiling on the names one miss compares against, so a large store cannot make a 404 expensive.+MAX_SKILL_NAME_MATCH_CANDIDATES = 500def _content_search_match(content: str, query: str, *, matched_field: str, path: str) -> dict[str, Any] | None:@@ -499,9 +504,49 @@ class LLMSkillViewSet()return None- def _skill_not_found_response(self, skill_name: str) -> Response:+ def _skill_not_found_response(self, skill_name: str, version: int | None = None) -> Response:+ """A 404 that answers from the same rows `list` returns.++ An agent that lists a skill and then cannot read it concludes the store is inconsistent+ and abandons the skill, so a miss has to say which of the two lookups it is: an unknown+ name (near-miss names the caller can actually read) or a known name at an absent version+ (the versions it does hold).+ """+ visible = self._visible_skills_queryset()+ if version is not None:+ available_versions = list(+ visible.filter(name=skill_name).order_by("version").values_list("version", flat=True)+ )+ if available_versions:+ return Response(+ {+ "detail": (+ f"Skill with name '{skill_name}' has no version {version}. "+ f"Available versions: {', '.join(str(v) for v in available_versions)}."+ ),+ "type": "skill_version_not_found",+ "skill_name": skill_name,+ "available_versions": available_versions,+ },+ status=status.HTTP_404_NOT_FOUND,+ )++ suggestions = get_close_matches(+ skill_name,+ visible.filter(is_latest=True).values_list("name", flat=True)[:MAX_SKILL_NAME_MATCH_CANDIDATES],+ n=MAX_SKILL_NAME_SUGGESTIONS,+ cutoff=SKILL_NAME_SUGGESTION_CUTOFF,+ )+ detail = f"Skill with name '{skill_name}' not found."+ if suggestions:+ detail += " Did you mean " + ", ".join(f"'{name}'" for name in suggestions) + "?"return Response(- {"detail": f"Skill with name '{skill_name}' not found."},+ {+ "detail": detail,+ "type": "skill_not_found",+ "skill_name": skill_name,+ "suggestions": suggestions,+ },status=status.HTTP_404_NOT_FOUND,)@@ -604,12 +649,17 @@ class LLMSkillViewSet(serializer.is_valid(raise_exception=True)return serializer.validated_data+ def _visible_skills_queryset(self) -> QuerySet[LLMSkill]:+ """Every active skill row this caller may read. `list` and every by-name read share it, so+ a name the list returned can never be denied by a read as if it did not exist."""+ return self.user_access_control.filter_queryset_by_access_level(+ get_active_skill_queryset(self.team), resource="llm_skill"+ )+def _get_list_queryset(self, request: Request) -> QuerySet[LLMSkill]:params = self._get_list_params(request)- queryset = self.user_access_control.filter_queryset_by_access_level(- get_latest_skills_queryset(self.team), resource="llm_skill"- )+ queryset = self._visible_skills_queryset().filter(is_latest=True)search = params.get("search", "").strip()if search:@@ -806,7 +856,7 @@ class LLMSkillViewSet(return redirectif skill is None:- return self._skill_not_found_response(skill_name)+ return self._skill_not_found_response(skill_name, version)# Cap the first page when the caller doesn't page explicitly, so body_next_offset is a# valid continuation offset even when the full body would be truncated in transit.@@ -1021,7 +1071,7 @@ class LLMSkillViewSet(str(version_id) if version_id else None,)if skill is None:- return self._skill_not_found_response(skill_name)+ return self._skill_not_found_response(skill_name, version)limit = cast(int, query_params["limit"])offset = cast(int | None, query_params.get("offset"))@@ -1063,7 +1113,7 @@ class LLMSkillViewSet(version = cast(int | None, version_params.get("version"))skill = self._load_skill_with_object_access(request, skill_name, version)if skill is None:- return self._skill_not_found_response(skill_name)+ return self._skill_not_found_response(skill_name, version)# SKILL.md never carries the bundled files, so don't load them just to render it.export = skill.to_export()@@ -1089,7 +1139,7 @@ class LLMSkillViewSet(version = cast(int | None, version_params.get("version"))skill = self._load_skill_with_object_access(request, skill_name, version)if skill is None:- return self._skill_not_found_response(skill_name)+ return self._skill_not_found_response(skill_name, version)export = load_skill_export(skill)problems = _spec_problem_messages(export)@@ -1667,7 +1717,7 @@ class LLMSkillViewSet(version = cast(int | None, version_params.get("version"))skill = self._load_skill_with_object_access(request, skill_name, version)if skill is None:- return self._skill_not_found_response(skill_name)+ return self._skill_not_found_response(skill_name, version)file_path = file_path.rstrip("/")normalized = file_path.replace("\\", "/")diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 2043d5688f44..781de9fbb5f9 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -863,6 +863,38 @@ class TestLLMSkillAPI(APIBaseTest):assert response.status_code == status.HTTP_404_NOT_FOUND+ def test_listed_skill_is_readable_by_the_name_and_version_the_list_returned(self):+ self.create_skill(name="signals-scout-drive-session-completion", version=1)++ listed = self.client.get(self._url()).json()["results"][0]+ response = self.client.get(self._url(f"name/{listed['name']}?version={listed['version']}"))++ assert response.status_code == status.HTTP_200_OK+ assert (response.json()["name"], response.json()["version"]) == (listed["name"], listed["version"])++ def test_get_skill_by_near_miss_name_suggests_the_listed_name(self):+ self.create_skill(name="signals-scout-drive-session-completion")++ response = self.client.get(self._url("name/signals-scout-drive-session?version=1"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ body = response.json()+ assert body["type"] == "skill_not_found"+ assert body["suggestions"] == ["signals-scout-drive-session-completion"]+ assert "signals-scout-drive-session-completion" in body["detail"]++ def test_get_skill_at_absent_version_names_the_versions_the_store_holds(self):+ self.create_skill(name="versioned-skill", version=1, is_latest=False)+ self.create_skill(name="versioned-skill", version=2)++ response = self.client.get(self._url("name/versioned-skill?version=7"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ body = response.json()+ assert body["type"] == "skill_version_not_found"+ assert body["available_versions"] == [1, 2]+ assert "has no version 7" in body["detail"]+@parameterized.expand([("no_query_string", "", None),@@ -2169,6 +2201,27 @@ class TestSkillAccessControlRBAC(APIBaseTest):],}+ def test_not_found_suggestions_omit_skills_the_member_cannot_read(self):+ LLMSkill.objects.create(+ team=self.team,+ name="make-fractals-restricted",+ description="d",+ body="# x\n",+ created_by=self.user,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="llm_skill",+ resource_id=str(self.skill.id),+ access_level="viewer",+ organization_member=OrganizationMembership.objects.get(user=self.member, organization=self.organization),+ )++ response = self.client.get(self._url("name/make-fractal"))++ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.json()["suggestions"] == ["make-fractals"]+@parameterized.expand([("list", ""),diff --git a/services/mcp/src/tools/skills/notFound.ts b/services/mcp/src/tools/skills/notFound.tsindex 22d6685e19c6..d94cee843ffd 100644--- a/services/mcp/src/tools/skills/notFound.ts+++ b/services/mcp/src/tools/skills/notFound.ts@@ -11,6 +11,36 @@ const FILE_MISSING_DETAIL = 'not found in skill'* that emits it, so a 404 without it came from somewhere else. */const SKILL_MISSING_DETAIL = 'Skill with name'+/** `type` values the store stamps on a skill-level 404, telling the two lookups+ * apart: an unknown name, or a known name at a version the store does not hold. */+const VERSION_MISSING_TYPE = 'skill_version_not_found'+const NAME_MISSING_TYPE = 'skill_not_found'++/** The store's 404 body, when it carries the typed shape. Anything else parses to+ * undefined and the generic messages below stand. */+interface SkillMissBody {+ detail?: unknown+ type?: unknown+ suggestions?: unknown+ available_versions?: unknown+}++function parseSkillMissBody(body: string): SkillMissBody | undefined {+ try {+ const parsed: unknown = JSON.parse(body)+ return parsed && typeof parsed === 'object' ? (parsed as SkillMissBody) : undefined+ } catch {+ return undefined+ }+}++function typedArray<T>(value: unknown, isT: (item: unknown) => item is T): T[] {+ return Array.isArray(value) ? value.filter(isT) : []+}++const isString = (item: unknown): item is string => typeof item === 'string'+const isNumber = (item: unknown): item is number => typeof item === 'number'+/** Which kind of miss the message answers. Stamped on the errored `$mcp_tool_call`* so "agents asking the store for a built-in skill" is its own line in the data,* rather than hiding among the typos in one undifferentiated 404 count. */@@ -91,7 +121,42 @@ export function formatSkillLookupMiss(return undefined}- // Both read tools take a `version`, and the store returns this same+ // The store answers from the rows `skill-list` returns, so when it says which+ // lookup missed, that verdict is authoritative and its detail carries the+ // recovery the generic messages below can only guess at.+ const missBody = parseSkillMissBody(apiError.body)+ const serverDetail = typeof missBody?.detail === 'string' ? missBody.detail : undefined++ const availableVersions = typedArray(missBody?.available_versions, isNumber)+ if (missBody?.type === VERSION_MISSING_TYPE && serverDetail && availableVersions.length > 0) {+ // Name the newest one the store holds: a run that pinned a version wants a+ // real version back, not an unpinned read that can race a mid-run publish.+ const newest = Math.max(...availableVersions)+ return {+ kind: 'version',+ message: [+ serverDetail,+ `Run \`call skill-get {"skill_name": "${skillName}", "version": ${newest}}\` to read the newest one.`,+ ].join('\n'),+ }+ }++ // A near-miss name is the common way a read fails on a skill the store holds,+ // and the agent cannot recover from a bare "not found" that denies a name+ // `skill-list` would show. A built-in name keeps the built-in message below:+ // a store name that merely reads like it is not where that skill lives.+ const suggestions = typedArray(missBody?.suggestions, isString)+ if (missBody?.type === NAME_MISSING_TYPE && serverDetail && suggestions.length > 0 && !hint?.isBuiltIn(skillName)) {+ return {+ kind: 'unknown',+ message: [+ serverDetail,+ `Run \`call skill-get {"skill_name": "${suggestions[0]}"}\` if that is the one you want, or \`call skill-list\` to see the skills that are available.`,+ ].join('\n'),+ }+ }++ // Both read tools take a `version`, and an older store returns the same// skill-level detail when the name resolves but the pinned version does not// exist. So a pinned read cannot be told the skill is absent: `skill-list`// would then list the skill the message just denied.diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 191f11b610ed..813af877d638 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -902,6 +902,54 @@ describe('exec tool', () => {)})+ // A near-miss name is how a scout loses its bound skill: the store denies a+ // name `skill-list` would show, and the run reads that as the store being+ // inconsistent rather than as its own typo.+ it('names the near-miss skill the store offered', async () => {+ const exec = createExec([+ makeSkillTool(+ 'skill-get',+ JSON.stringify({+ detail: "Skill with name 'signals-scout-drive-session' not found. Did you mean 'signals-scout-drive-session-completion'?",+ type: 'skill_not_found',+ skill_name: 'signals-scout-drive-session',+ suggestions: ['signals-scout-drive-session-completion'],+ })+ ),+ ])++ const result = (await exec.handler(mockContext, {+ command: 'call skill-get {"skill_name":"signals-scout-drive-session","version":1}',+ })) as string++ expect(result).toContain("Did you mean 'signals-scout-drive-session-completion'?")+ expect(result).toContain('Run `call skill-get {"skill_name": "signals-scout-drive-session-completion"}`')+ })++ it('names the versions the store holds when the pinned one is absent', async () => {+ const exec = createExec([+ makeSkillTool(+ 'skill-get',+ JSON.stringify({+ detail: "Skill with name 'real-skill' has no version 7. Available versions: 1, 2.",+ type: 'skill_version_not_found',+ skill_name: 'real-skill',+ available_versions: [1, 2],+ })+ ),+ ])++ const result = (await exec.handler(mockContext, {+ command: 'call skill-get {"skill_name":"real-skill","version":7}',+ })) as string++ expect(result).toContain('Available versions: 1, 2.')+ expect(result).toContain('Run `call skill-get {"skill_name": "real-skill", "version": 2}`')+ // The store told the two lookups apart, so the message must not repeat the+ // legacy caveat that a version miss could mean the skill is gone.+ expect(result).not.toContain('answers the same way')+ })+// Built-in PostHog skills are a catalog the store never held, so a tool// description that says "load the `<name>` skill" sends an agent here and// the store answers 404. The message above points at `skill-list`, which