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): enforce per-skill permissions on skill reads and writes (#97083)

Jake Ruth5dd6179cc63b
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index 184ad0b1bb2c..fdc3fc86fa7b 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -335,6 +335,8 @@ def model_to_resource(model: Model | type[Model]) -> Optional[APIScopeObject]:
return "customer_task"
if name in ("replayscanner", "replayobservation"):
return "replay_scanner"
+ if name == "llmskill":
+ return "llm_skill"
if name in ("visionalertconfiguration", "visionalertevent"):
return "vision_alert"
# These scopes are served by several viewsets, each with its own model
diff --git a/products/posthog_ai/eval_harness/log_parser.py b/products/posthog_ai/eval_harness/log_parser.py
index de7063675d0b..b97325e538fa 100644
--- a/products/posthog_ai/eval_harness/log_parser.py
+++ b/products/posthog_ai/eval_harness/log_parser.py
@@ -347,13 +347,16 @@ def _index_tool_use_positions(messages: list[dict[str, Any]]) -> dict[str, int]:
return positions
+_CALL_FLAGS = frozenset({"--json", "--confirm", "--no-skills"})
+
+
def _parse_exec_command(command: str) -> tuple[str, dict[str, Any]] | None:
"""Split a CLI-style ``exec`` command string into ``(virtual_name, input)``.
Recognised shapes (produced by single-exec mode where the agent talks to
the PostHog MCP through one ``exec`` tool):
- ``"info <tool>"`` → ``("__info__:<tool>", {})``
- - ``"call [--json] <tool> <json>"`` → ``("<tool>", parsed_json)``
+ - ``"call [--json] [--confirm] [--no-skills] <tool> <json>"`` → ``("<tool>", parsed_json)``
Returns ``None`` for anything else (``search``, ``tools``, ``schema``,
malformed) so callers can fall through to the raw ``exec`` representation.
@@ -373,8 +376,10 @@ def _parse_exec_command(command: str) -> tuple[str, dict[str, Any]] | None:
if head == "call":
rest = rest.strip()
- if rest.startswith("--json"):
- rest = rest[len("--json") :].lstrip()
+ flag, _, remainder = rest.partition(" ")
+ while flag in _CALL_FLAGS:
+ rest = remainder.lstrip()
+ flag, _, remainder = rest.partition(" ")
if not rest:
return None
tool, _, json_part = rest.partition(" ")
diff --git a/products/posthog_ai/eval_harness/test/test_log_parser.py b/products/posthog_ai/eval_harness/test/test_log_parser.py
index 83ab779c5938..1088d33d2bb2 100644
--- a/products/posthog_ai/eval_harness/test/test_log_parser.py
+++ b/products/posthog_ai/eval_harness/test/test_log_parser.py
@@ -306,17 +306,20 @@ class TestLogParserToolCalls(unittest.TestCase):
self.assertEqual(call.raw_name, EXEC_TOOL_NAME)
self.assertEqual(call.output, "results")
- def test_exec_call_with_json_flag_is_unwrapped(self):
- raw = _make_tool_log(
- EXEC_TOOL_NAME,
- {"command": 'call --json query-trends {"x": 2}'},
- )
- parser = LogParser(raw, initial_prompt="hi")
-
- call = parser.get_tool_calls()[0]
- self.assertEqual(call.name, "query-trends")
- self.assertEqual(call.input, {"x": 2})
- self.assertTrue(call.is_exec_unwrapped)
+ def test_exec_call_flags_are_consumed_before_the_tool_name(self):
+ for command in (
+ 'call --json query-trends {"x": 2}',
+ 'call --no-skills query-trends {"x": 2}',
+ 'call --confirm --json query-trends {"x": 2}',
+ ):
+ with self.subTest(command=command):
+ raw = _make_tool_log(EXEC_TOOL_NAME, {"command": command})
+ parser = LogParser(raw, initial_prompt="hi")
+
+ call = parser.get_tool_calls()[0]
+ self.assertEqual(call.name, "query-trends")
+ self.assertEqual(call.input, {"x": 2})
+ self.assertTrue(call.is_exec_unwrapped)
def test_exec_info_command_produces_synthetic_name(self):
raw = _make_tool_log(
diff --git a/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py
index d66b97617d61..e577b6955a12 100644
--- a/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_skill_distribution_scorers.py
@@ -137,6 +137,15 @@ def test_skill_search_must_not_be_parallelized_with_non_learning_exec_commands()
),
SkillLoadedBeforeTool(),
),
+ (
+ _output(
+ _exec("search", "learn -s revenue", QUALIFIED_SKILL),
+ _exec("query", "call execute-sql {}"),
+ _exec("load", f"learn {QUALIFIED_SKILL}"),
+ _exec("retry", "call execute-sql {}"),
+ ),
+ SkillLoadedBeforeTool(),
+ ),
],
)
def test_skill_distribution_scorers_reject_missing_discovery_or_wrong_order(
@@ -302,6 +311,16 @@ def test_exec_distribution_accepts_an_alternate_skill(scorer: Scorer) -> None:
assert _score(scorer, output, EXEC_EXPECTED).score == 0.0
[email protected]("command", ["call --no-skills execute-sql {}", "call --confirm --json execute-sql {}"])
+def test_downstream_call_flags_do_not_hide_the_tool(command: str) -> None:
+ output = _output(
+ _exec("search", "learn -s revenue", QUALIFIED_SKILL),
+ _exec("load", f"learn {QUALIFIED_SKILL}"),
+ _exec("query", command, "[]"),
+ )
+ assert _score(SkillLoadedBeforeTool(), output).score == 1.0
+
+
@pytest.mark.parametrize("scorer", [ExpectedSkillLoaded(), SkillLoadedBeforeTool()])
def test_bundled_distribution_accepts_an_alternate_skill(scorer: Scorer) -> None:
output = _output(
diff --git a/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py
index f9376b300a37..726f37e380de 100644
--- a/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py
+++ b/products/posthog_ai/eval_harness/test/test_skill_usage_scorers.py
@@ -134,6 +134,20 @@ def test_search_recovery_after_zero_hit(calls: list[list[str]], expected_score:
assert result.score == expected_score
[email protected]("learn_first", [True, False])
+def test_search_recovery_rejects_a_product_call_parallel_with_the_learn(learn_first: bool) -> None:
+ zero_hit = _exec("zero", "learn -s xyz", ZERO_HIT)
+ learn = _exec("recover", "learn skills", "posthog:s")
+ product = _exec("give-up", "call execute-sql {}", "[]")
+ first, second = (learn, product) if learn_first else (product, learn)
+ output: dict[str, object] = {
+ "raw_log": "\n".join([*zero_hit, first[0], second[0], first[1], second[1]]),
+ "prompt": "analyze revenue",
+ }
+
+ assert _score(SearchRecoveryAfterZeroHit(), output, _recovery_expected()).score == 0.0
+
+
def test_skill_answer_correctness_self_skips_when_not_requested() -> None:
prepared = SkillAnswerCorrectness()._prepare({"last_message": "anything"}, {})
assert isinstance(prepared, Score)
diff --git a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
index 6414e7d17990..4597bd6d4660 100644
--- a/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/skill_distribution_scorers.py
@@ -390,25 +390,31 @@ class SkillLoadedBeforeTool(Scorer):
loads = _any_skill_loads(parser, skill_spec.skills, skill_spec.delivery, skill_spec.source)
downstream_calls = [call for call in parser.get_tool_calls() if not call.is_error and call.name in tools]
- for load in loads:
- for downstream in downstream_calls:
- if load.position < downstream.position:
- return Score(
- name=self._name(),
- score=1.0,
- metadata={
- "skill": load.skill,
- "delivery": skill_spec.delivery,
- "tool": downstream.name,
- "call_id": downstream.call_id,
- "matched_via": load.matched_via,
- },
- )
+ first_downstream = min(downstream_calls, key=lambda call: call.position, default=None)
+ if first_downstream is not None:
+ load = next((load for load in loads if load.position < first_downstream.position), None)
+ if load is not None:
+ return Score(
+ name=self._name(),
+ score=1.0,
+ metadata={
+ "skill": load.skill,
+ "delivery": skill_spec.delivery,
+ "tool": first_downstream.name,
+ "call_id": first_downstream.call_id,
+ "matched_via": load.matched_via,
+ },
+ )
+ reason = (
+ "A downstream tool ran before the skill was loaded"
+ if loads and first_downstream is not None
+ else "No expected downstream tool ran after the skill was loaded"
+ )
return Score(
name=self._name(),
score=0.0,
metadata={
- "reason": "No expected downstream tool ran after the skill was loaded",
+ "reason": reason,
"skill": skill,
"delivery": skill_spec.delivery,
"tools": tools,
diff --git a/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
index a3182d24008a..317e35538abc 100644
--- a/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
+++ b/products/posthog_ai/evals/cli_mcp/skill_usage_scorers.py
@@ -175,15 +175,20 @@ class SearchRecoveryAfterZeroHit(Scorer):
score=0.0,
metadata={"reason": "No learning follow-up after zero-hit search", "call_id": zero_hit.call_id},
)
- nxt = min(following, key=lambda call: call.position)
- command = _exec_command(nxt)
- if command.verb != "learn":
+ # Parallel tool calls in one turn share a position, so check every call in the earliest batch.
+ earliest = min(call.position for call in following)
+ offender = next(
+ (call for call in following if call.position == earliest and _exec_command(call).verb != "learn"),
+ None,
+ )
+ if offender is not None:
+ command = _exec_command(offender)
return Score(
name=self._name(),
score=0.0,
metadata={
"reason": "A non-learning command followed a zero-hit search",
- "call_id": nxt.call_id,
+ "call_id": offender.call_id,
"command": f"{command.verb} {command.arguments}".strip(),
},
)
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.py
index 976ffeaa57c4..4ff3f67f0cdc 100644
--- a/products/skills/backend/api/skills.py
+++ b/products/skills/backend/api/skills.py
@@ -459,6 +459,24 @@ class LLMSkillViewSet(
status=status.HTTP_404_NOT_FOUND,
)
+ def _load_skill_with_object_access(
+ self,
+ request: Request,
+ skill_name: str,
+ version: int | None = None,
+ version_id: str | None = None,
+ ) -> LLMSkill | None:
+ # has_permission passes anyone with a grant on any one skill, so the loaded row is checked here.
+ skill = get_skill_by_name_from_db(self.team, skill_name, version, version_id)
+ if skill is not None:
+ self.check_object_permissions(request, skill)
+ return skill
+
+ def _guard_object_access(self, request: Request, skill_name: str) -> Response | None:
+ if self._load_skill_with_object_access(request, skill_name) is None:
+ return self._skill_not_found_response(skill_name)
+ return None
+
def _handle_skill_write_error(self, err: Exception, skill_name: str) -> Response | None:
"""Render the error responses shared by create_file / delete_file / rename_file.
@@ -550,7 +568,9 @@ class LLMSkillViewSet(
def _get_list_queryset(self, request: Request) -> QuerySet[LLMSkill]:
params = self._get_list_params(request)
- queryset = get_latest_skills_queryset(self.team)
+ queryset = self.user_access_control.filter_queryset_by_access_level(
+ get_latest_skills_queryset(self.team), resource="llm_skill"
+ )
search = params.get("search", "").strip()
if search:
@@ -739,7 +759,7 @@ class LLMSkillViewSet(
def get_by_name(self, request: Request, skill_name: str = "", **kwargs) -> Response:
version_params = self._get_body_fetch_params(request)
version = cast(int | None, version_params.get("version"))
- skill = get_skill_by_name_from_db(self.team, skill_name, version)
+ skill = self._load_skill_with_object_access(request, skill_name, version)
if skill is None and _is_uuid(skill_name):
redirect = self._redirect_to_name(request, skill_name)
@@ -767,6 +787,7 @@ class LLMSkillViewSet(
skill_by_id = get_active_skill_queryset(self.team).filter(id=skill_name).first()
if skill_by_id is None:
return None
+ self.check_object_permissions(request, skill_by_id)
# Use a relative path (no build_absolute_uri) to avoid embedding the
# Host header in the Location value — prevents host-header open-redirect.
redirect_url = request.get_full_path().replace(skill_name, skill_by_id.name, 1)
@@ -783,6 +804,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
payload = LLMSkillPublishSerializer(data=request.data)
payload.is_valid(raise_exception=True)
@@ -950,11 +975,11 @@ class LLMSkillViewSet(
query_params = self._get_resolve_query_params(request)
version = cast(int | None, query_params.get("version"))
version_id = query_params.get("version_id")
- skill = get_skill_by_name_from_db(
- self.team,
- skill_name=skill_name,
- version=version,
- version_id=str(version_id) if version_id else None,
+ skill = self._load_skill_with_object_access(
+ request,
+ skill_name,
+ version,
+ str(version_id) if version_id else None,
)
if skill is None:
return self._skill_not_found_response(skill_name)
@@ -987,7 +1012,7 @@ class LLMSkillViewSet(
def export(self, request: Request, skill_name: str = "", **kwargs) -> Response | HttpResponse:
version_params = self._get_requested_version_params(request)
version = cast(int | None, version_params.get("version"))
- skill = get_skill_by_name_from_db(self.team, skill_name, version)
+ skill = self._load_skill_with_object_access(request, skill_name, version)
if skill is None:
return self._skill_not_found_response(skill_name)
@@ -1285,6 +1310,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
try:
skill_versions = archive_skill(self.team, skill_name)
except LLMSkillNotFoundError:
@@ -1325,6 +1354,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
payload = LLMSkillDuplicateSerializer(data=request.data)
payload.is_valid(raise_exception=True)
new_name = payload.validated_data["new_name"]
@@ -1386,6 +1419,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
payload = LLMSkillRenameSerializer(data=request.data)
payload.is_valid(raise_exception=True)
new_name = payload.validated_data["new_name"]
@@ -1443,7 +1480,7 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
- skill = get_skill_by_name_from_db(self.team, skill_name)
+ skill = self._load_skill_with_object_access(request, skill_name)
if skill is None:
return self._skill_not_found_response(skill_name)
@@ -1541,7 +1578,7 @@ class LLMSkillViewSet(
def get_file(self, request: Request, skill_name: str = "", file_path: str = "", **kwargs) -> Response:
version_params = self._get_requested_version_params(request)
version = cast(int | None, version_params.get("version"))
- skill = get_skill_by_name_from_db(self.team, skill_name, version)
+ skill = self._load_skill_with_object_access(request, skill_name, version)
if skill is None:
return self._skill_not_found_response(skill_name)
@@ -1575,6 +1612,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
payload = LLMSkillFileCreateSerializer(data=request.data)
payload.is_valid(raise_exception=True)
@@ -1638,6 +1679,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
file_path = file_path.rstrip("/")
normalized = file_path.replace("\\", "/")
if ".." in normalized.split("/") or normalized.startswith("/"):
@@ -1705,6 +1750,10 @@ class LLMSkillViewSet(
if auth_error is not None:
return auth_error
+ access_error = self._guard_object_access(request, skill_name)
+ if access_error is not None:
+ return access_error
+
payload = LLMSkillFileRenameSerializer(data=request.data)
payload.is_valid(raise_exception=True)
diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.py
index 401c57d8ee05..7d97aab88f4d 100644
--- a/products/skills/backend/api/test/test_skills.py
+++ b/products/skills/backend/api/test/test_skills.py
@@ -1993,6 +1993,97 @@ class TestSkillAccessControlRBAC(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED
+ def _other_skill_with_object_grant(self) -> LLMSkill:
+ other = LLMSkill.objects.create(
+ team=self.team,
+ name="theirs",
+ description="d",
+ body="# x\n",
+ version=1,
+ is_latest=True,
+ created_by=self.user,
+ )
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_skill",
+ resource_id=str(other.id),
+ access_level="editor",
+ organization_member=OrganizationMembership.objects.get(user=self.member, organization=self.organization),
+ )
+ return other
+
+ @parameterized.expand(
+ [
+ ("read by name", "get", "name/make-fractals", None),
+ ("resolve by name", "get", "resolve/name/make-fractals", None),
+ ("export", "get", "name/make-fractals/export", None),
+ ("update by name", "patch", "name/make-fractals", {"description": "d2", "base_version": 1}),
+ ("archive", "post", "name/make-fractals/archive", {}),
+ ("duplicate", "post", "name/make-fractals/duplicate", {"new_name": "copy"}),
+ ("rename", "post", "name/make-fractals/rename", {"new_name": "renamed-fractals"}),
+ ("create file", "post", "name/make-fractals/files", {"path": "notes.md", "content": "x"}),
+ ("delete file", "delete", "name/make-fractals/files/SKILL.md", None),
+ ("rename file", "post", "name/make-fractals/files-rename", {"old_path": "a.md", "new_path": "b.md"}),
+ ]
+ )
+ def test_an_object_level_grant_on_one_skill_does_not_reach_another(self, _label, method, path, data):
+ self._other_skill_with_object_grant()
+
+ call = getattr(self.client, method)
+ response = call(self._url(path)) if data is None else call(self._url(path), data=data, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_an_object_level_grant_reaches_the_skill_it_was_granted_on(self):
+ other = self._other_skill_with_object_grant()
+
+ response = self.client.patch(
+ self._url(f"name/{other.name}"),
+ data={"description": "d2", "base_version": 1},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ @parameterized.expand(
+ [(access, endpoint) for access in ("none", "viewer") for endpoint in ("list", "body", "file", "id")]
+ )
+ def test_list_and_reads_respect_individual_skill_grants(self, resource_access: str, endpoint: str) -> None:
+ self._grant_llm_skill_access(resource_access)
+ membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)
+ restricted = LLMSkill.objects.create(
+ team=self.team,
+ name="aaa-restricted",
+ description="Restricted description",
+ body="Restricted instructions",
+ created_by=self.user,
+ )
+ for skill, access in [(self.skill, "viewer"), (restricted, "none")]:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_skill",
+ resource_id=str(skill.id),
+ access_level=access,
+ organization_member=membership,
+ )
+ LLMSkillFile.objects.create(skill=skill, path="reference.md", content=f"Reference for {skill.name}")
+
+ if endpoint == "list":
+ response = self.client.get(self._url(), {"limit": "1", "order_by": "name"})
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count"] == 1
+ assert [skill["name"] for skill in response.json()["results"]] == [self.skill.name]
+ return
+
+ allowed_status = status.HTTP_302_FOUND if endpoint == "id" else status.HTTP_200_OK
+ for skill, expected_status in [(self.skill, allowed_status), (restricted, status.HTTP_403_FORBIDDEN)]:
+ name = str(skill.id) if endpoint == "id" else skill.name
+ suffix = "/files/reference.md" if endpoint == "file" else ""
+ version_params: list[dict[str, int]] = [{}, {"version": 1}]
+ for params in version_params:
+ response = self.client.get(self._url(f"name/{name}{suffix}"), params)
+ assert response.status_code == expected_status, (endpoint, skill.name, params, response.content)
+
def test_org_admin_has_full_access_without_explicit_grant(self):
membership = OrganizationMembership.objects.get(user=self.member, organization=self.organization)
membership.level = OrganizationMembership.Level.ADMIN
diff --git a/services/mcp/src/skills/project-skill-catalog.ts b/services/mcp/src/skills/project-skill-catalog.ts
index 55d9d024f1fa..caa4c4b017d0 100644
--- a/services/mcp/src/skills/project-skill-catalog.ts
+++ b/services/mcp/src/skills/project-skill-catalog.ts
@@ -157,12 +157,17 @@ export class ProjectSkillCatalog {
return {
identifier: `project:${name}`,
description,
+ // Name and description matches carry no path; the header already prints both.
snippets: dedupeSnippets(
- matches.map((match) => ({
- path: match.path ?? match.matched_field,
- line: match.line ?? 1,
- text: match.excerpt,
- }))
+ matches
+ .filter(
+ (match): match is Schemas.LLMSkillSearchMatch & { path: string } => match.path !== undefined
+ )
+ .map((match) => ({
+ path: match.path,
+ line: match.line ?? 1,
+ text: match.excerpt,
+ }))
),
// Scored client-side so project and PostHog results merge into one relevance order.
score: scoreProjectSearchResult(
diff --git a/services/mcp/src/tools/exec-learn.ts b/services/mcp/src/tools/exec-learn.ts
index 92ab3765a888..4d6aebadf634 100644
--- a/services/mcp/src/tools/exec-learn.ts
+++ b/services/mcp/src/tools/exec-learn.ts
@@ -325,15 +325,17 @@ export class ExecLearnCatalog {
}
private async zeroHitRecovery(query: string): Promise<string> {
+ const projectSearched = this.skillSources?.project !== undefined
const header =
`No skills matched "${query}".\n` +
- 'None of the query words appear in any skill. Try fewer or broader keywords (single words match best).'
+ (projectSearched
+ ? 'None of the query words appear in any skill.'
+ : 'None of the query words appear in any PostHog skill; project skills were not searched.') +
+ ' Try fewer or broader keywords (single words match best).'
const posthogNames = this.skillSources?.posthog?.listNames() ?? []
let projectListing: ProjectSkillList | undefined
- if (!this.skillSources?.project) {
- projectListing = { count: 0, names: [], truncated: false }
- } else {
+ if (this.skillSources?.project) {
try {
projectListing = await this.skillSources.project.listNames()
} catch {
@@ -341,12 +343,13 @@ export class ExecLearnCatalog {
}
}
- if (projectListing && posthogNames.length + projectListing.count <= ZERO_HIT_INLINE_LIMIT) {
+ const projectCount = projectSearched ? projectListing?.count : 0
+ if (projectCount !== undefined && posthogNames.length + projectCount <= ZERO_HIT_INLINE_LIMIT) {
const lines = [header, '', 'Available skills:']
if (posthogNames.length > 0) {
lines.push(`posthog: ${posthogNames.join(', ')}`)
}
- if (projectListing.names.length > 0) {
+ if (projectListing && projectListing.names.length > 0) {
lines.push(`project: ${projectListing.names.join(', ')}`)
}
return lines.join('\n')
@@ -356,7 +359,9 @@ export class ExecLearnCatalog {
// claiming "0 project skills" would send the agent down the no-skill path.
const counts = projectListing
? `${posthogNames.length} posthog and ${projectListing.count} project skills exist`
- : `${posthogNames.length} posthog skills exist; the project skill listing is temporarily unavailable`
+ : projectSearched
+ ? `${posthogNames.length} posthog skills exist; the project skill listing is temporarily unavailable`
+ : `${posthogNames.length} posthog skills exist; project skills were not searched`
return (
`${header}\n\n` +
`${counts} — ` +
diff --git a/services/mcp/tests/unit/project-skill-catalog.test.ts b/services/mcp/tests/unit/project-skill-catalog.test.ts
index 215e976e7d2e..3896dd194ed7 100644
--- a/services/mcp/tests/unit/project-skill-catalog.test.ts
+++ b/services/mcp/tests/unit/project-skill-catalog.test.ts
@@ -227,6 +227,26 @@ describe('ProjectSkillCatalog', () => {
expect(request).toHaveBeenCalledTimes(1)
})
+ it('renders only path-bearing matches as snippets', async () => {
+ const request = vi.fn(async () => ({
+ results: [
+ {
+ name: 'retention-analysis',
+ description: 'Find where users stop returning.',
+ matches: [
+ { matched_field: 'name', excerpt: 'retention-analysis' },
+ { matched_field: 'body', path: 'SKILL.md', line: 3, excerpt: 'Weekly retention cohorts.' },
+ ],
+ },
+ ],
+ }))
+ const catalog = new ProjectSkillCatalog(makeContext(request))
+
+ const [result] = await catalog.searchResults('retention')
+
+ expect(result!.snippets).toEqual([{ path: 'SKILL.md', line: 3, text: 'Weekly retention cohorts.' }])
+ })
+
it('surfaces a body-only match via per-token search when the whole query misses', async () => {
const request = vi.fn(async ({ path, query }: { path: string; query?: any }) => {
if (path.endsWith('/search/')) {
diff --git a/services/mcp/tests/unit/skill-catalog.test.ts b/services/mcp/tests/unit/skill-catalog.test.ts
index 5e7dd3577853..d17b7b32f35b 100644
--- a/services/mcp/tests/unit/skill-catalog.test.ts
+++ b/services/mcp/tests/unit/skill-catalog.test.ts
@@ -380,6 +380,20 @@ describe('SkillCatalog and exec learn', () => {
expect(output).toContain('learn skills')
}
})
+
+ it('does not report zero project skills when the project source is unavailable', async () => {
+ const learn = new ExecLearnCatalog([], {
+ posthog: makeCatalog(),
+ projectUnavailableReason: 'This connection is missing the llm_skill:read scope.',
+ })
+
+ const output = await learn.execute('-s zzzznomatch')
+
+ expect(output).toContain('project skills were not searched')
+ expect(output).not.toContain('0 project skills')
+ expect(output).toContain('posthog: funnels, retention-analysis')
+ expect(output).toContain('[Project skills unavailable: This connection is missing the llm_skill:read scope.]')
+ })
describe('skill invocation reporting', () => {
it('reports successful loads with source, path, and read kind — never searches or describes', async () => {
const invocations: unknown[] = []