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.

feat(llma): community skills browse/install/vote API (2/7) (#65011)

Andrew Maguirec7177bf1b953
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.md
new file mode 100644
index 000000000000..22110cac0f63
--- /dev/null
+++ b/docs/internal/skills/community-skills-api.md
@@ -0,0 +1,69 @@
+# Community skills API
+
+The community skills marketplace lets a team browse, install, and upvote agent skills shared
+through the [`PostHog/community-skills`](https://github.com/PostHog/community-skills) repo.
+The catalog is an **instance-global** read-model — it is not team-scoped — synced hourly from the
+repo's `registry.json`.
+Installing copies a catalog entry into the team as a regular `LLMSkill`.
+
+Viewset: `products/skills/backend/api/community_skills.py` (`CommunitySkillViewSet`).
+Route: registered in `products/skills/backend/routes.py` as `community_skills` under
+`/api/projects/{team_id}/community_skills/`.
+
+## Authentication and gating
+
+- Web-app session auth only (`scope_object = "INTERNAL"`); the endpoint is **not** exposed for
+ personal-API-key scoping, since the catalog is instance-global.
+- Gated by `CommunitySkillFeatureFlagPermission`, which requires **both**
+ `llm-analytics-community-skills` (the marketplace) and `llm-analytics-skills` (the base skills
+ product the installed skill lands in) to be enabled.
+ The flag is evaluated with the organization **and** project group so a per-project rollout matches
+ in-app evaluation, and `POSTHOG_FEATURE_FLAGS_FORCE_ENABLED` is honored for self-hosted.
+- `install` and `vote` additionally require resource-level `editor` access on `llm_skill`, and are
+ rate-limited by a burst + sustained throttle.
+
+## Endpoints
+
+| Method | Path | Purpose |
+| ------ | ---------------------------------- | ----------------------------------------------------- |
+| `GET` | `community_skills/` | List catalog entries (paginated; body omitted). |
+| `GET` | `community_skills/{slug}/` | Retrieve one entry, including body and file manifest. |
+| `POST` | `community_skills/{slug}/install/` | Copy the entry into the team as an `LLMSkill`. |
+| `POST` | `community_skills/{slug}/vote/` | Toggle the requesting user's upvote. |
+
+`{slug}` is the repo directory name.
+Slugs are validated at sync against the skill-name pattern, so they are always routable by DRF's
+default lookup regex (no `.` or `/`).
+
+### List filters (`GET community_skills/`)
+
+| Param | Behavior |
+| ------------ | ------------------------------------------------------------------------------------------------------ |
+| `search` | Case-insensitive substring on name and description; also matches a tag exactly (case-insensitive). |
+| `tag` | Returns only skills carrying this exact tag (case-insensitive; tags are stored lowercased at sync). |
+| `trust_tier` | One of `official`, `verified`, `community`. |
+| `order_by` | One of name/created_at/published_at/install_count/vote_count (± prefix). Defaults to `-install_count`. |
+
+## Install behavior
+
+`install_community_skill` (`community_skill_services.py`) copies the entry into a new `LLMSkill`
+named after `new_name` (defaulting to the slug) and bumps the catalog's `install_count`.
+Because catalog content originates outside the app, the install path re-validates it rather than
+trusting the sync:
+
+- Bundled file paths and sizes are re-checked with the same guards as normal skill creation.
+- Installs into auto-running namespaces are refused: the `signals-scout-` and `review-hog-` prefixes,
+ whose skills PostHog registers and runs on its own (Signals scouts run with privileged scopes,
+ ReviewHog skills auto-enable in a team's PR reviews). The whole `review-hog-` prefix is reserved,
+ not only ReviewHog's canonical names, because `products.skills` can't import `products.review_hog`
+ to read that list — `review_hog` already depends on `skills`, so the import would cycle. Install a
+ community skill whose slug starts with either prefix under a different `new_name`.
+- ReviewHog provenance keys (`seeded_by`, `canonical_hash`, `source`) are stripped from copied
+ metadata so a catalog entry can't make an installed skill get pruned by ReviewHog's sync.
+- Entries with an empty body or description are rejected (an empty description would later fail
+ export validation).
+- The catalog row is locked and its `deleted` flag re-checked before copying, so a skill removed from
+ the catalog mid-install can't be installed.
+
+Errors surface as `400` (invalid payload / duplicate name) or `404` (unknown or removed slug).
+A duplicate-name conflict only blames the `new_name` field when the caller actually supplied it.
diff --git a/products/skills/backend/api/community_skill_serializers.py b/products/skills/backend/api/community_skill_serializers.py
new file mode 100644
index 000000000000..47f432adee71
--- /dev/null
+++ b/products/skills/backend/api/community_skill_serializers.py
@@ -0,0 +1,164 @@
+from typing import Any
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillTrustTier
+
+ALLOWED_LIST_ORDERINGS = frozenset(
+ {
+ "name",
+ "-name",
+ "created_at",
+ "-created_at",
+ "published_at",
+ "-published_at",
+ "install_count",
+ "-install_count",
+ "vote_count",
+ "-vote_count",
+ }
+)
+
+
+class CommunitySkillFileSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = CommunitySkillFile
+ fields = ["path", "content", "content_type"]
+
+
+class CommunitySkillFileManifestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = CommunitySkillFile
+ fields = ["path", "content_type"]
+
+
+class CommunitySkillSerializer(serializers.ModelSerializer):
+ allowed_tools = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=list,
+ help_text="Tools the skill declares it may use. Surface these to the user before install.",
+ )
+ metadata = serializers.DictField(
+ required=False,
+ default=dict,
+ help_text="Arbitrary key-value metadata carried from the skill's frontmatter.",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=list,
+ help_text="Free-form tags used for filtering and discovery.",
+ )
+ trust_tier = serializers.ChoiceField(
+ choices=CommunitySkillTrustTier.choices,
+ help_text="Moderation tier: 'official' (PostHog-authored), 'verified' (reviewed), or 'community'.",
+ )
+ files = serializers.SerializerMethodField(
+ help_text="Bundled files manifest — path and content_type only. File contents are copied in on install.",
+ )
+ vote_count = serializers.SerializerMethodField(
+ help_text="Total number of upvotes this skill has received.",
+ )
+ has_voted = serializers.SerializerMethodField(
+ help_text="Whether the requesting user has upvoted this skill.",
+ )
+
+ class Meta:
+ model = CommunitySkill
+ fields = [
+ "id",
+ "slug",
+ "name",
+ "description",
+ "body",
+ "license",
+ "compatibility",
+ "allowed_tools",
+ "metadata",
+ "tags",
+ "trust_tier",
+ "author_handle",
+ "github_url",
+ "files",
+ "install_count",
+ "vote_count",
+ "has_voted",
+ "published_at",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "slug": {"help_text": "Stable identifier matching the skill's directory in the community-skills repo."},
+ "name": {"help_text": "Display name of the skill."},
+ "description": {"help_text": "What the skill does and when to use it."},
+ "body": {"help_text": "The SKILL.md instruction content (markdown)."},
+ "license": {"help_text": "License name or reference."},
+ "compatibility": {"help_text": "Environment requirements declared by the skill."},
+ "author_handle": {"help_text": "GitHub handle (or name) of the contributor who published the skill."},
+ "github_url": {"help_text": "Link to the skill's source directory on GitHub."},
+ "install_count": {"help_text": "Number of times this skill has been installed into a team."},
+ "published_at": {"help_text": "When the skill was first published to the community repo."},
+ }
+
+ @extend_schema_field(CommunitySkillFileManifestSerializer(many=True))
+ def get_files(self, instance: CommunitySkill) -> list[dict[str, Any]]:
+ # Iterate the related manager so prefetch_related's cache is used — .values() would issue a
+ # second query and defeat the viewset's manifest-only prefetch.
+ return [{"path": f.path, "content_type": f.content_type} for f in instance.files.all()]
+
+ def get_vote_count(self, instance: CommunitySkill) -> int:
+ # Provided by the viewset's annotated queryset; fall back to a count for unannotated instances.
+ annotated = getattr(instance, "vote_count", None)
+ return int(annotated) if annotated is not None else instance.votes.count()
+
+ def get_has_voted(self, instance: CommunitySkill) -> bool:
+ return bool(getattr(instance, "has_voted", False))
+
+
+class CommunitySkillListSerializer(CommunitySkillSerializer):
+ """List serializer that omits body and file manifest — progressive disclosure."""
+
+ class Meta(CommunitySkillSerializer.Meta):
+ fields = [f for f in CommunitySkillSerializer.Meta.fields if f not in ("body", "files")]
+ read_only_fields = fields
+
+
+class CommunitySkillListQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Substring filter on skill names and descriptions; also matches a tag exactly (case-insensitive).",
+ )
+ tag = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Return only skills carrying this exact tag (case-insensitive).",
+ )
+ trust_tier = serializers.ChoiceField(
+ choices=CommunitySkillTrustTier.choices,
+ required=False,
+ help_text="Filter to a single moderation tier.",
+ )
+ order_by = serializers.ChoiceField(
+ choices=sorted(ALLOWED_LIST_ORDERINGS),
+ required=False,
+ default="-install_count",
+ help_text="Sort key. Defaults to most-installed first.",
+ )
+
+
+class CommunitySkillInstallSerializer(serializers.Serializer):
+ new_name = serializers.CharField(
+ max_length=64,
+ required=False,
+ allow_blank=True,
+ help_text="Name for the installed skill in your team. Defaults to the community skill's slug.",
+ )
+
+
+class CommunitySkillVoteResponseSerializer(serializers.Serializer):
+ vote_count = serializers.IntegerField(help_text="Total upvotes after applying the toggle.")
+ has_voted = serializers.BooleanField(help_text="Whether the requesting user is now an upvoter.")
diff --git a/products/skills/backend/api/community_skill_services.py b/products/skills/backend/api/community_skill_services.py
new file mode 100644
index 000000000000..a508f3cae6c7
--- /dev/null
+++ b/products/skills/backend/api/community_skill_services.py
@@ -0,0 +1,177 @@
+from django.db import IntegrityError, transaction
+from django.db.models import F
+
+from rest_framework.serializers import ValidationError as DRFValidationError
+
+from posthog.models import Team, User
+
+from ..models.community_skills import CommunitySkill, CommunitySkillVote
+from ..models.skills import LLMSkill
+from .skill_serializers import validate_allowed_tool, validate_skill_file_path, validate_skill_name_value
+from .skill_services import MAX_SKILL_FILE_BYTES, create_skill
+
+# Namespaces where PostHog auto-registers and runs a skill under privileged scopes on an enrolled
+# team: Signals scouts on the scout coordinator, ReviewHog's review skills on a team's first PR
+# review. An install landing on one of these names would auto-run a contributor's instructions
+# against the installing team, so the whole prefix is reserved — the canonical skills in each
+# namespace are seeded through their own authorized path and never arrive via install. Reserving by
+# prefix rather than by exact canonical name keeps this module free of a cross-product import
+# (`products.review_hog` already depends on `products.skills`, so the reverse edge is a cycle) and
+# can't drift as either namespace grows. A community skill named in one of these spaces is still
+# installable under a different `new_name`.
+RESERVED_INSTALL_NAME_PREFIXES: dict[str, str] = {
+ "signals-scout-": "PostHog-managed Signals scouts",
+ "review-hog-": "PostHog-managed review skills",
+}
+
+# Provenance keys ReviewHog stamps on the rows it manages. Its prune keys on `seeded_by`, so if a
+# catalog entry carried these they could make a user's freshly installed skill disappear on the next
+# review sync — strip them before stamping community provenance, the way duplicate_skill drops seeded_by.
+_INTERNAL_METADATA_KEYS = frozenset({"seeded_by", "canonical_hash", "source"})
+
+
+class CommunitySkillNotFoundError(Exception):
+ pass
+
+
+class CommunitySkillInvalidPayloadError(Exception):
+ """The synced catalog entry can't be safely copied into a team — a traversal/reserved file path,
+ oversized file content, a whitespace-bearing tool name, an empty body, or a reserved privileged
+ namespace. Surfaced as a 400 rather than persisting a malformed team skill."""
+
+ def __init__(self, detail: str) -> None:
+ self.detail = detail
+ super().__init__(detail)
+
+
+def get_community_skill_by_slug(slug: str) -> CommunitySkill | None:
+ return CommunitySkill.objects.filter(slug=slug, deleted=False).first()
+
+
+def _first_error_detail(err: DRFValidationError) -> str:
+ detail = err.detail
+ if isinstance(detail, list) and detail:
+ return str(detail[0])
+ return str(detail)
+
+
+def _validate_installable_files(source: CommunitySkill) -> list[dict[str, str]]:
+ """Re-run the same path/size guards as the regular skill create/import flows.
+
+ create_skill only checks file count and exact-duplicate paths, so without this a catalog file
+ shipping `../x`, a reserved name, control characters, or oversized content would be persisted
+ into the team skill and later corrupt exports or marketplace clones.
+ """
+ validated: list[dict[str, str]] = []
+ for f in source.files.all():
+ try:
+ path = validate_skill_file_path(f.path)
+ except DRFValidationError as err:
+ raise CommunitySkillInvalidPayloadError(
+ f"Bundled file '{f.path}' is invalid: {_first_error_detail(err)}"
+ ) from err
+ if len(f.content.encode("utf-8")) > MAX_SKILL_FILE_BYTES:
+ raise CommunitySkillInvalidPayloadError(f"Bundled file '{path}' exceeds the size limit.")
+ validated.append({"path": path, "content": f.content, "content_type": f.content_type})
+ return validated
+
+
+def install_community_skill(
+ *,
+ team: Team,
+ user: User,
+ slug: str,
+ new_name: str | None = None,
+) -> LLMSkill:
+ """Copy a community skill into a team as a regular LLMSkill and bump its install counter.
+
+ Raises CommunitySkillNotFoundError if the slug is unknown, LLMSkillDuplicateNameConflictError
+ if the target name already exists in the team, and CommunitySkillInvalidPayloadError if the
+ catalog entry can't be safely installed.
+ """
+ community_skill = get_community_skill_by_slug(slug)
+ if community_skill is None:
+ raise CommunitySkillNotFoundError()
+
+ try:
+ target_name = validate_skill_name_value(new_name or community_skill.slug)
+ except DRFValidationError as err:
+ raise CommunitySkillInvalidPayloadError(_first_error_detail(err)) from err
+
+ for prefix, owner in RESERVED_INSTALL_NAME_PREFIXES.items():
+ if target_name.startswith(prefix):
+ raise CommunitySkillInvalidPayloadError(
+ f"That name is reserved for {owner} and can't be used for a community install."
+ )
+
+ for tool in community_skill.allowed_tools or []:
+ try:
+ validate_allowed_tool(tool)
+ except DRFValidationError as err:
+ raise CommunitySkillInvalidPayloadError(_first_error_detail(err)) from err
+
+ with transaction.atomic():
+ # Lock the catalog row so a concurrent sync can't replace the body/metadata after we read
+ # them but before we copy the files — otherwise the install could be a hybrid of two
+ # revisions. create_skill + the counter bump then commit together or not at all.
+ locked = CommunitySkill.objects.select_for_update().get(pk=community_skill.pk)
+ # A concurrent sync could have soft-deleted the row between the initial lookup and this lock;
+ # a PK query still returns it, so recheck under the lock rather than installing a removed skill.
+ if locked.deleted:
+ raise CommunitySkillNotFoundError()
+ if not (locked.body or "").strip():
+ raise CommunitySkillInvalidPayloadError("This community skill has no instructions and can't be installed.")
+ # A blank description passes the sync's length-only check but later makes the installed skill
+ # fail export validation, so reject it here rather than persisting an un-exportable skill.
+ if not (locked.description or "").strip():
+ raise CommunitySkillInvalidPayloadError("This community skill has no description and can't be installed.")
+ files = _validate_installable_files(locked)
+
+ installed = create_skill(
+ team,
+ user=user,
+ name=target_name,
+ description=locked.description,
+ body=locked.body,
+ license=locked.license,
+ compatibility=locked.compatibility,
+ allowed_tools=locked.allowed_tools,
+ # Stamp provenance so an installed skill can be traced back to its community source, but
+ # first drop any internal ReviewHog ownership keys the catalog entry might carry.
+ metadata={
+ **{k: v for k, v in (locked.metadata or {}).items() if k not in _INTERNAL_METADATA_KEYS},
+ "community_skill_slug": locked.slug,
+ "community_skill_id": str(locked.id),
+ },
+ files=files or None,
+ )
+
+ CommunitySkill.objects.filter(pk=locked.pk).update(install_count=F("install_count") + 1)
+ return installed
+
+
+def toggle_community_skill_vote(*, slug: str, user: User) -> tuple[int, bool]:
+ """Add or remove the user's upvote. Returns (vote_count, has_voted) after the toggle."""
+ community_skill = get_community_skill_by_slug(slug)
+ if community_skill is None:
+ raise CommunitySkillNotFoundError()
+
+ with transaction.atomic():
+ existing = CommunitySkillVote.objects.filter(skill=community_skill, user=user).first()
+ if existing is not None:
+ existing.delete()
+ has_voted = False
+ else:
+ try:
+ # Nested atomic → a SAVEPOINT: if a concurrent request inserted the vote first, the
+ # IntegrityError rolls back only to here, leaving the outer transaction healthy so
+ # the count() below still runs (a bare except would poison the whole transaction).
+ with transaction.atomic():
+ CommunitySkillVote.objects.create(skill=community_skill, user=user)
+ has_voted = True
+ except IntegrityError:
+ # Concurrent request created the vote first — converge on the "voted" state.
+ has_voted = True
+ vote_count = CommunitySkillVote.objects.filter(skill=community_skill).count()
+
+ return vote_count, has_voted
diff --git a/products/skills/backend/api/community_skill_sync.py b/products/skills/backend/api/community_skill_sync.py
index d452a67362e9..f6c868b46cd5 100644
--- a/products/skills/backend/api/community_skill_sync.py
+++ b/products/skills/backend/api/community_skill_sync.py
@@ -201,7 +201,9 @@ def _upsert_community_skill(entry: dict[str, Any]) -> bool:
# .get return None, which these non-nullable JSON columns reject at insert time.
"allowed_tools": entry.get("allowed_tools") or [],
"metadata": entry.get("metadata") or {},
- "tags": entry.get("tags") or [],
+ # Store tags lowercased so the tag/search filters match regardless of how a contributor
+ # capitalized them in frontmatter (_validate_entry_shape guarantees a list of strings).
+ "tags": [t.lower() for t in (entry.get("tags") or [])],
"trust_tier": trust_tier,
"author_handle": _text(entry, "author_handle", "'author_handle'"),
"github_url": _text(entry, "github_url", "'github_url'"),
diff --git a/products/skills/backend/api/community_skills.py b/products/skills/backend/api/community_skills.py
new file mode 100644
index 000000000000..d5c4391daf59
--- /dev/null
+++ b/products/skills/backend/api/community_skills.py
@@ -0,0 +1,254 @@
+from typing import Any, cast
+
+from django.db.models import Count, Exists, OuterRef, Prefetch, Q, QuerySet
+
+import structlog
+import posthoganalytics
+from drf_spectacular.utils import extend_schema
+from rest_framework import mixins, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.permissions import BasePermission
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
+from posthog.models import User
+from posthog.permissions import _FORCE_ENABLED_FLAGS, get_organization_from_view
+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle
+
+from ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillVote
+from .community_skill_serializers import (
+ CommunitySkillInstallSerializer,
+ CommunitySkillListQuerySerializer,
+ CommunitySkillListSerializer,
+ CommunitySkillSerializer,
+ CommunitySkillVoteResponseSerializer,
+)
+from .community_skill_services import (
+ CommunitySkillInvalidPayloadError,
+ CommunitySkillNotFoundError,
+ install_community_skill,
+ toggle_community_skill_vote,
+)
+from .skill_serializers import LLMSkillSerializer
+from .skill_services import LLMSkillDuplicateNameConflictError, LLMSkillFileLimitError, LLMSkillFilePathConflictError
+
+logger = structlog.get_logger(__name__)
+
+COMMUNITY_SKILL_FEATURE_FLAG = "llm-analytics-community-skills"
+# Installing copies into a regular LLMSkill, whose UI and APIs are gated by this base flag — so the
+# marketplace also requires it, otherwise installed skills would be unreachable.
+BASE_SKILL_FEATURE_FLAG = "llm-analytics-skills"
+
+
+class CommunitySkillBurstThrottle(PersonalApiKeyOrUserRateThrottle):
+ # Web-aware burst throttle: this endpoint is session-authenticated, so the default
+ # PersonalApiKeyRateThrottle (personal-API-key only) would leave it unthrottled.
+ scope = "burst"
+ rate = "480/minute"
+
+
+class CommunitySkillSustainedThrottle(PersonalApiKeyOrUserRateThrottle):
+ scope = "sustained"
+ rate = "4800/hour"
+
+
+class CommunitySkillFeatureFlagPermission(BasePermission):
+ def has_permission(self, request, view) -> bool:
+ user = cast(User, request.user)
+ organization = get_organization_from_view(view)
+ org_id = str(organization.id)
+ distinct_id = user.distinct_id or str(user.uuid)
+
+ groups: dict[str, str] = {"organization": org_id}
+ group_properties: dict[str, dict[str, str]] = {"organization": {"id": org_id}}
+ # Match in-app flag evaluation: posthog-js carries project (team) context, so a per-project
+ # rollout evaluates True in the UI but would 403 here if we only sent the organization group.
+ try:
+ team_for_flag = view.team
+ except (ValueError, KeyError, AttributeError):
+ team_for_flag = None
+ if team_for_flag is not None:
+ project_id = str(team_for_flag.id)
+ groups["project"] = project_id
+ group_properties["project"] = {"id": project_id}
+
+ # Honor POSTHOG_FEATURE_FLAGS_FORCE_ENABLED so self-hosted deployments can enable the
+ # marketplace without a round-trip to PostHog Cloud, matching the canonical permission.
+ return all(
+ flag in _FORCE_ENABLED_FLAGS
+ or bool(
+ posthoganalytics.feature_enabled(
+ flag,
+ distinct_id,
+ groups=groups,
+ group_properties=group_properties,
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ for flag in (COMMUNITY_SKILL_FEATURE_FLAG, BASE_SKILL_FEATURE_FLAG)
+ )
+
+
+class CommunitySkillViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.RetrieveModelMixin,
+ viewsets.GenericViewSet,
+):
+ # The community catalog is instance-global, so this endpoint is web-app only and not
+ # exposed for personal-API-key scoping. Team context comes from the URL for install/vote.
+ scope_object = "INTERNAL"
+ serializer_class = CommunitySkillSerializer
+ permission_classes = [CommunitySkillFeatureFlagPermission]
+ lookup_field = "slug"
+
+ def get_throttles(self):
+ if self.action in ("install", "vote"):
+ return [CommunitySkillBurstThrottle(), CommunitySkillSustainedThrottle()]
+ return super().get_throttles()
+
+ def dangerously_get_queryset(self) -> QuerySet[CommunitySkill]:
+ # Deliberately bypasses team/parent filtering: CommunitySkill is a shared, instance-global
+ # catalog with no team_id. Access is gated by the feature-flag permission above.
+ user = cast(User, self.request.user)
+ queryset = CommunitySkill.objects.filter(deleted=False).annotate(
+ vote_count=Count("votes", distinct=True),
+ has_voted=Exists(CommunitySkillVote.objects.filter(skill=OuterRef("pk"), user=user)),
+ )
+ if self.action == "list":
+ # The list serializer omits body; bodies run up to 1 MB, so don't haul a page of them
+ # out of Postgres only to discard them.
+ return queryset.defer("body")
+ # Detail renders the files manifest (path + content_type) but never file content — prefetch
+ # only those columns so a skill with dozens of 1 MB files doesn't load megabytes we discard.
+ return queryset.prefetch_related(
+ Prefetch("files", queryset=CommunitySkillFile.objects.only("path", "content_type", "skill_id"))
+ )
+
+ def get_serializer_class(self):
+ if self.action == "list":
+ return CommunitySkillListSerializer
+ return super().get_serializer_class()
+
+ @extend_schema(
+ parameters=[CommunitySkillListQuerySerializer], responses={200: CommunitySkillListSerializer(many=True)}
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ params = CommunitySkillListQuerySerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+
+ queryset = self.get_queryset()
+ search = params.validated_data.get("search", "").strip()
+ if search:
+ # Substring-match name/description; tags is a JSONField array of lowercased slugs, so
+ # match a tag exactly (case-folded) rather than substring-matching the serialized JSON.
+ queryset = queryset.filter(
+ Q(name__icontains=search) | Q(description__icontains=search) | Q(tags__contains=[search.lower()])
+ )
+ # Tags are stored lowercased at sync, so case-fold the query to keep the filter case-insensitive.
+ tag = params.validated_data.get("tag", "").strip().lower()
+ if tag:
+ queryset = queryset.filter(tags__contains=[tag])
+ trust_tier = params.validated_data.get("trust_tier")
+ if trust_tier:
+ queryset = queryset.filter(trust_tier=trust_tier)
+
+ # order_by is a ChoiceField over ALLOWED_LIST_ORDERINGS, so is_valid() already guarantees a
+ # valid key. Secondary "-id" keeps pagination stable when the primary key ties.
+ order_by = params.validated_data["order_by"]
+ queryset = queryset.order_by(order_by, "-id")
+
+ page = self.paginate_queryset(queryset)
+ if page is not None:
+ serializer = self.get_serializer(page, many=True)
+ return self.get_paginated_response(serializer.data)
+ serializer = self.get_serializer(queryset, many=True)
+ return Response({"count": len(serializer.data), "results": serializer.data})
+
+ @extend_schema(request=CommunitySkillInstallSerializer, responses={201: LLMSkillSerializer})
+ @action(methods=["POST"], detail=True)
+ def install(self, request: Request, slug: str = "", **kwargs) -> Response:
+ # Installing creates a durable LLMSkill in the team, so it must require the same write
+ # access as LLMSkillViewSet's create (resource-level "editor" on llm_skill). The viewset
+ # is scope_object="INTERNAL", so the shared AccessControlPermission only checks project
+ # membership — enforce skill-write access imperatively here. Catalog reads (list/retrieve)
+ # stay global and unaffected, and we avoid object-level AC checks against CommunitySkill
+ # (which has no team and is not an LLMSkill).
+ if not self.user_access_control.check_access_level_for_resource("llm_skill", "editor"):
+ raise PermissionDenied("You do not have permission to install skills in this project.")
+
+ payload = CommunitySkillInstallSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+
+ try:
+ installed = install_community_skill(
+ team=self.team,
+ user=cast(User, request.user),
+ slug=slug,
+ new_name=payload.validated_data.get("new_name"),
+ )
+ except CommunitySkillNotFoundError:
+ return Response(
+ {"detail": f"Community skill '{slug}' not found."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ except LLMSkillDuplicateNameConflictError:
+ # Only blame the new_name field when the caller actually supplied it — otherwise the
+ # conflicting name is the skill's own slug, so a generic message is accurate.
+ if payload.validated_data.get("new_name"):
+ return Response(
+ {"attr": "new_name", "detail": "A skill with this name already exists in your project."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ return Response(
+ {
+ "detail": f"A skill named '{slug}' is already installed in your project. "
+ "Pass new_name to install it under a different name."
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ except CommunitySkillInvalidPayloadError as err:
+ return Response({"detail": err.detail}, status=status.HTTP_400_BAD_REQUEST)
+ except (LLMSkillFileLimitError, LLMSkillFilePathConflictError):
+ # The synced community payload violates the skill limits (too many files / bad paths).
+ return Response(
+ {"detail": "This community skill can't be installed because its bundled files are invalid."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ report_user_action(
+ cast(User, request.user),
+ "community skill installed",
+ {
+ "community_skill_slug": slug,
+ "installed_skill_name": installed.name,
+ },
+ team=self.team,
+ request=request,
+ )
+ return Response(
+ cast(dict[str, Any], LLMSkillSerializer(installed, context=self.get_serializer_context()).data),
+ status=status.HTTP_201_CREATED,
+ )
+
+ @extend_schema(request=None, responses={200: CommunitySkillVoteResponseSerializer})
+ @action(methods=["POST"], detail=True)
+ def vote(self, request: Request, slug: str = "", **kwargs) -> Response:
+ # A vote mutates instance-global catalog state (it feeds default ordering for every team), so
+ # it takes the same skill-write access as install rather than the project membership that
+ # scope_object="INTERNAL" alone would check.
+ if not self.user_access_control.check_access_level_for_resource("llm_skill", "editor"):
+ raise PermissionDenied("You do not have permission to vote on community skills.")
+
+ try:
+ vote_count, has_voted = toggle_community_skill_vote(slug=slug, user=cast(User, request.user))
+ except CommunitySkillNotFoundError:
+ return Response(
+ {"detail": f"Community skill '{slug}' not found."},
+ status=status.HTTP_404_NOT_FOUND,
+ )
+ return Response({"vote_count": vote_count, "has_voted": has_voted})
diff --git a/products/skills/backend/api/test/test_community_skill_sync.py b/products/skills/backend/api/test/test_community_skill_sync.py
index e4625364f086..3db6c6462037 100644
--- a/products/skills/backend/api/test/test_community_skill_sync.py
+++ b/products/skills/backend/api/test/test_community_skill_sync.py
@@ -313,6 +313,25 @@ class TestCommunitySkillSync(APIBaseTest):
with self.assertRaises(OperationalError):
sync_community_skills_from_github()
+ @patch("products.skills.backend.api.community_skill_sync.github_request")
+ def test_sync_lowercases_tags(self, mock_get) -> None:
+ mock_get.return_value.raise_for_status.return_value = None
+ mock_get.return_value.json.return_value = {
+ "skills": [
+ {
+ "slug": "web-analytics-triage",
+ "name": "Web analytics triage",
+ "description": "Investigate a change in web traffic.",
+ "body": "# Triage",
+ "tags": ["Web-Analytics", "SQL"],
+ }
+ ],
+ }
+
+ # Tags are stored lowercased so the case-insensitive tag/search filters match reliably.
+ sync_community_skills_from_github()
+ self.assertEqual(CommunitySkill.objects.get(slug="web-analytics-triage").tags, ["web-analytics", "sql"])
+
@patch("products.skills.backend.api.community_skill_sync.github_request")
def test_sync_coerces_unknown_trust_tier_to_community(self, mock_get) -> None:
mock_get.return_value.raise_for_status.return_value = None
diff --git a/products/skills/backend/api/test/test_community_skills.py b/products/skills/backend/api/test/test_community_skills.py
new file mode 100644
index 000000000000..3a72b520335b
--- /dev/null
+++ b/products/skills/backend/api/test/test_community_skills.py
@@ -0,0 +1,225 @@
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+
+from ...models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillVote
+from ...models.skills import LLMSkill
+
+try:
+ from ee.models.rbac.access_control import AccessControl
+except ImportError:
+ pass
+
+
+def _create_community_skill(
+ *,
+ slug: str = "web-analytics-triage",
+ name: str = "Web analytics triage",
+ trust_tier: str = "official",
+ install_count: int = 0,
+ deleted: bool = False,
+) -> CommunitySkill:
+ return CommunitySkill.objects.create(
+ slug=slug,
+ name=name,
+ description="Investigate a change in web traffic.",
+ body="# Triage\nDo the thing.",
+ trust_tier=trust_tier,
+ tags=["web-analytics"],
+ install_count=install_count,
+ deleted=deleted,
+ )
+
+
+@patch(
+ "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled",
+ return_value=True,
+)
+class TestCommunitySkillAPI(APIBaseTest):
+ def _url(self, path: str = "") -> str:
+ return f"/api/projects/{self.team.id}/community_skills/{path}"
+
+ def test_list_returns_published_skills_ordered_by_installs(self, _mock_flag) -> None:
+ _create_community_skill(slug="alpha", install_count=1)
+ _create_community_skill(slug="beta", install_count=5)
+
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual([s["slug"] for s in results], ["beta", "alpha"])
+ self.assertNotIn("body", results[0]) # list serializer omits body
+
+ def test_list_excludes_deleted(self, _mock_flag) -> None:
+ _create_community_skill(slug="visible")
+ _create_community_skill(slug="gone", deleted=True)
+
+ response = self.client.get(self._url())
+ self.assertEqual([s["slug"] for s in response.json()["results"]], ["visible"])
+
+ def test_filter_by_trust_tier(self, _mock_flag) -> None:
+ _create_community_skill(slug="official-one", trust_tier="official")
+ _create_community_skill(slug="community-one", trust_tier="community")
+
+ response = self.client.get(self._url(), {"trust_tier": "community"})
+ self.assertEqual([s["slug"] for s in response.json()["results"]], ["community-one"])
+
+ def test_filter_by_tag_is_case_insensitive(self, _mock_flag) -> None:
+ _create_community_skill(slug="tagged") # stored tag is lowercase "web-analytics"
+ # A differently-cased tag query must still match the stored tag.
+ response = self.client.get(self._url(), {"tag": "Web-Analytics"})
+ self.assertEqual([s["slug"] for s in response.json()["results"]], ["tagged"])
+
+ def test_retrieve_by_slug_includes_body(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ response = self.client.get(self._url("web-analytics-triage/"))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["body"], "# Triage\nDo the thing.")
+
+ def test_install_creates_team_skill_and_increments_count(self, _mock_flag) -> None:
+ skill = _create_community_skill(slug="web-analytics-triage")
+ CommunitySkillFile.objects.create(skill=skill, path="references/playbook.md", content="hints")
+
+ response = self.client.post(self._url("web-analytics-triage/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+
+ installed = LLMSkill.objects.get(team=self.team, name="web-analytics-triage")
+ self.assertEqual(installed.body, "# Triage\nDo the thing.")
+ self.assertEqual(installed.metadata["community_skill_slug"], "web-analytics-triage")
+ self.assertEqual(installed.files.count(), 1)
+
+ skill.refresh_from_db()
+ self.assertEqual(skill.install_count, 1)
+
+ def test_install_with_custom_name(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ response = self.client.post(self._url("web-analytics-triage/install/"), {"new_name": "my-triage"})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertTrue(LLMSkill.objects.filter(team=self.team, name="my-triage").exists())
+
+ def test_install_default_name_conflict_omits_new_name_attr(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ LLMSkill.objects.create(team=self.team, name="web-analytics-triage", description="x", body="y")
+
+ response = self.client.post(self._url("web-analytics-triage/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ # Caller never supplied new_name, so the response must not blame that field.
+ self.assertNotIn("attr", response.json())
+
+ def test_install_custom_name_conflict_blames_new_name(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ LLMSkill.objects.create(team=self.team, name="taken", description="x", body="y")
+
+ response = self.client.post(self._url("web-analytics-triage/install/"), {"new_name": "taken"})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json().get("attr"), "new_name")
+
+ def test_install_blank_new_name_falls_back_to_slug(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ # A controlled empty text input sends "" — it must mean "use the default", not 400.
+ response = self.client.post(self._url("web-analytics-triage/install/"), {"new_name": ""})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ self.assertTrue(LLMSkill.objects.filter(team=self.team, name="web-analytics-triage").exists())
+
+ def test_install_rejects_unsafe_bundled_file_path(self, _mock_flag) -> None:
+ skill = _create_community_skill(slug="web-analytics-triage")
+ # A traversal path in the catalog must not be persisted into the team skill.
+ CommunitySkillFile.objects.create(skill=skill, path="../escape.md", content="x")
+
+ response = self.client.post(self._url("web-analytics-triage/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(LLMSkill.objects.filter(team=self.team).exists())
+ skill.refresh_from_db()
+ self.assertEqual(skill.install_count, 0)
+
+ @parameterized.expand(
+ [
+ # signals-scout-* auto-registers and runs with privileged scout scopes.
+ ("scout_namespace", "signals-scout-evil"),
+ # A canonical ReviewHog name auto-enables and runs in the installing user's PR reviews.
+ ("reviewhog_canonical", "review-hog-perspective-logic-correctness"),
+ ]
+ )
+ def test_install_rejects_reserved_auto_running_names(self, _mock_flag, _name, reserved_name) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+ # These namespaces auto-run community-controlled instructions on install, so they're refused.
+ response = self.client.post(self._url("web-analytics-triage/install/"), {"new_name": reserved_name})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name=reserved_name).exists())
+
+ def test_install_strips_internal_reviewhog_provenance(self, _mock_flag) -> None:
+ skill = _create_community_skill(slug="web-analytics-triage")
+ # ReviewHog prunes rows by seeded_by, so these keys must not be copied through on install —
+ # otherwise a catalog entry could make a user's freshly installed skill disappear.
+ CommunitySkill.objects.filter(pk=skill.pk).update(
+ metadata={"seeded_by": "review_hog", "canonical_hash": "deadbeef", "keep": "me"}
+ )
+ response = self.client.post(self._url("web-analytics-triage/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+
+ installed = LLMSkill.objects.get(team=self.team, name="web-analytics-triage")
+ self.assertNotIn("seeded_by", installed.metadata)
+ self.assertNotIn("canonical_hash", installed.metadata)
+ self.assertEqual(installed.metadata["keep"], "me")
+
+ def test_install_rejects_blank_description(self, _mock_flag) -> None:
+ skill = _create_community_skill(slug="web-analytics-triage")
+ # A blank description installs a skill that later fails export validation.
+ CommunitySkill.objects.filter(pk=skill.pk).update(description=" ")
+ response = self.client.post(self._url("web-analytics-triage/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(LLMSkill.objects.filter(team=self.team).exists())
+
+ def test_install_unknown_slug_returns_404(self, _mock_flag) -> None:
+ response = self.client.post(self._url("does-not-exist/install/"), {})
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_vote_toggles_on_and_off(self, _mock_flag) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+
+ first = self.client.post(self._url("web-analytics-triage/vote/"))
+ self.assertEqual(first.json(), {"vote_count": 1, "has_voted": True})
+
+ second = self.client.post(self._url("web-analytics-triage/vote/"))
+ self.assertEqual(second.json(), {"vote_count": 0, "has_voted": False})
+ self.assertFalse(CommunitySkillVote.objects.exists())
+
+
+@patch(
+ "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled",
+ return_value=True,
+)
+class TestCommunitySkillWriteAccess(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_skill",
+ resource_id=None,
+ access_level="viewer",
+ organization_member=OrganizationMembership.objects.get(user=viewer, organization=self.organization),
+ )
+ self.client.force_login(viewer)
+
+ @parameterized.expand([("install",), ("vote",)])
+ def test_viewer_cannot_write(self, _mock_flag, action: str) -> None:
+ _create_community_skill(slug="web-analytics-triage")
+
+ response = self.client.post(f"/api/projects/{self.team.id}/community_skills/web-analytics-triage/{action}/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
+ self.assertFalse(LLMSkill.objects.filter(team=self.team).exists())
+ self.assertFalse(CommunitySkillVote.objects.exists())
diff --git a/products/skills/backend/routes.py b/products/skills/backend/routes.py
index 251a66da8741..16d0c370d4f7 100644
--- a/products/skills/backend/routes.py
+++ b/products/skills/backend/routes.py
@@ -1,11 +1,14 @@
from posthog.api.routing import RouterRegistry
+from products.skills.backend.api.community_skills import CommunitySkillViewSet
from products.skills.backend.api.marketplace_views import LLMSkillMarketplaceViewSet
from products.skills.backend.api.skills import LLMSkillViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(r"llm_skills", LLMSkillViewSet, "project_llm_skills", ["team_id"])
+ # Instance-global community skills catalog (browse/install/vote). New endpoint, projects-only.
+ routers.projects.register(r"community_skills", CommunitySkillViewSet, "project_community_skills", ["team_id"])
# Git Smart HTTP marketplace. The prefix is the clone repo root: a client appends
# /info/refs and /git-upload-pack, which map to the viewset's two actions. New endpoint,
# so projects-only (no legacy environments alias).
diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.ts
index 137e7ad6a2c6..34e4473e476b 100644
--- a/products/skills/frontend/generated/api.schemas.ts
+++ b/products/skills/frontend/generated/api.schemas.ts
@@ -7,6 +7,151 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community
+ */
+export type TrustTierEnumApi = (typeof TrustTierEnumApi)[keyof typeof TrustTierEnumApi]
+
+export const TrustTierEnumApi = {
+ Official: 'official',
+ Verified: 'verified',
+ Community: 'community',
+} as const
+
+/**
+ * Arbitrary key-value metadata carried from the skill's frontmatter.
+ */
+export type CommunitySkillListApiMetadata = { [key: string]: unknown }
+
+/**
+ * List serializer that omits body and file manifest — progressive disclosure.
+ */
+export interface CommunitySkillListApi {
+ readonly id: string
+ /** Stable identifier matching the skill's directory in the community-skills repo. */
+ readonly slug: string
+ /** Display name of the skill. */
+ readonly name: string
+ /** What the skill does and when to use it. */
+ readonly description: string
+ /** License name or reference. */
+ readonly license: string
+ /** Environment requirements declared by the skill. */
+ readonly compatibility: string
+ /** Tools the skill declares it may use. Surface these to the user before install. */
+ allowed_tools?: string[]
+ /** Arbitrary key-value metadata carried from the skill's frontmatter. */
+ metadata?: CommunitySkillListApiMetadata
+ /** Free-form tags used for filtering and discovery. */
+ tags?: string[]
+ /** Moderation tier: 'official' (PostHog-authored), 'verified' (reviewed), or 'community'.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community */
+ trust_tier: TrustTierEnumApi
+ /** GitHub handle (or name) of the contributor who published the skill. */
+ readonly author_handle: string
+ /** Link to the skill's source directory on GitHub. */
+ readonly github_url: string
+ /** Number of times this skill has been installed into a team. */
+ readonly install_count: number
+ /** Total number of upvotes this skill has received. */
+ readonly vote_count: number
+ /** Whether the requesting user has upvoted this skill. */
+ readonly has_voted: boolean
+ /**
+ * When the skill was first published to the community repo.
+ * @nullable
+ */
+ readonly published_at: string | null
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedCommunitySkillListListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: CommunitySkillListApi[]
+}
+
+/**
+ * Arbitrary key-value metadata carried from the skill's frontmatter.
+ */
+export type CommunitySkillApiMetadata = { [key: string]: unknown }
+
+export interface CommunitySkillFileManifestApi {
+ /** @maxLength 500 */
+ path: string
+ /** @maxLength 100 */
+ content_type?: string
+}
+
+export interface CommunitySkillApi {
+ readonly id: string
+ /** Stable identifier matching the skill's directory in the community-skills repo. */
+ readonly slug: string
+ /** Display name of the skill. */
+ readonly name: string
+ /** What the skill does and when to use it. */
+ readonly description: string
+ /** The SKILL.md instruction content (markdown). */
+ readonly body: string
+ /** License name or reference. */
+ readonly license: string
+ /** Environment requirements declared by the skill. */
+ readonly compatibility: string
+ /** Tools the skill declares it may use. Surface these to the user before install. */
+ allowed_tools?: string[]
+ /** Arbitrary key-value metadata carried from the skill's frontmatter. */
+ metadata?: CommunitySkillApiMetadata
+ /** Free-form tags used for filtering and discovery. */
+ tags?: string[]
+ /** Moderation tier: 'official' (PostHog-authored), 'verified' (reviewed), or 'community'.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community */
+ trust_tier: TrustTierEnumApi
+ /** GitHub handle (or name) of the contributor who published the skill. */
+ readonly author_handle: string
+ /** Link to the skill's source directory on GitHub. */
+ readonly github_url: string
+ /** Bundled files manifest — path and content_type only. File contents are copied in on install. */
+ readonly files: readonly CommunitySkillFileManifestApi[]
+ /** Number of times this skill has been installed into a team. */
+ readonly install_count: number
+ /** Total number of upvotes this skill has received. */
+ readonly vote_count: number
+ /** Whether the requesting user has upvoted this skill. */
+ readonly has_voted: boolean
+ /**
+ * When the skill was first published to the community repo.
+ * @nullable
+ */
+ readonly published_at: string | null
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface CommunitySkillInstallApi {
+ /**
+ * Name for the installed skill in your team. Defaults to the community skill's slug.
+ * @maxLength 64
+ */
+ new_name?: string
+}
+
+/**
+ * Arbitrary key-value metadata.
+ */
+export type LLMSkillApiMetadata = { [key: string]: unknown }
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -64,6 +209,13 @@ export interface UserBasicApi {
role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}
+export interface LLMSkillFileManifestApi {
+ /** @maxLength 500 */
+ path: string
+ /** @maxLength 100 */
+ content_type?: string
+}
+
export interface LLMSkillOutlineEntryApi {
/**
* Markdown heading level (1-6).
@@ -75,15 +227,7 @@ export interface LLMSkillOutlineEntryApi {
text: string
}
-/**
- * Arbitrary key-value metadata.
- */
-export type LLMSkillListApiMetadata = { [key: string]: unknown }
-
-/**
- * List serializer that omits body and file manifest — progressive disclosure (Level 1).
- */
-export interface LLMSkillListApi {
+export interface LLMSkillApi {
readonly id: string
/**
* Unique skill name. Lowercase letters, numbers, and hyphens only. Max 64 characters.
@@ -95,6 +239,15 @@ export interface LLMSkillListApi {
* @maxLength 4096
*/
description: string
+ /** Total length of the full body in characters, independent of any body_offset/body_length paging. Compare against the length of the returned body to detect a truncated response. */
+ readonly body_total_length: number
+ /**
+ * When body_length paging stops before the end of the body, the character offset to request next (pass as body_offset). Null when the returned body reaches the end.
+ * @nullable
+ */
+ readonly body_next_offset: number | null
+ /** The SKILL.md instruction content (markdown). */
+ body: string
/**
* License name or reference to a bundled license file.
* @maxLength 255
@@ -108,11 +261,13 @@ export interface LLMSkillListApi {
/** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
- metadata?: LLMSkillListApiMetadata
+ metadata?: LLMSkillApiMetadata
/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */
readonly category: string
/** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */
readonly owners: readonly UserBasicApi[]
+ /** Bundled files manifest. Each entry is path + content_type only; fetch content via /llm_skills/name/{name}/files/{path}/. */
+ readonly files: readonly LLMSkillFileManifestApi[]
/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */
readonly outline: readonly LLMSkillOutlineEntryApi[]
readonly version: number
@@ -131,39 +286,22 @@ export interface LLMSkillListApi {
readonly first_version_created_at: string
}
-export interface PaginatedLLMSkillListListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: LLMSkillListApi[]
+export interface CommunitySkillVoteResponseApi {
+ /** Total upvotes after applying the toggle. */
+ vote_count: number
+ /** Whether the requesting user is now an upvoter. */
+ has_voted: boolean
}
/**
* Arbitrary key-value metadata.
*/
-export type LLMSkillCreateApiMetadata = { [key: string]: unknown }
-
-export interface LLMSkillFileInputApi {
- /**
- * File path relative to skill root, e.g. 'scripts/setup.sh' or 'references/guide.md'.
- * @maxLength 500
- */
- path: string
- /** Text content of the file. */
- content: string
- /**
- * MIME type of the file content.
- * @maxLength 100
- */
- content_type?: string
-}
+export type LLMSkillListApiMetadata = { [key: string]: unknown }
/**
- * Create serializer — accepts bundled files and owners as write-only input on POST.
+ * List serializer that omits body and file manifest — progressive disclosure (Level 1).
*/
-export interface LLMSkillCreateApi {
+export interface LLMSkillListApi {
readonly id: string
/**
* Unique skill name. Lowercase letters, numbers, and hyphens only. Max 64 characters.
@@ -175,15 +313,6 @@ export interface LLMSkillCreateApi {
* @maxLength 4096
*/
description: string
- /** Total length of the full body in characters, independent of any body_offset/body_length paging. Compare against the length of the returned body to detect a truncated response. */
- readonly body_total_length: number
- /**
- * When body_length paging stops before the end of the body, the character offset to request next (pass as body_offset). Null when the returned body reaches the end.
- * @nullable
- */
- readonly body_next_offset: number | null
- /** The SKILL.md instruction content (markdown). */
- body: string
/**
* License name or reference to a bundled license file.
* @maxLength 255
@@ -197,16 +326,11 @@ export interface LLMSkillCreateApi {
/** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
- metadata?: LLMSkillCreateApiMetadata
+ metadata?: LLMSkillListApiMetadata
/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */
readonly category: string
- /**
- * User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.
- * @maxItems 25
- */
- owners?: string[]
- /** Bundled files to include with the initial version (scripts, references, assets). */
- files?: LLMSkillFileInputApi[]
+ /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */
+ readonly owners: readonly UserBasicApi[]
/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */
readonly outline: readonly LLMSkillOutlineEntryApi[]
readonly version: number
@@ -225,19 +349,39 @@ export interface LLMSkillCreateApi {
readonly first_version_created_at: string
}
+export interface PaginatedLLMSkillListListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: LLMSkillListApi[]
+}
+
/**
* Arbitrary key-value metadata.
*/
-export type LLMSkillApiMetadata = { [key: string]: unknown }
+export type LLMSkillCreateApiMetadata = { [key: string]: unknown }
-export interface LLMSkillFileManifestApi {
- /** @maxLength 500 */
+export interface LLMSkillFileInputApi {
+ /**
+ * File path relative to skill root, e.g. 'scripts/setup.sh' or 'references/guide.md'.
+ * @maxLength 500
+ */
path: string
- /** @maxLength 100 */
+ /** Text content of the file. */
+ content: string
+ /**
+ * MIME type of the file content.
+ * @maxLength 100
+ */
content_type?: string
}
-export interface LLMSkillApi {
+/**
+ * Create serializer — accepts bundled files and owners as write-only input on POST.
+ */
+export interface LLMSkillCreateApi {
readonly id: string
/**
* Unique skill name. Lowercase letters, numbers, and hyphens only. Max 64 characters.
@@ -271,13 +415,16 @@ export interface LLMSkillApi {
/** List of pre-approved tools the skill may use. Tool names cannot contain whitespace. */
allowed_tools?: string[]
/** Arbitrary key-value metadata. */
- metadata?: LLMSkillApiMetadata
+ metadata?: LLMSkillCreateApiMetadata
/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */
readonly category: string
- /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */
- readonly owners: readonly UserBasicApi[]
- /** Bundled files manifest. Each entry is path + content_type only; fetch content via /llm_skills/name/{name}/files/{path}/. */
- readonly files: readonly LLMSkillFileManifestApi[]
+ /**
+ * User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.
+ * @maxItems 25
+ */
+ owners?: string[]
+ /** Bundled files to include with the initial version (scripts, references, assets). */
+ files?: LLMSkillFileInputApi[]
/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */
readonly outline: readonly LLMSkillOutlineEntryApi[]
readonly version: number
@@ -513,6 +660,59 @@ export interface LLMSkillResolveResponseApi {
has_more: boolean
}
+export type CommunitySkillsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Sort key. Defaults to most-installed first.
+ *
+ * * `-created_at` - -created_at
+ * * `-install_count` - -install_count
+ * * `-name` - -name
+ * * `-published_at` - -published_at
+ * * `-vote_count` - -vote_count
+ * * `created_at` - created_at
+ * * `install_count` - install_count
+ * * `name` - name
+ * * `published_at` - published_at
+ * * `vote_count` - vote_count
+ * @minLength 1
+ */
+ order_by?: string
+ /**
+ * Substring filter on skill names and descriptions; also matches a tag exactly (case-insensitive).
+ */
+ search?: string
+ /**
+ * Return only skills carrying this exact tag (case-insensitive).
+ */
+ tag?: string
+ /**
+ * Filter to a single moderation tier.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community
+ * @minLength 1
+ */
+ trust_tier?: CommunitySkillsListTrustTier
+}
+
+export type CommunitySkillsListTrustTier =
+ (typeof CommunitySkillsListTrustTier)[keyof typeof CommunitySkillsListTrustTier]
+
+export const CommunitySkillsListTrustTier = {
+ Official: 'official',
+ Verified: 'verified',
+ Community: 'community',
+} as const
+
export type LlmSkillsListParams = {
/**
* Filter skills to this exact category. Pass "scout" for Signals scouts, or an empty string to return only uncategorized skills. Omit the parameter entirely to return skills of every category.
diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.ts
index 8b6fd78ed720..b204d39d6ed4 100644
--- a/products/skills/frontend/generated/api.ts
+++ b/products/skills/frontend/generated/api.ts
@@ -9,6 +9,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ CommunitySkillApi,
+ CommunitySkillInstallApi,
+ CommunitySkillVoteResponseApi,
+ CommunitySkillsListParams,
LLMSkillApi,
LLMSkillCreateApi,
LLMSkillDuplicateApi,
@@ -25,6 +29,7 @@ import type {
LlmSkillsNameFilesRetrieveParams,
LlmSkillsNameRetrieveParams,
LlmSkillsResolveNameRetrieveParams,
+ PaginatedCommunitySkillListListApi,
PaginatedLLMSkillListListApi,
PatchedLLMSkillPublishApi,
} from './api.schemas'
@@ -46,6 +51,81 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getCommunitySkillsListUrl = (projectId: string, params?: CommunitySkillsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/community_skills/?${stringifiedParams}`
+ : `/api/projects/${projectId}/community_skills/`
+}
+
+export const communitySkillsList = async (
+ projectId: string,
+ params?: CommunitySkillsListParams,
+ options?: RequestInit
+): Promise<PaginatedCommunitySkillListListApi> => {
+ return apiMutator<PaginatedCommunitySkillListListApi>(getCommunitySkillsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCommunitySkillsRetrieveUrl = (projectId: string, slug: string) => {
+ return `/api/projects/${projectId}/community_skills/${slug}/`
+}
+
+export const communitySkillsRetrieve = async (
+ projectId: string,
+ slug: string,
+ options?: RequestInit
+): Promise<CommunitySkillApi> => {
+ return apiMutator<CommunitySkillApi>(getCommunitySkillsRetrieveUrl(projectId, slug), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getCommunitySkillsInstallCreateUrl = (projectId: string, slug: string) => {
+ return `/api/projects/${projectId}/community_skills/${slug}/install/`
+}
+
+export const communitySkillsInstallCreate = async (
+ projectId: string,
+ slug: string,
+ communitySkillInstallApi?: CommunitySkillInstallApi,
+ options?: RequestInit
+): Promise<LLMSkillApi> => {
+ return apiMutator<LLMSkillApi>(getCommunitySkillsInstallCreateUrl(projectId, slug), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(communitySkillInstallApi),
+ })
+}
+
+export const getCommunitySkillsVoteCreateUrl = (projectId: string, slug: string) => {
+ return `/api/projects/${projectId}/community_skills/${slug}/vote/`
+}
+
+export const communitySkillsVoteCreate = async (
+ projectId: string,
+ slug: string,
+ options?: RequestInit
+): Promise<CommunitySkillVoteResponseApi> => {
+ return apiMutator<CommunitySkillVoteResponseApi>(getCommunitySkillsVoteCreateUrl(projectId, slug), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getLlmSkillsListUrl = (projectId: string, params?: LlmSkillsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.ts
index 0cc143cdd704..92b5fe3596c2 100644
--- a/products/skills/frontend/generated/api.zod.ts
+++ b/products/skills/frontend/generated/api.zod.ts
@@ -9,6 +9,16 @@
*/
import * as zod from 'zod'
+export const communitySkillsInstallCreateBodyNewNameMax = 64
+
+export const CommunitySkillsInstallCreateBody = /* @__PURE__ */ zod.object({
+ new_name: zod
+ .string()
+ .max(communitySkillsInstallCreateBodyNewNameMax)
+ .optional()
+ .describe("Name for the installed skill in your team. Defaults to the community skill's slug."),
+})
+
export const llmSkillsCreateBodyNameMax = 64
export const llmSkillsCreateBodyDescriptionMax = 4096
diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yaml
index a1db5604e9ac..dfc5bb4798d0 100644
--- a/products/skills/mcp/tools.yaml
+++ b/products/skills/mcp/tools.yaml
@@ -9,6 +9,18 @@ feature: skills
url_prefix: /skills
ui_apps: {}
tools:
+ community-skills-install-create:
+ operation: community_skills_install_create
+ enabled: false
+ community-skills-list:
+ operation: community_skills_list
+ enabled: false
+ community-skills-retrieve:
+ operation: community_skills_retrieve
+ enabled: false
+ community-skills-vote-create:
+ operation: community_skills_vote_create
+ enabled: false
llm-skills-import-create:
operation: llm_skills_import_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 697d2d355484..01d6f170e9bc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15777,6 +15777,145 @@ export namespace Schemas {
readonly truncated: boolean;
}
+ /**
+ * Arbitrary key-value metadata carried from the skill's frontmatter.
+ */
+ export type CommunitySkillMetadata = { [key: string]: unknown };
+
+ /**
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community
+ */
+ export type TrustTierEnum = typeof TrustTierEnum[keyof typeof TrustTierEnum];
+
+
+ export const TrustTierEnum = {
+ Official: 'official',
+ Verified: 'verified',
+ Community: 'community',
+ } as const;
+
+ export interface CommunitySkillFileManifest {
+ /** @maxLength 500 */
+ path: string;
+ /** @maxLength 100 */
+ content_type?: string;
+ }
+
+ export interface CommunitySkill {
+ readonly id: string;
+ /** Stable identifier matching the skill's directory in the community-skills repo. */
+ readonly slug: string;
+ /** Display name of the skill. */
+ readonly name: string;
+ /** What the skill does and when to use it. */
+ readonly description: string;
+ /** The SKILL.md instruction content (markdown). */
+ readonly body: string;
+ /** License name or reference. */
+ readonly license: string;
+ /** Environment requirements declared by the skill. */
+ readonly compatibility: string;
+ /** Tools the skill declares it may use. Surface these to the user before install. */
+ allowed_tools?: string[];
+ /** Arbitrary key-value metadata carried from the skill's frontmatter. */
+ metadata?: CommunitySkillMetadata;
+ /** Free-form tags used for filtering and discovery. */
+ tags?: string[];
+ /** Moderation tier: 'official' (PostHog-authored), 'verified' (reviewed), or 'community'.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community */
+ trust_tier: TrustTierEnum;
+ /** GitHub handle (or name) of the contributor who published the skill. */
+ readonly author_handle: string;
+ /** Link to the skill's source directory on GitHub. */
+ readonly github_url: string;
+ /** Bundled files manifest — path and content_type only. File contents are copied in on install. */
+ readonly files: readonly CommunitySkillFileManifest[];
+ /** Number of times this skill has been installed into a team. */
+ readonly install_count: number;
+ /** Total number of upvotes this skill has received. */
+ readonly vote_count: number;
+ /** Whether the requesting user has upvoted this skill. */
+ readonly has_voted: boolean;
+ /**
+ * When the skill was first published to the community repo.
+ * @nullable
+ */
+ readonly published_at: string | null;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
+ export interface CommunitySkillInstall {
+ /**
+ * Name for the installed skill in your team. Defaults to the community skill's slug.
+ * @maxLength 64
+ */
+ new_name?: string;
+ }
+
+ /**
+ * Arbitrary key-value metadata carried from the skill's frontmatter.
+ */
+ export type CommunitySkillListMetadata = { [key: string]: unknown };
+
+ /**
+ * List serializer that omits body and file manifest — progressive disclosure.
+ */
+ export interface CommunitySkillList {
+ readonly id: string;
+ /** Stable identifier matching the skill's directory in the community-skills repo. */
+ readonly slug: string;
+ /** Display name of the skill. */
+ readonly name: string;
+ /** What the skill does and when to use it. */
+ readonly description: string;
+ /** License name or reference. */
+ readonly license: string;
+ /** Environment requirements declared by the skill. */
+ readonly compatibility: string;
+ /** Tools the skill declares it may use. Surface these to the user before install. */
+ allowed_tools?: string[];
+ /** Arbitrary key-value metadata carried from the skill's frontmatter. */
+ metadata?: CommunitySkillListMetadata;
+ /** Free-form tags used for filtering and discovery. */
+ tags?: string[];
+ /** Moderation tier: 'official' (PostHog-authored), 'verified' (reviewed), or 'community'.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community */
+ trust_tier: TrustTierEnum;
+ /** GitHub handle (or name) of the contributor who published the skill. */
+ readonly author_handle: string;
+ /** Link to the skill's source directory on GitHub. */
+ readonly github_url: string;
+ /** Number of times this skill has been installed into a team. */
+ readonly install_count: number;
+ /** Total number of upvotes this skill has received. */
+ readonly vote_count: number;
+ /** Whether the requesting user has upvoted this skill. */
+ readonly has_voted: boolean;
+ /**
+ * When the skill was first published to the community repo.
+ * @nullable
+ */
+ readonly published_at: string | null;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
+ export interface CommunitySkillVoteResponse {
+ /** Total upvotes after applying the toggle. */
+ vote_count: number;
+ /** Whether the requesting user is now an upvoter. */
+ has_voted: boolean;
+ }
+
export interface CompareItem {
label: string;
value: string;
@@ -46330,6 +46469,15 @@ export namespace Schemas {
results: Comment[];
}
+ export interface PaginatedCommunitySkillListList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: CommunitySkillList[];
+ }
+
export interface PaginatedConversationMinimalList {
count: number;
/** @nullable */
@@ -80662,6 +80810,59 @@ export namespace Schemas {
Task: 'task',
} as const;
+ export type CommunitySkillsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Sort key. Defaults to most-installed first.
+ *
+ * * `-created_at` - -created_at
+ * * `-install_count` - -install_count
+ * * `-name` - -name
+ * * `-published_at` - -published_at
+ * * `-vote_count` - -vote_count
+ * * `created_at` - created_at
+ * * `install_count` - install_count
+ * * `name` - name
+ * * `published_at` - published_at
+ * * `vote_count` - vote_count
+ * @minLength 1
+ */
+ order_by?: string;
+ /**
+ * Substring filter on skill names and descriptions; also matches a tag exactly (case-insensitive).
+ */
+ search?: string;
+ /**
+ * Return only skills carrying this exact tag (case-insensitive).
+ */
+ tag?: string;
+ /**
+ * Filter to a single moderation tier.
+ *
+ * * `official` - Official
+ * * `verified` - Verified
+ * * `community` - Community
+ * @minLength 1
+ */
+ trust_tier?: CommunitySkillsListTrustTier;
+ };
+
+ export type CommunitySkillsListTrustTier = typeof CommunitySkillsListTrustTier[keyof typeof CommunitySkillsListTrustTier];
+
+
+ export const CommunitySkillsListTrustTier = {
+ Official: 'official',
+ Verified: 'verified',
+ Community: 'community',
+ } as const;
+
export type ConversationsListParams = {
/**
* Number of results to return per page.