Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp): respect locked org rules in posthog ai mcp tool calls (#108149)

Vojta Bartošc808216a90a7
diff --git a/ee/hogai/tools/call_mcp_server/installations.py b/ee/hogai/tools/call_mcp_server/installations.py
index a724b838e31c..f845afc58657 100644
--- a/ee/hogai/tools/call_mcp_server/installations.py
+++ b/ee/hogai/tools/call_mcp_server/installations.py
@@ -6,7 +6,7 @@ from django.db.models import Q
from posthog.models import Team, User
-from products.mcp_store.backend.facade.api import resolve_member_tool_states
+from products.mcp_store.backend.facade.api import resolve_member_tool_states, resolve_member_unlisted_tool_state
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool
from products.mcp_store.backend.oauth import refresh_installation_token
@@ -95,9 +95,16 @@ def _get_tool_approval_states(
team_id,
gateway_server_id,
user_id=user.id if user is not None else None,
+ block_locked_approvals=True,
)
+def _get_unlisted_tool_state(
+ installation_id: str, team_id: int, gateway_server_id: UUID, user: User, tool_name: str
+) -> str:
+ return resolve_member_unlisted_tool_state(installation_id, team_id, gateway_server_id, user.id, tool_name)
+
+
def _mark_needs_reauth_sync(installation_id: str) -> None:
try:
inst = MCPServerInstallation.objects.get(id=installation_id)
diff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.py
index 2adabb9b3815..43aced091b91 100644
--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py
+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py
@@ -14,6 +14,7 @@ from posthog.security.url_validation import PinnedUrlVerdict
from products.mcp_store.backend.models import (
MCPGatewayServer,
+ MCPOrgRule,
MCPServerInstallation,
MCPServerInstallationTool,
TeamMCPGatewayConfig,
@@ -1062,6 +1063,76 @@ class TestIsDangerousOperation(TestCallMCPServerTool):
tool = self._create_tool(installations=[self._inst_dict(installation)])
self.assertTrue(await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="new_tool"))
+ @parameterized.expand([("listed_tool", True), ("unlisted_tool", False)])
+ @patch("products.mcp_store.backend.facade.api.resync_installation_tools", return_value=False)
+ async def test_org_rule_locked_approval_cannot_be_self_approved(
+ self, _name: str, tool_is_listed: bool, _mock_resync
+ ) -> None:
+ def _setup() -> tuple[MCPServerInstallation, MCPGatewayServer]:
+ server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team, name="Linear", url=self.SERVER_URL
+ )
+ installation = self._seed({"delete_issue": "approved"} if tool_is_listed else {})
+ installation.gateway_server = server
+ installation.save()
+ MCPOrgRule.objects.for_team(self.team.id).create(
+ team=self.team, name="Review deletes", effect="needs_approval", tool_pattern="delete_*"
+ )
+ return installation, server
+
+ installation, server = await sync_to_async(_setup)()
+ tool = self._create_tool(installations=[{**self._inst_dict(installation), "gateway_server_id": server.id}])
+
+ self.assertFalse(await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="delete_issue"))
+ with patch("ee.hogai.tools.call_mcp_server.tool.MCPClient") as MockClient:
+ mock_instance = self._make_mock_client()
+ MockClient.return_value = mock_instance
+ with self.assertRaises(MaxToolFatalError):
+ await tool._arun_impl(server_url=self.SERVER_URL, tool_name="delete_issue", arguments={})
+ mock_instance.call_tool.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("relisting_unavailable", None, False),
+ ("relisting_finds_destructive_hint", {"destructiveHint": True}, False),
+ ("relisting_finds_safe_tool", {}, True),
+ ]
+ )
+ async def test_unlisted_tool_resolves_pattern_less_rule_with_relisted_annotations(
+ self, _name: str, relisted_annotations: dict | None, needs_prompt: bool
+ ) -> None:
+ def _setup() -> tuple[MCPServerInstallation, MCPGatewayServer]:
+ server = MCPGatewayServer.objects.for_team(self.team.id).create(
+ team=self.team, name="Linear", url=self.SERVER_URL
+ )
+ installation = self._seed({})
+ installation.gateway_server = server
+ installation.save()
+ MCPOrgRule.objects.for_team(self.team.id).create(team=self.team, name="Block destructive tools")
+ return installation, server
+
+ def _relist(installation: MCPServerInstallation) -> bool:
+ if relisted_annotations is None:
+ return False
+ MCPServerInstallationTool.objects.create(
+ installation=installation,
+ tool_name="close_ticket",
+ annotations=relisted_annotations,
+ last_seen_at=timezone.now(),
+ )
+ return True
+
+ installation, server = await sync_to_async(_setup)()
+ tool = self._create_tool(installations=[{**self._inst_dict(installation), "gateway_server_id": server.id}])
+
+ with patch("products.mcp_store.backend.facade.api.resync_installation_tools", side_effect=_relist):
+ is_dangerous = await tool.is_dangerous_operation(server_url=self.SERVER_URL, tool_name="close_ticket")
+
+ self.assertEqual(is_dangerous, needs_prompt)
+ self.assertEqual(
+ tool._approval_cache[self.SERVER_URL]["close_ticket"], "needs_approval" if needs_prompt else "do_not_use"
+ )
+
async def test_unknown_server_url_does_not_trigger_approval(self):
# Validation will reject it during execution; approval gate stays off.
installation = await sync_to_async(self._seed)({})
diff --git a/ee/hogai/tools/call_mcp_server/tool.py b/ee/hogai/tools/call_mcp_server/tool.py
index c6e2af9c5402..58037e2d68ba 100644
--- a/ee/hogai/tools/call_mcp_server/tool.py
+++ b/ee/hogai/tools/call_mcp_server/tool.py
@@ -24,6 +24,7 @@ from .installations import (
_get_cached_tools,
_get_installations,
_get_tool_approval_states,
+ _get_unlisted_tool_state,
_mark_needs_reauth_sync,
_refresh_token_sync,
)
@@ -148,7 +149,18 @@ class CallMCPServerTool(MaxTool):
async def _resolve_approval_state(self, server_url: str, tool_name: str) -> str:
states = await self._get_approval_states(server_url)
- return states.get(tool_name, _APPROVAL_DEFAULT)
+ if tool_name in states:
+ return states[tool_name]
+ inst = self._get_installation(server_url)
+ gateway_server_id = inst.get("gateway_server_id")
+ if gateway_server_id is None:
+ return _APPROVAL_DEFAULT
+ # An org rule can match a tool the installation has no row for yet.
+ state = await database_sync_to_async(_get_unlisted_tool_state)(
+ str(inst["id"]), self._team.id, gateway_server_id, self._user, tool_name
+ )
+ states[tool_name] = state
+ return state
async def is_dangerous_operation(
self, *, server_url: str, tool_name: str, arguments: dict | None = None, **_kwargs
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index 29eeb126bf9c..fad945305146 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_policy_state_allowed,
+ is_read_only_connector_tool,
+)
from products.mcp_store.backend.proxy import record_tool_call_audit, resolve_call_decision, validate_installation_auth
from products.mcp_store.backend.tools import (
ToolCallError,
@@ -63,6 +68,8 @@ def resolve_member_tool_states(
team_id: int,
gateway_server_id: uuid.UUID | None,
user_id: int | None = None,
+ *,
+ block_locked_approvals: bool = False,
) -> dict[str, str]:
"""Return a {tool_name: effective_state} map for an installation.
@@ -73,7 +80,11 @@ def resolve_member_tool_states(
call them even if the cached approval state was previously `approved` —
if the tool is gone upstream, it's gone. Anything not in the map is
treated as `needs_approval` by the caller (explicit opt-in for freshly
- discovered tools)."""
+ discovered tools).
+
+ With `block_locked_approvals`, a `needs_approval` state that an org rule
+ locks surfaces as `"do_not_use"`. Use it for callers that approve calls
+ on 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"
)
@@ -93,10 +104,56 @@ def resolve_member_tool_states(
if row["removed_at"]:
resolved[row["tool_name"]] = "do_not_use"
else:
- resolved[row["tool_name"]] = context.resolve(row["tool_name"], row["annotations"]).state
+ resolved[row["tool_name"]] = _member_tool_state(
+ context, row["tool_name"], row["annotations"], block_locked_approvals=block_locked_approvals
+ )
return resolved
+def resolve_member_unlisted_tool_state(
+ installation_id: str,
+ team_id: int,
+ gateway_server_id: uuid.UUID,
+ user_id: int,
+ tool_name: str,
+) -> str:
+ """Return the effective state of a tool the installation has no row for.
+
+ The installation re-lists its tools once, so a tool the upstream server
+ added later resolves with its real annotations. Without a row the
+ annotations are unknown, so the tool resolves as if it were destructive.
+ The result is never looser than `needs_approval`, the default for
+ unknown tools."""
+ installation = MCPServerInstallation.objects.filter(id=installation_id, team_id=team_id).first()
+ tool = _registered_tool(installation, tool_name) if installation is not None else None
+ context = PolicyContext(
+ team_id=team_id,
+ caller=GatewayCaller(kind="member", user_id=user_id),
+ gateway_server_id=gateway_server_id,
+ legacy_rows={},
+ )
+ if tool is not None and tool.removed_at is None:
+ state = _member_tool_state(context, tool_name, tool.annotations, block_locked_approvals=True)
+ else:
+ as_listed = _member_tool_state(context, tool_name, None, block_locked_approvals=True)
+ as_destructive = _member_tool_state(context, tool_name, {"destructiveHint": True}, block_locked_approvals=True)
+ state = as_destructive if is_policy_state_allowed(as_destructive, as_listed) else as_listed
+ return state if state == "do_not_use" else "needs_approval"
+
+
+def _member_tool_state(
+ context: PolicyContext,
+ tool_name: str,
+ annotations: dict[str, Any] | None,
+ *,
+ block_locked_approvals: bool,
+) -> str:
+ resolved = context.resolve(tool_name, annotations)
+ if block_locked_approvals and resolved.locked and resolved.state == "needs_approval":
+ return "do_not_use"
+ return resolved.state
+
+
def unauthorized_installation_ids(team_id: int, user_id: int, candidate_ids: Iterable[str]) -> list[str]:
"""Return the subset of `candidate_ids` the caller must REJECT — installation
ids not owned by this (team, user). Ownership is keyed by `(team_id, user_id)`
diff --git a/products/mcp_store/backend/test/test_gateway_exec_tools.py b/products/mcp_store/backend/test/test_gateway_exec_tools.py
index 75d0e14f999f..69e7f24bcbc4 100644
--- a/products/mcp_store/backend/test/test_gateway_exec_tools.py
+++ b/products/mcp_store/backend/test/test_gateway_exec_tools.py
@@ -15,6 +15,7 @@ from products.mcp_store.backend.models import (
MCPAuditEvent,
MCPGatewayServer,
MCPMemberServerRevocation,
+ MCPOrgRule,
MCPServerInstallation,
MCPServerInstallationTool,
)
@@ -255,6 +256,18 @@ class TestGatewayExecTools(APIBaseTest):
assert self._available().json()["servers"] == []
+ def test_available_tools_lists_rule_locked_approval_with_its_state(self):
+ self._tool()
+ MCPOrgRule.objects.for_team(self.team.id).create(
+ team=self.team, name="Review issues", effect="needs_approval", tool_pattern="create_*"
+ )
+
+ [server] = self._available().json()["servers"]
+
+ assert [(tool["name"], tool["approval_state"]) for tool in server["tools"]] == [
+ ("create_issue", "needs_approval")
+ ]
+
def test_available_tools_includes_a_teammates_shared_connection(self):
other = self._create_user("[email protected]")
shared = MCPServerInstallation.objects.create(