:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(skills): serve the rendered SKILL.md and its frontmatter (#99962)
posthog[bot]a37f3f5c4deb
diff --git a/docs/internal/skills/skill-md-api.md b/docs/internal/skills/skill-md-api.mdnew file mode 100644index 000000000000..7f12bb399280--- /dev/null+++ b/docs/internal/skills/skill-md-api.md@@ -0,0 +1,60 @@+# SKILL.md API++One skill's `SKILL.md` as the store renders it, plus the same frontmatter as a JSON object.++It exists for a host that serves a skill as a file — the MCP skills extension serves+`skill://<prefix>/<name>/SKILL.md` and must list the file's frontmatter field for field.+A host that renders the frontmatter itself would drift from the store, and every digest taken over+the file would then disagree with the listing. So both halves of this response come from one+renderer.++Viewset: `products/skills/backend/api/skills.py` (`LLMSkillViewSet.skill_md`).+Rendering: `products/skills/backend/marketplace/packaging.py` (`render_skill_md`, `frontmatter_document`).++## Endpoint++```text+GET /api/projects/{team_id}/llm_skills/name/{skill_name}/skill-md/?version=N+```++| Param | Default | Behavior |+| --------- | -------------- | -------------------------------------------------------- |+| `version` | latest version | Pins the response to one published version of the skill. |++Response:++```json+{+ "name": "my-skill",+ "version": 3,+ "content": "---\nname: my-skill\n...\n---\n\n<body>",+ "frontmatter": { "name": "my-skill", "description": "...", "metadata": { "version": "3" } }+}+```++- `content` is the complete file: the frontmatter block, a blank line, then the body. Take a digest over this exact string.+- `frontmatter` equals `yaml.safe_load` of the block in `content`. Keys use the spec's own names, so tool names arrive under `allowed-tools`.+- The body is not paged. `MAX_SKILL_BODY_BYTES` caps it at 1 MB.++## Authentication and access++- Session, personal API key and OAuth callers all work. The action requires the `llm_skill:read` scope.+- Object-level access control matches the other read actions on this viewset: a skill the caller cannot reach returns `403`, not `404`.+- `404` for an unknown skill name and for a version the skill never published.++## Frontmatter shape++`frontmatter_document` maps storage shape to spec shape:++| Stored | Served |+| --------------- | --------------------------------------------------------- |+| `name` | `name` |+| `description` | `description` |+| `license` | `license`, omitted when empty |+| `compatibility` | `compatibility`, omitted when empty |+| `metadata` | `metadata`, with `version` written last so it always wins |+| `allowed_tools` | `allowed-tools`, space separated, omitted when empty |++The spec has no top-level version field, so the platform version is parked under+`metadata.version`. It is a string, and it changes on every publish even when the body does not,+so the rendered file changes with it.diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex 14d24386bc23..37853bf1418f 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -878,6 +878,46 @@ class LLMSkillResolveResponseSerializer(serializers.Serializer):has_more = serializers.BooleanField()+@extend_schema_field(+ {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "description": {"type": "string"},+ "license": {"type": "string"},+ "compatibility": {"type": "string"},+ "metadata": {"type": "object", "additionalProperties": {"type": "string"}},+ "allowed-tools": {"type": "string"},+ },+ "required": ["name", "description", "metadata"],+ }+)+class SkillFrontmatterField(serializers.DictField):+ """The Agent Skills frontmatter mapping, passed through with the spec's own key names.++ ``allowed-tools`` is hyphenated in the spec, so the mapping is served verbatim instead of+ through declared fields: a client must be able to compare it to ``yaml.safe_load`` of the+ block in ``content`` key for key.+ """+++class LLMSkillMarkdownSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Name of the skill, which is also its directory name.")+ version = serializers.IntegerField(help_text="Version of the skill that this SKILL.md was rendered from.")+ content = serializers.CharField(+ help_text=(+ "The complete SKILL.md file: the YAML frontmatter block, a blank line, then the skill body. "+ "Serve these bytes as the file; a digest must be taken over this exact string."+ )+ )+ frontmatter = SkillFrontmatterField(+ help_text=(+ "The frontmatter block of content as a JSON object. Equal to yaml.safe_load of that block, "+ "so a listing can carry the same fields the file carries."+ )+ )++class LLMSkillFileCreateSerializer(LLMSkillFileInputSerializer):base_version = serializers.IntegerField(min_value=1,diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex 4f402608e0fd..821f211c7344 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -56,7 +56,14 @@ from ..marketplace.credentials import (marketplace_credential_label,marketplace_repo_url,)-from ..marketplace.packaging import SkillExport, SkillImportError, build_skill_zip, parse_skill_zip+from ..marketplace.packaging import (+ SkillExport,+ SkillImportError,+ build_skill_zip,+ frontmatter_document,+ parse_skill_zip,+ render_skill_md,+)from ..models.skills import LLMSkill, LLMSkillFilefrom .community_publish_services import (CommunitySkillPublishError,@@ -83,6 +90,7 @@ from .skill_serializers import (LLMSkillImportSerializer,LLMSkillListQuerySerializer,LLMSkillListSerializer,+ LLMSkillMarkdownSerializer,LLMSkillMarketplaceCommandSerializer,LLMSkillMarketplaceIssueSerializer,LLMSkillPublishConflictSerializer,@@ -1015,6 +1023,42 @@ class LLMSkillViewSet(})+ @extend_schema(+ parameters=[LLMSkillFetchQuerySerializer],+ responses={200: LLMSkillMarkdownSerializer},+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path=r"name/(?P<skill_name>[^/]+)/skill-md",+ required_scopes=["llm_skill:read"],+ )+ @llma_track_latency("llma_skills_skill_md")+ @monitor(feature=None, endpoint="llma_skills_skill_md", method="GET")+ def skill_md(self, request: Request, skill_name: str = "", **kwargs) -> Response:+ """The rendered SKILL.md plus its frontmatter as JSON, for a host that serves the file.++ Both halves come from one renderer, so a digest a client takes over ``content`` still+ describes the fields it reads from ``frontmatter``.+ """+ version_params = self._get_requested_version_params(request)+ version = cast(int | None, version_params.get("version"))+ skill = self._load_skill_with_object_access(request, skill_name, version)+ if skill is None:+ return self._skill_not_found_response(skill_name)++ # SKILL.md never carries the bundled files, so don't load them just to render it.+ export = skill.to_export()+ payload = LLMSkillMarkdownSerializer(+ instance={+ "name": skill.name,+ "version": skill.version,+ "content": render_skill_md(export),+ "frontmatter": frontmatter_document(export),+ }+ )+ return Response(payload.data)+@extend_schema(parameters=[LLMSkillFetchQuerySerializer, _FORMAT_QUERY_PARAM_EXCLUDED],responses={(200, "application/zip"): OpenApiTypes.BINARY},diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 4adba6c70bbe..92e406b077d0 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -11,6 +11,7 @@ from django.test import SimpleTestCasefrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone+import yamlfrom parameterized import parameterizedfrom rest_framework import serializers, status@@ -43,7 +44,7 @@ from ...api.skill_services import (resolve_skill_owners,set_skill_owners,)-from ...marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH+from ...marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH, parse_skill_mdfrom ...models.skills import LLMSkill, LLMSkillFileCOMMUNITY_FLAG = "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled"@@ -536,17 +537,44 @@ class TestLLMSkillAPI(APIBaseTest):@parameterized.expand([- ("read_scope_allowed", ["llm_skill:read"], status.HTTP_200_OK),- ("unrelated_scope_denied", ["dashboard:read"], status.HTTP_403_FORBIDDEN),+ (f"{endpoint}_{auth_method}_{label}", path, auth_method, scopes, expected_status)+ for endpoint, path in [+ ("search", "search?query=scope"),+ ("skill_md", "name/scope-search-skill/skill-md"),+ ]+ for auth_method in ["personal_key", "oauth"]+ for label, scopes, expected_status in [+ ("read_scope_allowed", ["llm_skill:read"], status.HTTP_200_OK),+ ("unrelated_scope_denied", ["dashboard:read"], status.HTTP_403_FORBIDDEN),+ ]])- def test_search_skills_pak_scope_end_to_end(self, _label, scopes, expected_status):+ def test_skill_read_scope_end_to_end(self, _label, path, auth_method, scopes, expected_status):self.create_skill(name="scope-search-skill")- api_key = self.create_personal_api_key_with_scopes(scopes)+ if auth_method == "personal_key":+ token = self.create_personal_api_key_with_scopes(scopes)+ else:+ app = OAuthApplication.objects.create(+ name="Skill read scope test",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ user=self.user,+ )+ token = OAuthAccessToken.objects.create(+ user=self.user,+ application=app,+ token="pha_skill_read_scope_test",+ scope=" ".join(scopes),+ expires=timezone.now() + timedelta(hours=1),+ scoped_teams=[self.team.id],+ ).tokenself.client.logout()- self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key}")+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")- response = self.client.get(self._url("search?query=scope"))+ response = self.client.get(self._url(path))assert response.status_code == expected_status@@ -743,6 +771,67 @@ class TestLLMSkillAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["name"] == uuid_shaped_name+ # --- Rendered SKILL.md ---++ def test_skill_md_round_trips_every_stored_spec_field(self):+ self.create_skill(+ name="rendered",+ description="Renders a SKILL.md.",+ body="# Rendered\nDo the thing.",+ license="Apache-2.0",+ compatibility="Requires Python 3.12+",+ allowed_tools=["Read", "Bash"],+ metadata={"author": "posthog"},+ )++ response = self.client.get(self._url("name/rendered/skill-md"))++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert data["name"] == "rendered"+ assert data["version"] == 1+ assert parse_skill_md(data["content"]) == {+ "name": "rendered",+ "description": "Renders a SKILL.md.",+ "license": "Apache-2.0",+ "compatibility": "Requires Python 3.12+",+ "metadata": {"author": "posthog"},+ "allowed_tools": ["Read", "Bash"],+ "body": "# Rendered\nDo the thing.",+ }++ def test_skill_md_frontmatter_matches_the_block_in_the_content(self):+ self.create_skill(name="paired", allowed_tools=["Read"], metadata={"author": "posthog"})++ data = self.client.get(self._url("name/paired/skill-md")).json()++ block = data["content"].split("---\n")[1]+ assert yaml.safe_load(block) == data["frontmatter"]+ assert data["frontmatter"]["metadata"]["version"] == "1"++ def test_skill_md_pins_to_a_requested_version(self):+ self.create_skill(name="pinned", body="# v1", version=1, is_latest=False)+ self.create_skill(name="pinned", body="# v2", version=2)++ data = self.client.get(self._url("name/pinned/skill-md?version=1")).json()++ assert data["version"] == 1+ assert parse_skill_md(data["content"])["body"] == "# v1"+ assert data["frontmatter"]["metadata"]["version"] == "1"++ @parameterized.expand(+ [+ ("missing_skill", "name/nonexistent/skill-md"),+ ("missing_version", "name/rendered/skill-md?version=9"),+ ]+ )+ def test_skill_md_not_found(self, _label, path):+ self.create_skill(name="rendered")++ response = self.client.get(self._url(path))++ assert response.status_code == status.HTTP_404_NOT_FOUND+# --- Publish new version ---def test_publish_new_version(self):@@ -1957,12 +2046,13 @@ class TestSkillAccessControlRBAC(APIBaseTest):@parameterized.expand([- ("list",),- ("get_by_name",),+ ("list", ""),+ ("get_by_name", "name/{name}"),+ ("skill_md", "name/{name}/skill-md"),])- def test_member_without_skill_access_cannot_read(self, action):- path = "" if action == "list" else f"name/{self.skill.name}"+ def test_member_without_skill_access_cannot_read(self, _action, path):+ path = path.format(name=self.skill.name)response = self.client.get(self._url(path))assert response.status_code == status.HTTP_403_FORBIDDEN@@ -2126,6 +2216,7 @@ class TestSkillAccessControlRBAC(APIBaseTest):("read by name", "get", "name/make-fractals", None),("resolve by name", "get", "resolve/name/make-fractals", None),("export", "get", "name/make-fractals/export", None),+ ("rendered skill.md", "get", "name/make-fractals/skill-md", 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"}),diff --git a/products/skills/backend/marketplace/packaging.py b/products/skills/backend/marketplace/packaging.pyindex f737bc358fae..8dbdd333ae9c 100644--- a/products/skills/backend/marketplace/packaging.py+++ b/products/skills/backend/marketplace/packaging.py@@ -87,12 +87,15 @@ def _key_sorted(value: Any) -> Any:return value-def render_frontmatter(skill: SkillExport) -> str:- """Serialize a skill's spec fields as a YAML frontmatter block (with delimiters).+def frontmatter_document(skill: SkillExport) -> dict[str, object]:+ """The skill's spec fields as a plain mapping, in the order the frontmatter block writes them.Maps storage shape -> spec shape: ``allowed_tools`` (list) becomes the spec'shyphenated, space-separated ``allowed-tools`` string, and the platform ``version``is parked under ``metadata`` since the spec defines no top-level version field.++ A caller that serves the frontmatter as JSON shares this helper with ``render_frontmatter``,+ so the JSON and the rendered block cannot drift apart."""document: dict[str, object] = {"name": skill.name, "description": skill.description}if skill.license:@@ -114,7 +117,12 @@ def render_frontmatter(skill: SkillExport) -> str:if skill.allowed_tools:document["allowed-tools"] = " ".join(skill.allowed_tools)- body = yaml.safe_dump(document, sort_keys=False, allow_unicode=True, default_flow_style=False)+ return document+++def render_frontmatter(skill: SkillExport) -> str:+ """Serialize a skill's spec fields as a YAML frontmatter block (with delimiters)."""+ body = yaml.safe_dump(frontmatter_document(skill), sort_keys=False, allow_unicode=True, default_flow_style=False)return f"---\n{body}---\n"diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex 46764197bd8c..0f8af0daa288 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -743,6 +743,31 @@ export interface LLMSkillRenameApi {new_name: string}+export type LLMSkillMarkdownApiFrontmatterMetadata = { [key: string]: string }++/**+ * The frontmatter block of content as a JSON object. Equal to yaml.safe_load of that block, so a listing can carry the same fields the file carries.+ */+export type LLMSkillMarkdownApiFrontmatter = {+ name: string+ description: string+ license?: string+ compatibility?: string+ metadata: LLMSkillMarkdownApiFrontmatterMetadata+ 'allowed-tools'?: string+}++export interface LLMSkillMarkdownApi {+ /** Name of the skill, which is also its directory name. */+ name: string+ /** Version of the skill that this SKILL.md was rendered from. */+ version: number+ /** The complete SKILL.md file: the YAML frontmatter block, a blank line, then the skill body. Serve these bytes as the file; a digest must be taken over this exact string. */+ content: string+ /** The frontmatter block of content as a JSON object. Equal to yaml.safe_load of that block, so a listing can carry the same fields the file carries. */+ frontmatter: LLMSkillMarkdownApiFrontmatter+}+export interface LLMSkillVersionSummaryApi {readonly id: stringreadonly version: number@@ -964,6 +989,14 @@ export type LlmSkillsNameFilesDestroyParams = {base_version?: number}+export type LlmSkillsNameSkillMdRetrieveParams = {+ /**+ * Specific skill version to fetch. If omitted, the latest version is returned.+ * @minimum 1+ */+ version?: number+}+export type LlmSkillsResolveNameRetrieveParams = {/*** Return versions older than this version number. Mutually exclusive with offset.diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.tsindex 00218a6cf758..5e761da31285 100644--- a/products/skills/frontend/generated/api.ts+++ b/products/skills/frontend/generated/api.ts@@ -21,6 +21,7 @@ import type {LLMSkillFileCreateApi,LLMSkillFileRenameApi,LLMSkillImportApi,+ LLMSkillMarkdownApi,LLMSkillMarketplaceCommandApi,LLMSkillMarketplaceIssueApi,LLMSkillPublishToCommunityApi,@@ -33,6 +34,7 @@ import type {LlmSkillsNameFilesDestroyParams,LlmSkillsNameFilesRetrieveParams,LlmSkillsNameRetrieveParams,+ LlmSkillsNameSkillMdRetrieveParams,LlmSkillsResolveNameRetrieveParams,LlmSkillsSearchRetrieveParams,PaginatedCommunitySkillListListApi,@@ -522,6 +524,44 @@ export const llmSkillsNameRenameCreate = async (})}+export const getLlmSkillsNameSkillMdRetrieveUrl = (+ projectId: string,+ skillName: string,+ params?: LlmSkillsNameSkillMdRetrieveParams+) => {+ 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}/llm_skills/name/${skillName}/skill-md/?${stringifiedParams}`+ : `/api/projects/${projectId}/llm_skills/name/${skillName}/skill-md/`+}++/**+ * The rendered SKILL.md plus its frontmatter as JSON, for a host that serves the file.+ *+ * Both halves come from one renderer, so a digest a client takes over ``content`` still+ * describes the fields it reads from ``frontmatter``.+ */+export const llmSkillsNameSkillMdRetrieve = async (+ projectId: string,+ skillName: string,+ params?: LlmSkillsNameSkillMdRetrieveParams,+ options?: RequestInit+): Promise<LLMSkillMarkdownApi> => {+ return apiMutator<LLMSkillMarkdownApi>(getLlmSkillsNameSkillMdRetrieveUrl(projectId, skillName, params), {+ ...options,+ method: 'GET',+ })+}+export const getLlmSkillsResolveNameRetrieveUrl = (projectId: string,skillName: string,diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yamlindex 8abd11ca7537..6180d9850c32 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -36,6 +36,9 @@ tools:llm-skills-name-publish-community-create:operation: llm_skills_name_publish_community_createenabled: false+ llm-skills-name-skill-md-retrieve:+ operation: llm_skills_name_skill_md_retrieve+ enabled: falsellm-skills-search-retrieve:operation: llm_skills_search_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8fcd6fcb9172..f78b30288545 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49669,6 +49669,31 @@ export namespace Schemas {readonly first_version_created_at: string;}+ export type LLMSkillMarkdownFrontmatterMetadata = {[key: string]: string};++ /**+ * The frontmatter block of content as a JSON object. Equal to yaml.safe_load of that block, so a listing can carry the same fields the file carries.+ */+ export type LLMSkillMarkdownFrontmatter = {+ name: string;+ description: string;+ license?: string;+ compatibility?: string;+ metadata: LLMSkillMarkdownFrontmatterMetadata;+ 'allowed-tools'?: string;+ };++ export interface LLMSkillMarkdown {+ /** Name of the skill, which is also its directory name. */+ name: string;+ /** Version of the skill that this SKILL.md was rendered from. */+ version: number;+ /** The complete SKILL.md file: the YAML frontmatter block, a blank line, then the skill body. Serve these bytes as the file; a digest must be taken over this exact string. */+ content: string;+ /** The frontmatter block of content as a JSON object. Equal to yaml.safe_load of that block, so a listing can carry the same fields the file carries. */+ frontmatter: LLMSkillMarkdownFrontmatter;+ }+/*** * `absent` - absent* * `exists` - exists@@ -101600,6 +101625,14 @@ export namespace Schemas {base_version?: number;};+ export type LlmSkillsNameSkillMdRetrieveParams = {+ /**+ * Specific skill version to fetch. If omitted, the latest version is returned.+ * @minimum 1+ */+ version?: number;+ };+export type LlmSkillsResolveNameRetrieveParams = {/*** Return versions older than this version number. Mutually exclusive with offset.