:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): tighten mcp store tool policy and cli install paths (#122542)
Richard Solomou17f4577b1c13
diff --git a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.test.ts b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.test.tsindex 5ba461b3bead..05ec8455f4b2 100644--- a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.test.ts+++ b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.test.ts@@ -5,6 +5,7 @@ import type {} from "@posthog/api-client/posthog-client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {+ canEditGatewayPolicyScope,countGatewayServersByCategory,countPoliciesByState,defaultAgentGrantPolicy,@@ -412,6 +413,58 @@ describe("getGatewayServerRemovalAction", () => {});});+describe("canEditGatewayPolicyScope", () => {+ const share = (userId: number) => ({+ service_account_id: "sa-1",+ user: {+ id: userId,+ uuid: `user-${userId}`,+ email: `user-${userId}@example.com`,+ hedgehog_config: null,+ },+ scope: "personal" as const,+ name: "Deploy bot",+ handle: "deploy-bot",+ status: "active" as const,+ last_active_at: null,+ granted_by: null,+ });+ const agentScope = {+ scopeType: "agent" as const,+ scopeServiceAccountId: "sa-1",+ };++ it.each([+ ["an admin without a share", server({}), true, true],+ [+ "a member with their own share",+ server({ agents: [share(1)], your_connection: connection() }),+ false,+ true,+ ],+ [+ "a member whose connection behind their share is deleted",+ server({ agents: [share(1)] }),+ false,+ false,+ ],+ [+ "a member with only a teammate's share",+ server({ agents: [share(2)] }),+ false,+ false,+ ],+ ] as const)("agent scope for %s", (_label, srv, isAdmin, expected) => {+ expect(+ canEditGatewayPolicyScope(srv, agentScope, {+ isAdmin,+ canManageAgentAccess: true,+ currentUserId: 1,+ }),+ ).toBe(expected);+ });+});+describe("countPoliciesByState", () => {it("counts each state, defaulting to zero", () => {const policy = (state: McpResolvedToolPolicy["policy_state"]) =>diff --git a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.tsindex 6f1d95662402..433c6f9f5d8a 100644--- a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts+++ b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts@@ -191,6 +191,32 @@ export function getGatewayServerRemovalAction(return personallyAddedCustomServer ? "delete_for_you" : "disconnect";}+/**+ * Whether the caller may change tool policy for a scope. An agent's policy+ * covers every member's share of the server, so a member may change it only+ * while holding a share of their own and the connection behind it.+ */+export function canEditGatewayPolicyScope(+ server: McpGatewayServer,+ scope: { scopeType: McpGatewayScopeType; scopeServiceAccountId?: string },+ caller: {+ isAdmin: boolean;+ canManageAgentAccess: boolean;+ currentUserId: number | null;+ },+): boolean {+ if (caller.isAdmin || scope.scopeType === "member") return true;+ if (scope.scopeType !== "agent" || !caller.canManageAgentAccess) return false;+ return (+ server.your_connection !== null &&+ server.agents.some(+ (agent) =>+ agent.service_account_id === scope.scopeServiceAccountId &&+ agent.user.id === caller.currentUserId,+ )+ );+}+export type GatewayPolicyCounts = Record<McpApprovalState, number>;export const AGENT_POLICY_STATES = [diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.test.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.test.tsxindex a4d8c24c0786..76ca7dad6826 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.test.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.test.tsx@@ -230,52 +230,68 @@ describe("GatewayServerDetail", () => {});});- it("shows a single scope-aware bulk trio when a member views an agent scope", () => {- const serverWithAgent = {- ...server,- agents: [- {- service_account_id: "sa-1",- user: {- id: 7,- uuid: "user-7",- first_name: "Ada",- last_name: "Lovelace",- email: "[email protected]",- hedgehog_config: null,- },- scope: "personal",- name: "Deploy bot",- handle: "deploy-bot",- status: "active",- last_active_at: null,- granted_by: null,+ it.each([+ ["their own share", 7, true],+ ["only a teammate's share", 8, false],+ ])(+ "offers the agent-scope bulk trio to a member viewing %s",+ (_label, currentUserId, editable) => {+ mocks.currentUser = { id: currentUserId };+ const serverWithAgent = {+ ...server,+ your_connection: {+ installation_id: "installation-1",+ is_enabled: true,+ pending_oauth: false,+ needs_reauth: false,+ last_used_at: null,},- ],- } as McpGatewayServer;- mocks.gateway.servers = [serverWithAgent];-- render(- <Theme>- <GatewayServerDetail- serverId={server.id}- initialScope={{- scopeType: "agent",- scopeServiceAccountId: "sa-1",- label: "Deploy bot",- }}- isAdmin={false}- canManageAgentAccess- onNavigate={vi.fn()}- />- </Theme>,- );-- // The scope switcher carries the only bulk trio; the top-level one- // (label "Set all") must not render alongside it.- expect(screen.getByText("Set all for Deploy bot")).toBeInTheDocument();- expect(screen.queryByText("Set all")).not.toBeInTheDocument();- });+ agents: [+ {+ service_account_id: "sa-1",+ user: {+ id: 7,+ uuid: "user-7",+ first_name: "Ada",+ last_name: "Lovelace",+ email: "[email protected]",+ hedgehog_config: null,+ },+ scope: "personal",+ name: "Deploy bot",+ handle: "deploy-bot",+ status: "active",+ last_active_at: null,+ granted_by: null,+ },+ ],+ } as McpGatewayServer;+ mocks.gateway.servers = [serverWithAgent];++ render(+ <Theme>+ <GatewayServerDetail+ serverId={server.id}+ initialScope={{+ scopeType: "agent",+ scopeServiceAccountId: "sa-1",+ label: "Deploy bot",+ }}+ isAdmin={false}+ canManageAgentAccess+ onNavigate={vi.fn()}+ />+ </Theme>,+ );++ // The scope switcher carries the only bulk trio; the top-level one+ // (label "Set all") must not render alongside it.+ expect(screen.queryByText("Set all for Deploy bot") !== null).toBe(+ editable,+ );+ expect(screen.queryByText("Set all")).not.toBeInTheDocument();+ },+ );it("offers the grant scope toggle only on the caller's own agent share", async () => {mocks.currentUser = { id: 7 };diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.tsxindex 4bcf0b07b92b..80e5e49f8de7 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayServerDetail.tsx@@ -26,6 +26,7 @@ import {} from "@posthog/core/mcp-gateway/gatewayConnect";import {agentShareMessage,+ canEditGatewayPolicyScope,countPoliciesByState,formatAgo,getGatewayServerRemovalAction,@@ -219,10 +220,11 @@ export function GatewayServerDetail({const bulkEditableCount = hasToolSearch? filteredEditablePolicies.length: editableCount;- const scopeEditable =- isAdmin ||- scope.scopeType === "member" ||- (scope.scopeType === "agent" && canManageAgentAccess);+ const scopeEditable = canEditGatewayPolicyScope(server, scope, {+ isAdmin,+ canManageAgentAccess,+ currentUserId: currentUser?.id ?? null,+ });// Any connected member can re-list — it runs against their own credential,// and it is the manual retry when auto-discovery failed.const refreshInstallationId = liveInstallationId;@@ -535,13 +537,15 @@ export function GatewayServerDetail({);})}<div className="ml-auto flex items-center gap-1">- <BulkTrio- label={`Set all for ${scope.label}`}- filtered={hasToolSearch}- disabled={tools.setAllPending || bulkEditableCount === 0}- allowNeedsApproval={!agentScope}- onSet={setBulkPolicy}- />+ {scopeEditable && (+ <BulkTrio+ label={`Set all for ${scope.label}`}+ filtered={hasToolSearch}+ disabled={tools.setAllPending || bulkEditableCount === 0}+ allowNeedsApproval={!agentScope}+ onSet={setBulkPolicy}+ />+ )}{refreshInstallationId && (<RefreshToolsButtonpending={tools.refreshPending}diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex a817c0f75171..e2867138e717 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -41,7 +41,12 @@ from products.mcp_store.backend.models import (MCPServiceAccount,MCPServiceAccountServerAccess,)-from products.mcp_store.backend.policy import GatewayCaller, PolicyContext, is_read_only_connector_tool+from products.mcp_store.backend.policy import (+ GatewayCaller,+ PolicyContext,+ is_read_only_connector_tool,+ legacy_state_for_caller,+)from products.mcp_store.backend.proxy import record_tool_call_audit, resolve_call_decision, validate_installation_authfrom products.mcp_store.backend.tools import (ToolCallError,@@ -79,19 +84,30 @@ def resolve_member_tool_states(With `block_locked_approvals`, a `needs_approval` state that an org rulelocks surfaces as `"do_not_use"`. Use it for callers that approve callson the member's behalf, because the member cannot approve a locked state."""- rows = MCPServerInstallationTool.objects.filter(installation_id=installation_id).values(- "tool_name", "annotations", "approval_state", "removed_at"+ rows = list(+ MCPServerInstallationTool.objects.filter(installation_id=installation_id).values(+ "tool_name", "annotations", "approval_state", "removed_at", "installation__user_id"+ ))- legacy = {row["tool_name"]: ("do_not_use" if row["removed_at"] else row["approval_state"]) for row in rows}+ owner_id = rows[0]["installation__user_id"] if rows else Noneif gateway_server_id is None or user_id is None:- return legacy+ caller_owns_installation = user_id is not None and owner_id == user_id+ return {+ row["tool_name"]: (+ "do_not_use"+ if row["removed_at"]+ else legacy_state_for_caller(row["approval_state"], caller_owns_installation=caller_owns_installation)+ )+ for row in rows+ }context = PolicyContext(team_id=team_id,caller=GatewayCaller(kind="member", user_id=user_id),gateway_server_id=gateway_server_id,legacy_rows={row["tool_name"]: row["approval_state"] for row in rows if row["removed_at"] is None},+ installation_owner_id=owner_id,)resolved: dict[str, str] = {}for row in rows:@@ -698,7 +714,9 @@ def call_member_server_tool(if gateway_server is not Noneelse None)- decision, block_reason = resolve_call_decision(tool, policy_context)+ decision, block_reason = resolve_call_decision(+ tool, policy_context, caller_owns_installation=installation.user_id == user_id+ )pending_approval_token = Noneif block_reason == "needs_approval":if policy_context is not None and policy_context.resolve(tool.tool_name, tool.annotations).locked:diff --git a/products/mcp_store/backend/policy.py b/products/mcp_store/backend/policy.pyindex bfa451c8a3b3..fb9376776a11 100644--- a/products/mcp_store/backend/policy.py+++ b/products/mcp_store/backend/policy.py@@ -7,8 +7,8 @@ can never make a tool more permissive than the team allows.1. Org rules — enabled team guardrails; a match locks the state.2. The stricter of the caller's own choice and the team ceiling. The caller'schoice comes from its scope row, or for members from the legacy- per-installation state. The ceiling comes from the explicit team row, then- the audience preset.+ per-installation state, which only its owner can approve through. The+ ceiling comes from the explicit team row, then the audience preset.3. `needs_approval` — freshly discovered tools are opt-in when neither sidehas made a choice.@@ -232,6 +232,17 @@ class _PolicyInputs:_STRICTNESS = {"do_not_use": 2, "needs_approval": 1, "approved": 0}+def legacy_state_for_caller(state: str, *, caller_owns_installation: bool) -> str:+ """Read an installation's legacy per-tool state for one caller.++ Only the owner writes that column, so on a shared installation a teammate+ keeps the owner's restrictions but not the owner's approvals.+ """+ if state == "approved" and not caller_owns_installation:+ return "needs_approval"+ return state++def is_policy_state_allowed(state: str, ceiling: str | None) -> bool:"""Whether ``state`` is at least as restrictive as ``ceiling``."""if ceiling is None:@@ -252,6 +263,7 @@ class PolicyContext:gateway_server_id: UUID | None = None,installation: MCPServerInstallation | None = None,legacy_rows: dict[str, str] | None = None,+ installation_owner_id: int | None = None,_preloaded: _PolicyInputs | None = None,) -> None:if gateway_server is not None:@@ -324,8 +336,14 @@ class PolicyContext:if legacy_rows is None and installation is not None and caller.kind == "member":for row in installation.tools.filter(removed_at__isnull=True).values("tool_name", "approval_state"):raw_legacy[row["tool_name"]] = row["approval_state"]+ owner_id = installation.user_id if installation is not None else installation_owner_id+ caller_owns_installation = caller.user_id is not None and owner_id == caller.user_id+ caller_legacy = {+ tool_name: legacy_state_for_caller(state, caller_owns_installation=caller_owns_installation)+ for tool_name, state in raw_legacy.items()+ }self._legacy_rows = {- tool_name: state for tool_name, state in raw_legacy.items() if state != SYNC_DEFAULT_APPROVAL_STATE+ tool_name: state for tool_name, state in caller_legacy.items() if state != SYNC_DEFAULT_APPROVAL_STATE}@classmethoddiff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.pyindex 2b4bcdf6c0c8..eaff9e4ddb79 100644--- a/products/mcp_store/backend/presentation/gateway_views.py+++ b/products/mcp_store/backend/presentation/gateway_views.py@@ -1063,19 +1063,48 @@ class MCPGatewayServerViewSet(return "agent", None, accountreturn "team", None, None- def _require_scope_permission(self, scope_type: str, scope_user: User | None, write: bool = False) -> None:+ def _require_scope_permission(+ self,+ server: MCPGatewayServer,+ scope_type: str,+ scope_user: User | None,+ scope_account: MCPServiceAccount | None,+ write: bool = False,+ ) -> None:"""Members may view team defaults and manage their own member scope;- agent scopes follow the team's agent-access setting."""+ agent scopes follow the team's agent-access setting. Agent policy covers+ every member's share of the server, so a member may change it only+ while holding a live share of their own."""if self._is_project_admin():returnif scope_type == "member" and scope_user is not None and scope_user.id == self.request.user.id:returnif scope_type == "agent" and self._can_manage_agent_access():- return+ if not write or self._holds_live_agent_share(server, scope_account):+ return+ raise PermissionDenied(+ "Share your connection to this server with the agent before changing its tool access."+ )if scope_type == "team" and not write:returnraise PermissionDenied("Only project admins can manage this scope.")+ def _holds_live_agent_share(self, server: MCPGatewayServer, account: MCPServiceAccount | None) -> bool:+ """The share must still carry the member's own credential. Revoked members+ never get here, because `safely_get_queryset` hides the server from them."""+ user_id = cast(User, self.request.user).id+ return (+ MCPServiceAccountServerAccess.objects.for_team(self.team_id)+ .filter(+ service_account=account,+ gateway_server=server,+ user_id=user_id,+ installation__isnull=False,+ installation__user_id=user_id,+ )+ .exists()+ )+def _member_installation(self, server: MCPGatewayServer, scope_user: User) -> MCPServerInstallation | None:"""The credential this member calls the server through.@@ -1203,7 +1232,7 @@ class MCPGatewayServerViewSet("""Tool catalog with the resolved policy for a scope."""server = self.get_object()scope_type, scope_user, scope_account = self._resolve_scope(request.validated_query_data)- self._require_scope_permission(scope_type, scope_user)+ self._require_scope_permission(server, scope_type, scope_user, scope_account)rows = self._resolve_policies_for_scope(server, scope_type, scope_user, scope_account)return Response({"count": len(rows), "next": None, "previous": None, "results": rows})@@ -1217,7 +1246,7 @@ class MCPGatewayServerViewSet(server = self.get_object()data = request.validated_datascope_type, scope_user, scope_account = self._resolve_scope(data)- self._require_scope_permission(scope_type, scope_user, write=True)+ self._require_scope_permission(server, scope_type, scope_user, scope_account, write=True)if scope_type != "team":if scope_type == "agent" and scope_account is not None:diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.pyindex 344d69f84c52..ee0fccbddc9d 100644--- a/products/mcp_store/backend/presentation/views.py+++ b/products/mcp_store/backend/presentation/views.py@@ -1334,7 +1334,9 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSetif gateway_server is not Noneelse None)- decision, block_reason = resolve_call_decision(tool, policy_context)+ decision, block_reason = resolve_call_decision(+ tool, policy_context, caller_owns_installation=installation.user_id == request.user.id+ )if gateway_server is not None:record_tool_call_audit(diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.pyindex d3db7a825a17..3833bbcb8e09 100644--- a/products/mcp_store/backend/proxy.py+++ b/products/mcp_store/backend/proxy.py@@ -21,7 +21,7 @@ from ee.hogai.utils.asgi import SyncIterableToAsyncfrom .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationToolfrom .oauth import TokenRefreshError, TokenRefreshRejectedError, is_token_expiring, refresh_installation_tokenfrom .oauth_credentials import oauth_credentials_source_is_allowed-from .policy import GatewayCaller, PolicyContext+from .policy import GatewayCaller, PolicyContext, legacy_state_for_callerfrom .url_policy import resolve_mcp_url_policy, trust_environment_proxylogger = structlog.get_logger(__name__)@@ -254,6 +254,8 @@ def _gateway_decision(policy_context: PolicyContext, tool: MCPServerInstallationdef resolve_call_decision(tool: MCPServerInstallationTool,policy_context: PolicyContext | None,+ *,+ caller_owns_installation: bool,) -> tuple[str, str | None]:"""Decide one tool call outside the JSON-RPC proxy path.@@ -273,9 +275,10 @@ def resolve_call_decision(return decision, "needs_approval" if decision == "pending" else "disabled"# Pre-gateway installations fall back to the cached per-tool approval flag.- if tool.approval_state == "approved":+ state = legacy_state_for_caller(tool.approval_state, caller_owns_installation=caller_owns_installation)+ if state == "approved":return "approved", None- if tool.approval_state == "needs_approval":+ if state == "needs_approval":return "pending", "needs_approval"return "blocked", "disabled"@@ -295,8 +298,10 @@ def record_tool_call_audit(def _evaluate_tool_call(tools_by_name: dict[str, MCPServerInstallationTool],item: dict[str, Any],- policy_context: PolicyContext | None = None,- audit_entries: list[tuple[str, str]] | None = None,+ policy_context: PolicyContext | None,+ audit_entries: list[tuple[str, str]] | None,+ *,+ caller_owns_installation: bool,) -> dict[str, Any] | None:"""Check a single JSON-RPC item against the installation's tool approval state.@@ -349,15 +354,16 @@ def _evaluate_tool_call(f"Tool '{tool_name}' is blocked by team policy",)- if tool.approval_state == "approved":+ state = legacy_state_for_caller(tool.approval_state, caller_owns_installation=caller_owns_installation)+ if state == "approved":return None- if tool.approval_state == "needs_approval":+ if state == "needs_approval":return _jsonrpc_error(request_id,TOOL_NEEDS_APPROVAL_CODE,f"Tool '{tool_name}' requires approval before it can be called",)- if tool.approval_state == "do_not_use":+ if state == "do_not_use":return _jsonrpc_error(request_id,TOOL_DISABLED_CODE,@@ -422,6 +428,8 @@ def enforce_tool_approval(data: dict[str, Any] | list[Any],policy_context: PolicyContext | None = None,audit_entries: list[tuple[str, str]] | None = None,+ *,+ caller_user_id: int | None,) -> HttpResponse | None:"""Inspect a JSON-RPC body and short-circuit tools/call that isn't approved.@@ -430,6 +438,7 @@ def enforce_tool_approval(passed through; unknown tool names return a JSON-RPC method-not-found errorwithout hitting the upstream server."""+ caller_owns_installation = caller_user_id is not None and caller_user_id == installation.user_idif isinstance(data, list):if not any(_is_tools_call(item) for item in data):return None@@ -439,7 +448,9 @@ def enforce_tool_approval(any_blocked = Falseany_passthrough = Falsefor item in data:- blocked = _evaluate_tool_call(tools_by_name, item, policy_context, audit_entries)+ blocked = _evaluate_tool_call(+ tools_by_name, item, policy_context, audit_entries, caller_owns_installation=caller_owns_installation+ )if blocked is not None:responses.append(blocked)any_blocked = True@@ -476,7 +487,9 @@ def enforce_tool_approval(if not _is_tools_call(data):return Nonetools_by_name = _tools_by_name(installation, _requested_tool_names(data))- blocked = _evaluate_tool_call(tools_by_name, data, policy_context, audit_entries)+ blocked = _evaluate_tool_call(+ tools_by_name, data, policy_context, audit_entries, caller_owns_installation=caller_owns_installation+ )if blocked is None:return Nonereturn HttpResponse(json.dumps(blocked), content_type="application/json", status=200)@@ -561,7 +574,13 @@ def proxy_mcp_request(installation=installation,)- enforcement_response = enforce_tool_approval(installation, data, policy_context, audit_entries)+ enforcement_response = enforce_tool_approval(+ installation,+ data,+ policy_context,+ audit_entries,+ caller_user_id=caller.user_id if caller is not None and caller.kind == "member" else None,+ )if gateway_server is not None and caller is not None and audit_entries:_write_audit_events(installation,diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.pyindex 41cf97d027dc..999935accd74 100644--- a/products/mcp_store/backend/test/test_api.py+++ b/products/mcp_store/backend/test/test_api.py@@ -1598,6 +1598,73 @@ class TestMCPServiceAccountAPI(APIBaseTest):is expected_access)+ @parameterized.expand(+ [+ ("member_with_only_a_teammate_share", "member", "teammate", status.HTTP_403_FORBIDDEN),+ ("member_whose_access_is_revoked", "member", "revoked", status.HTTP_404_NOT_FOUND),+ ("member_whose_connection_is_deleted", "member", "deleted_connection", status.HTTP_403_FORBIDDEN),+ ("admin_without_a_share", "admin", "teammate", status.HTTP_200_OK),+ ]+ )+ def test_agent_tool_policy_write_needs_a_live_share_of_your_own(+ self, _name: str, role: str, share: str, expected_status: int+ ) -> None:+ if role == "admin":+ self._make_admin()+ else:+ self._make_member()+ account = sync_built_in_agents(self.team)[0]+ server = MCPGatewayServer.objects.for_team(self.team.id).create(+ team=self.team,+ name="Agent share",+ url="https://mcp.agent-share.example.com/mcp",+ )+ sharer = User.objects.create_and_join(self.organization, "[email protected]", None)+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=sharer if share == "teammate" else self.user,+ display_name=server.name,+ url=server.url,+ auth_type="api_key",+ sensitive_configuration={"api_key": "secret"},+ scope="personal",+ gateway_server=server,+ )+ MCPServerInstallationTool.objects.create(+ installation=installation,+ tool_name="create_issue",+ last_seen_at=timezone.now(),+ )+ share_owner = sharer if share == "teammate" else self.user+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team=self.team,+ user=share_owner,+ service_account=account,+ gateway_server=server,+ installation=None if share == "deleted_connection" else installation,+ granted_by=share_owner,+ scope="team",+ )+ if share == "revoked":+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(+ team=self.team, gateway_server=server, user=self.user, revoked_by=sharer+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/mcp_gateway/servers/{server.id}/policies/",+ data={+ "scope_type": "agent",+ "scope_service_account_id": str(account.id),+ "policies": [{"tool_name": "create_issue", "policy_state": "approved"}],+ },+ format="json",+ )++ assert response.status_code == expected_status+ assert MCPToolPolicy.objects.for_team(self.team.id).filter(scope_type="agent").exists() is (+ expected_status == status.HTTP_200_OK+ )+def test_restricted_member_cannot_change_existing_agent_access_but_admin_can(self) -> None:self._make_member()account = sync_built_in_agents(self.team)[0]diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex b43c1d50c484..e022a5810c67 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -985,7 +985,10 @@ class TestCallMemberServerTool(BaseTest):self._installation(user=other_user, url="https://mcp.example.com.evil.test/mcp")self._tool(shared)- assert self._call().status == "ok"+ # The owner's approval does not carry over, so the teammate approves the call first.+ pending = self._call()+ assert pending.status == "needs_approval"+ assert self._call(approval_token=pending.approval_token).status == "ok"assert mock_call.call_args.args[0].id == shared.id@patch("products.mcp_store.backend.facade.api.call_upstream_tool")diff --git a/products/mcp_store/backend/test/test_gateway_tools.py b/products/mcp_store/backend/test/test_gateway_tools.pyindex 7f61a0bb65f7..38d96a15c623 100644--- a/products/mcp_store/backend/test/test_gateway_tools.py+++ b/products/mcp_store/backend/test/test_gateway_tools.py@@ -2,15 +2,19 @@ from posthog.test.base import APIBaseTestfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import status+from posthog.models import User++from products.mcp_store.backend.facade.api import resolve_member_tool_statesfrom products.mcp_store.backend.models import (MCPGatewayServer,MCPServerInstallation,MCPServerInstallationTool,MCPToolPolicy,)-from products.mcp_store.backend.policy import SYNC_DEFAULT_APPROVAL_STATE+from products.mcp_store.backend.policy import SYNC_DEFAULT_APPROVAL_STATE, GatewayCaller, PolicyContextclass TestMCPGatewayToolPoliciesAPI(APIBaseTest):@@ -150,3 +154,43 @@ class TestMCPGatewayToolPoliciesAPI(APIBaseTest):row = self._member_row(server)assert row["policy_state"] == "approved"assert row["decided_by"] == "scope"++ @parameterized.expand(+ [+ (f"{entry_point}_{caller}_{legacy_state}", entry_point, caller == "owner", legacy_state, expected)+ for entry_point in ("policy_context", "facade", "facade_unlinked")+ for caller, legacy_state, expected in (+ ("owner", "approved", "approved"),+ ("teammate", "approved", "needs_approval"),+ ("teammate", "do_not_use", "do_not_use"),+ )+ ]+ )+ def test_shared_installation_teammates_keep_owner_restrictions_but_not_approvals(+ self, _name: str, entry_point: str, caller_is_owner: bool, legacy_state: str, expected: str+ ) -> None:+ server, installation = self._server_with_tool("shared", legacy_state=legacy_state)+ installation.scope = "shared"+ installation.save(update_fields=["scope"])+ caller = (+ self.user if caller_is_owner else User.objects.create_and_join(self.organization, "[email protected]", None)+ )++ if entry_point == "policy_context":+ state = (+ PolicyContext(+ team_id=self.team.id,+ caller=GatewayCaller(kind="member", user_id=caller.id),+ gateway_server=server,+ installation=installation,+ )+ .resolve("search_items")+ .state+ )+ else:+ gateway_server_id = server.id if entry_point == "facade" else None+ state = resolve_member_tool_states(str(installation.id), self.team.id, gateway_server_id, caller.id)[+ "search_items"+ ]++ assert state == expecteddiff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.pyindex dd66265badbb..c7756a13229d 100644--- a/products/mcp_store/backend/test/test_proxy.py+++ b/products/mcp_store/backend/test/test_proxy.py@@ -698,6 +698,29 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTeassert response.status_code == 200mock_client.send.assert_called_once()+ @patch("products.mcp_store.backend.proxy.pinned_client")+ def test_owner_approval_on_shared_installation_still_prompts_a_teammate(self, mock_client_cls):+ owner = User.objects.create_and_join(self.organization, "[email protected]", None)+ installation = MCPServerInstallation.objects.create(+ team=self.team,+ user=owner,+ display_name="Shared tools",+ url="https://mcp.example.com/mcp",+ auth_type="api_key",+ sensitive_configuration={"api_key": "sk"},+ scope="shared",+ )+ self._tool(installation, "search", "approved")++ response = self.client.post(+ self._proxy_url(installation.id),+ data={"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "search"}},+ format="json",+ )++ assert response.json()["error"]["code"] == -32001+ mock_client_cls.assert_not_called()+@patch("products.mcp_store.backend.proxy.pinned_client")def test_needs_approval_tool_call_blocked_with_jsonrpc_error(self, mock_client_cls):installation = self._installation()diff --git a/products/mcp_store/frontend/gateway/GatewayServerScene.tsx b/products/mcp_store/frontend/gateway/GatewayServerScene.tsxindex 20b7e249ce00..383dced7d94c 100644--- a/products/mcp_store/frontend/gateway/GatewayServerScene.tsx+++ b/products/mcp_store/frontend/gateway/GatewayServerScene.tsx@@ -280,6 +280,7 @@ export function GatewayServerScene({function ToolPoliciesSection(): JSX.Element {const {availableScopes,+ canEditScope,displayedToolPolicies,filteredToolPolicies,isAdmin,@@ -296,8 +297,6 @@ function ToolPoliciesSection(): JSX.Element {} = useValues(gatewayServerLogic)const { setScope, setAllTools, setToolSearch, toggleToolsExpanded } = useActions(gatewayServerLogic)const { refreshServerTools } = useActions(mcpGatewayLogic)- const canEditScope =- isAdmin || scope.scopeType === 'member' || (scope.scopeType === 'agent' && canManageAgentAccess)const agentScope = scope.scopeType === 'agent'const bulkOptions = agentScope? POLICY_OPTIONS.filter((option) => option.value !== 'needs_approval')@@ -435,15 +434,13 @@ function ToolPoliciesSection(): JSX.Element {}function ToolPolicyRow({ policy }: { policy: ResolvedToolPolicyApi }): JSX.Element {- const { server, scope, isAdmin, canManageAgentAccess, toolPoliciesLoading } = useValues(gatewayServerLogic)+ const { server, scope, canEditScope, toolPoliciesLoading } = useValues(gatewayServerLogic)const { setToolPolicy } = useActions(gatewayServerLogic)const fqName = `${server?.name ?? ''}.${policy.tool_name}`const ruleLocked = policy.decided_by === 'rule'const setByTeamAdmin =scope.scopeType !== 'team' && (policy.decided_by === 'team' || policy.decided_by === 'preset')- const canEditScope =- isAdmin || scope.scopeType === 'member' || (scope.scopeType === 'agent' && canManageAgentAccess)const agentScope = scope.scopeType === 'agent'const displayedState: MCPToolApprovalStateEnumApi =agentScope && policy.policy_state === 'needs_approval' ? 'do_not_use' : policy.policy_statediff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.tsindex 53a5cd76c22b..f837d919671c 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.test.ts@@ -277,6 +277,25 @@ describe('gatewayServerLogic', () => {})})+ it.each([+ ['a member with their own share', false, YOU, true, true],+ ['a member whose connection behind their share is deleted', false, YOU, false, false],+ ['a member with only a teammate share', false, TEAMMATE, true, false],+ ['an admin without a share', true, TEAMMATE, true, true],+ ])('lets %s edit an agent scope', (_label, isAdmin, sharer, connected, expected) => {+ parentLogic.actions.loadConfigSuccess({+ is_admin: isAdmin,+ registered_template_ids: [],+ allow_custom_servers: true,+ allow_member_agent_access: true,+ })+ parentLogic.actions.loadServersSuccess([gatewayServer(connected ? {} : { your_connection: null })])+ parentLogic.actions.loadServiceAccountsSuccess([serviceAccount('scout-id', [{ user: sharer, scope: 'team' }])])+ logic.actions.setScope({ scopeType: 'agent', scopeServiceAccountId: 'scout-id', label: 'Agent scout-id' })++ expect(logic.values.canEditScope).toBe(expected)+ })+it('uses the policy mutation response while keeping the loader in flight', async () => {const pendingResponse = deferred<Awaited<ReturnType<typeof mcpGatewayServersPoliciesCreate>>>()const updatedPolicy = toolPolicy('create_issue', { policy_state: 'needs_approval' })diff --git a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts b/products/mcp_store/frontend/gateway/gatewayServerLogic.tsindex e232127ae98b..35337205ab29 100644--- a/products/mcp_store/frontend/gateway/gatewayServerLogic.ts+++ b/products/mcp_store/frontend/gateway/gatewayServerLogic.ts@@ -139,6 +139,7 @@ export interface gatewayServerLogicValues {availableAgentAccounts: MCPServiceAccountApi[]availableScopes: PolicyScope[]breadcrumbs: Breadcrumb[]+ canEditScope: booleandisplayedToolPolicies: ResolvedToolPolicyApi[]filteredToolPolicies: ResolvedToolPolicyApi[]policyCounts: Record<MCPToolApprovalStateEnumApi, number>@@ -402,6 +403,13 @@ export interface gatewayServerLogicMeta {serviceAccounts: MCPServiceAccountApi[],agentSharesByAccountId: Record<string, AgentServerShare>) => MCPServiceAccountApi[]+ canEditScope: (+ server: MCPGatewayServerApi | null,+ isAdmin: boolean,+ scope: PolicyScope,+ canManageAgentAccess: boolean,+ agentSharesByAccountId: Record<string, AgentServerShare>+ ) => booleanagentShareDisabledReason: (server: MCPGatewayServerApi | null) => string | undefinedrefreshInstallationId: (server: MCPGatewayServerApi | null) => string | nullfilteredToolPolicies: (toolPolicies: ResolvedToolPolicyApi[], toolSearch: string) => ResolvedToolPolicyApi[]@@ -719,6 +727,24 @@ export const gatewayServerLogic = kea<gatewayServerLogicType>([// stays available for the viewer to share their own connection.serviceAccounts.filter((account) => !agentSharesByAccountId[account.id]?.sharedByYou),],+ canEditScope: [+ (s) => [s.server, s.isAdmin, s.scope, s.canManageAgentAccess, s.agentSharesByAccountId],+ (+ server: MCPGatewayServerApi | null,+ isAdmin: boolean,+ scope: PolicyScope,+ canManageAgentAccess: boolean,+ agentSharesByAccountId: Record<string, AgentServerShare>+ ): boolean =>+ isAdmin ||+ scope.scopeType === 'member' ||+ // An agent's tool policy covers every member's share, so members tune it only alongside+ // their own share and the connection behind it.+ (scope.scopeType === 'agent' &&+ canManageAgentAccess &&+ !!server?.your_connection &&+ !!agentSharesByAccountId[scope.scopeServiceAccountId ?? '']?.sharedByYou),+ ],agentShareDisabledReason: [(s) => [s.server],(server: MCPGatewayServerApi | null): string | undefined =>diff --git a/products/posthog_ai/scripts/build_skills/frontmatter.py b/products/posthog_ai/scripts/build_skills/frontmatter.pyindex cdec2cfa2035..0cb4bef2866f 100644--- a/products/posthog_ai/scripts/build_skills/frontmatter.py+++ b/products/posthog_ai/scripts/build_skills/frontmatter.py@@ -11,9 +11,12 @@ _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)_MAX_SKILL_DESCRIPTION_LENGTH = 1024+# A skill name becomes a directory under dist/skills and .agents/skills, so it must stay one path segment.+SKILL_NAME_PATTERN = r"^[a-z0-9][a-z0-9-]*$"+class SkillFrontmatter(BaseModel):- name: str+ name: str = Field(pattern=SKILL_NAME_PATTERN)description: str = Field(max_length=_MAX_SKILL_DESCRIPTION_LENGTH)diff --git a/products/posthog_ai/scripts/build_skills/skill_builder.py b/products/posthog_ai/scripts/build_skills/skill_builder.pyindex dc82069f40a3..48bca6da0042 100644--- a/products/posthog_ai/scripts/build_skills/skill_builder.py+++ b/products/posthog_ai/scripts/build_skills/skill_builder.py@@ -225,8 +225,7 @@ class SkillBuilder:match = next((s for s in skills if s.name == skill_name), None)if match is not None and match.source_file.suffix != ".j2":try:- metadata, _ = frontmatter.parse_frontmatter(match.source_file.read_text())- fm_name = metadata.get("name", skill_name)+ fm_name = frontmatter.validate_frontmatter(match.source_file.read_text(), str(match.source_file)).nameif fm_name != skill_name and fm_name not in names_to_try:names_to_try.append(fm_name)except Exception:diff --git a/products/posthog_ai/scripts/build_skills/skill_manifest.py b/products/posthog_ai/scripts/build_skills/skill_manifest.pyindex df96e0c4364f..708d16cdef4a 100644--- a/products/posthog_ai/scripts/build_skills/skill_manifest.py+++ b/products/posthog_ai/scripts/build_skills/skill_manifest.py@@ -6,6 +6,8 @@ from pathlib import Pathfrom pydantic import BaseModel, Field, model_validator+from . import frontmatter+MANIFEST_VERSION = "1.0.0"@@ -22,7 +24,7 @@ class SkillFile(BaseModel):class SkillResource(BaseModel):- name: str+ name: str = Field(pattern=frontmatter.SKILL_NAME_PATTERN)description: strfiles: list[SkillFile]source: strdiff --git a/products/posthog_ai/scripts/test/test_build_skills.py b/products/posthog_ai/scripts/test/test_build_skills.pyindex ec45071b4930..38e49db87b05 100644--- a/products/posthog_ai/scripts/test/test_build_skills.py+++ b/products/posthog_ai/scripts/test/test_build_skills.py@@ -15,7 +15,7 @@ from products.posthog_ai.scripts.build_skills.discovery import SkillDiscovererfrom products.posthog_ai.scripts.build_skills.frontmatter import parse_frontmatter, validate_frontmatterfrom products.posthog_ai.scripts.build_skills.rendering import SkillRendererfrom products.posthog_ai.scripts.build_skills.skill_builder import SkillBuilder-from products.posthog_ai.scripts.build_skills.skill_manifest import DiscoveredSkill+from products.posthog_ai.scripts.build_skills.skill_manifest import DiscoveredSkill, SkillResourcefrom products.posthog_ai.scripts.build_skills.tool_references import _check_tool_references@@ -389,6 +389,17 @@ def test_build_manifest_rejects_duplicate_rendered_names(tmp_path: Path) -> Nonebuilder.build_manifest(discoverer.discover(), SkillRenderer())[email protected]("name", ["shadow/../trusted-skill", "../escape", "nested/skill", '""'])+def test_frontmatter_rejects_names_that_are_not_one_path_segment(name: str) -> None:+ with pytest.raises(ValueError):+ validate_frontmatter(f"---\nname: {name}\ndescription: desc\n---\n# Body\n")+++def test_skill_resource_rejects_names_that_are_not_one_path_segment() -> None:+ with pytest.raises(ValueError):+ SkillResource(name="shadow/../trusted-skill", description="desc", files=[], source="products/alpha/skills/x")++def test_end_to_end_template_with_pydantic(tmp_path: Path) -> None:from pydantic import BaseModel, Fielddiff --git a/services/mcp/src/cli/agents-md.ts b/services/mcp/src/cli/agents-md.tsindex 4f042fb953d2..f8eeb6c31c29 100644--- a/services/mcp/src/cli/agents-md.ts+++ b/services/mcp/src/cli/agents-md.ts@@ -2,7 +2,7 @@ import * as fs from 'node:fs/promises'import * as path from 'node:path'import agentsMdPrompt from './agents-md-snippet.md'-import { errorCode } from './utils'+import { assertResolvesInside, errorCode } from './utils'const OPEN_TAG = '<posthog>'const CLOSE_TAG = '</posthog>'@@ -15,7 +15,11 @@ export const AGENTS_MD_SNIPPET = `${OPEN_TAG}\n${AGENTS_MD_PROMPT}\n${CLOSE_TAG}const MANAGED_BLOCK_PATTERN = /<posthog>[\s\S]*?<\/posthog>/export async function installAgentsMdSnippet(opts: { cwd?: string; filePath?: string } = {}): Promise<string> {- const targetPath = path.resolve(opts.filePath ?? path.join(opts.cwd ?? process.cwd(), 'AGENTS.md'))+ const cwd = opts.cwd ?? process.cwd()+ const targetPath = path.resolve(opts.filePath ?? path.join(cwd, 'AGENTS.md'))+ if (!opts.filePath) {+ await assertResolvesInside(cwd, targetPath, '. Pass --path to choose the file to update.')+ }let existing = ''try {existing = await fs.readFile(targetPath, 'utf-8')diff --git a/services/mcp/src/cli/skills.ts b/services/mcp/src/cli/skills.tsindex 61a383bda748..53b6214fc992 100644--- a/services/mcp/src/cli/skills.ts+++ b/services/mcp/src/cli/skills.ts@@ -5,7 +5,7 @@ import * as path from 'node:path'import { fetchContextMillResources, filterValidEntries, loadManifestFromArchive } from '@/resources/internals'import type { ContextMillResource } from '@/resources/manifest-types'-import { errorCode } from './utils'+import { assertResolvesInside, assertSafeDestination, errorCode } from './utils'export interface SkillListItem {id: string@@ -46,14 +46,6 @@ function targetSkillDirectory(targetRoot: string, skillId: string): string {return destinationRoot}-function assertSafeDestination(root: string, destination: string): void {- const normalizedRoot = path.resolve(root)- const normalizedDestination = path.resolve(destination)- if (normalizedDestination !== normalizedRoot && !normalizedDestination.startsWith(normalizedRoot + path.sep)) {- throw new Error(`Refusing to write outside ${normalizedRoot}: ${normalizedDestination}`)- }-}-function assertSafeSkillId(skillId: string): void {if (!skillId || skillId.includes('..') || /[/\\]/.test(skillId)) {throw new Error(`Invalid skill ID "${skillId}": must not contain path separators or traversal sequences.`)@@ -80,6 +72,7 @@ export async function installSkill(}const destinationRoot = targetSkillDirectory(cwd, skillId)+ await assertResolvesInside(cwd, destinationRoot)try {await fs.access(destinationRoot)if (!opts.force) {diff --git a/services/mcp/src/cli/utils.ts b/services/mcp/src/cli/utils.tsindex 7973969defdd..c861075de2c7 100644--- a/services/mcp/src/cli/utils.ts+++ b/services/mcp/src/cli/utils.ts@@ -1,5 +1,58 @@+import * as fs from 'node:fs/promises'+import * as path from 'node:path'+export function errorCode(error: unknown): unknown {return typeof error === 'object' && error !== null && 'code' in error? (error as { code?: unknown }).code: undefined}++// Matches Linux's MAXSYMLINKS, so a link cycle fails instead of looping.+const MAX_SYMLINK_HOPS = 40++export function assertSafeDestination(root: string, destination: string, hint = ''): void {+ const normalizedRoot = path.resolve(root)+ const normalizedDestination = path.resolve(destination)+ if (normalizedDestination !== normalizedRoot && !normalizedDestination.startsWith(normalizedRoot + path.sep)) {+ throw new Error(`Refusing to write outside ${normalizedRoot}: ${normalizedDestination}${hint}`)+ }+}++/** Throws unless `target` stays inside `root` once symlinks are resolved, so a+ * link committed into a checkout cannot redirect a write elsewhere. */+export async function assertResolvesInside(root: string, target: string, hint = ''): Promise<void> {+ const realRoot = await fs.realpath(root)+ const missing: string[] = []+ let existing = path.resolve(target)+ let realExisting: string+ let hops = 0+ for (;;) {+ try {+ realExisting = await fs.realpath(existing)+ break+ } catch (error) {+ if (errorCode(error) !== 'ENOENT') {+ throw error+ }+ }+ // realpath fails on a dangling link too, but writing through it creates its target.+ const isLink = await fs.lstat(existing).then(+ (stats) => stats.isSymbolicLink(),+ () => false+ )+ if (isLink) {+ hops += 1+ if (hops > MAX_SYMLINK_HOPS) {+ throw new Error(`Refusing to follow too many symlinks at ${existing}${hint}`)+ }+ // Splice the raw target on without normalizing it, so the OS resolves any `..` after+ // the links it passes through, with its own separators.+ const linkTarget = await fs.readlink(existing)+ existing = path.isAbsolute(linkTarget) ? linkTarget : `${path.dirname(existing)}${path.sep}${linkTarget}`+ continue+ }+ missing.unshift(path.basename(existing))+ existing = path.dirname(existing)+ }+ assertSafeDestination(realRoot, path.join(realExisting, ...missing), hint)+}diff --git a/services/mcp/tests/unit/cli-agents-md.test.ts b/services/mcp/tests/unit/cli-agents-md.test.tsindex b434ab173da4..fb74cd5a1594 100644--- a/services/mcp/tests/unit/cli-agents-md.test.ts+++ b/services/mcp/tests/unit/cli-agents-md.test.ts@@ -40,4 +40,53 @@ describe('CLI AGENTS.md installer', () => {expect(content.indexOf('# Project')).toBeLessThan(content.indexOf('<posthog>'))expect(content.indexOf('</posthog>')).toBeLessThan(content.indexOf('Trailing instructions.'))})++ it.each([+ ['an existing file', true],+ ['a missing file', false],+ ])('refuses to follow an AGENTS.md symlink to %s outside the working directory', async (_label, exists) => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))+ const outside = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-outside-')), 'target.md')+ if (exists) {+ await fs.writeFile(outside, 'Outside content.\n')+ }+ await fs.symlink(outside, path.join(dir, 'AGENTS.md'))++ await expect(installAgentsMdSnippet({ cwd: dir })).rejects.toThrow('Refusing to write outside')+ const outsideAfter = await fs.readFile(outside, 'utf-8').catch(() => null)+ expect(outsideAfter).toBe(exists ? 'Outside content.\n' : null)+ })++ it('follows a link inside the target before applying a later ..', async () => {+ const base = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))+ const dir = path.join(base, 'checkout')+ await fs.mkdir(path.join(base, 'outside', 'subdir'), { recursive: true })+ await fs.mkdir(dir)+ await fs.symlink('../outside/subdir', path.join(dir, 'redirect'))+ await fs.symlink('redirect/../target.md', path.join(dir, 'AGENTS.md'))++ await expect(installAgentsMdSnippet({ cwd: dir })).rejects.toThrow('Refusing to write outside')+ await expect(fs.access(path.join(base, 'outside', 'target.md'))).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it.runIf(path.sep === '/')('treats a backslash in a link target as part of a file name', async () => {+ const base = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))+ const dir = path.join(base, 'checkout')+ await fs.mkdir(path.join(base, 'outside'), { recursive: true })+ await fs.mkdir(dir)+ await fs.symlink('../outside', path.join(dir, 'safe\\dir'))+ await fs.symlink('safe\\dir/target.md', path.join(dir, 'AGENTS.md'))++ await expect(installAgentsMdSnippet({ cwd: dir })).rejects.toThrow('Refusing to write outside')+ await expect(fs.access(path.join(base, 'outside', 'target.md'))).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('writes through an AGENTS.md symlink to a missing file inside the working directory', async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-agents-md-'))+ await fs.symlink('CLAUDE.md', path.join(dir, 'AGENTS.md'))++ await installAgentsMdSnippet({ cwd: dir })++ await expect(fs.readFile(path.join(dir, 'CLAUDE.md'), 'utf-8')).resolves.toContain('<posthog>')+ })})diff --git a/services/mcp/tests/unit/cli-skills.test.ts b/services/mcp/tests/unit/cli-skills.test.tsindex 381484bc1b4c..82268be054ec 100644--- a/services/mcp/tests/unit/cli-skills.test.ts+++ b/services/mcp/tests/unit/cli-skills.test.ts@@ -65,4 +65,14 @@ describe('CLI skill installer', () => {await expect(installSkill('../../../outside', { cwd: dir, force: true })).rejects.toThrow('Invalid skill ID')await expect(fs.access(path.join(dir, 'outside'))).rejects.toMatchObject({ code: 'ENOENT' })})++ it('refuses to follow a symlinked .agents directory out of the working directory', async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-cli-skills-'))+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'posthog-cli-outside-'))+ await fs.symlink(outside, path.join(dir, '.agents'))+ mockSkillArchive([skillEntry('test-skill')])++ await expect(installSkill('test-skill', { cwd: dir })).rejects.toThrow('Refusing to write outside')+ await expect(fs.readdir(outside)).resolves.toEqual([])+ })})