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(tasks): report MCP Store connections a run could not mount (#122346)

Georges-Antoine Assi5434ab9a786c
diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.py
index e2867138e717..fb9713a7931a 100644
--- a/products/mcp_store/backend/facade/api.py
+++ b/products/mcp_store/backend/facade/api.py
@@ -27,7 +27,14 @@ from products.mcp_store.backend.connector_approvals import (
consume_connector_approval,
issue_connector_approval,
)
-from products.mcp_store.backend.facade.contracts import ActiveInstallation, ConnectorCallOutcome, ConnectorTool
+from products.mcp_store.backend.facade.contracts import (
+ ActiveInstallation,
+ ConnectorCallOutcome,
+ ConnectorTool,
+ SandboxInstallations,
+ UnmountedInstallation,
+ UnmountedInstallationReason,
+)
from products.mcp_store.backend.gateway import (
agent_grant_owner_label,
agent_grant_proxy_path,
@@ -374,6 +381,69 @@ def get_installations_for_sandbox(
allowed_installation_ids: list[str] | None = None,
allowed_gateway_server_ids: list[str] | None = None,
) -> list[ActiveInstallation]:
+ """The installations ``resolve_installations_for_sandbox`` mounts."""
+ return list(
+ resolve_installations_for_sandbox(
+ team_id,
+ user_id=user_id,
+ include_personal=include_personal,
+ task_origin=task_origin,
+ task_agent_key=task_agent_key,
+ credential_owner_id=credential_owner_id,
+ allowed_installation_ids=allowed_installation_ids,
+ allowed_gateway_server_ids=allowed_gateway_server_ids,
+ ).mounted
+ )
+
+
+def _member_unmounted_reason(
+ installation: MCPServerInstallation,
+ revoked_gateway_server_ids: set[uuid.UUID],
+ allowed_gateway_server_ids: set[str] | None,
+ allowed_installation_ids: set[str] | None,
+) -> UnmountedInstallationReason | None:
+ gateway_server = installation.gateway_server
+ gateway_server_id = gateway_server.id if gateway_server is not None else None
+ if (
+ installation.scope == "shared"
+ and allowed_gateway_server_ids is not None
+ and (gateway_server_id is None or str(gateway_server_id) not in allowed_gateway_server_ids)
+ ):
+ return "not_selected"
+ health_failure: UnmountedInstallationReason | None = None
+ if gateway_server is not None and not gateway_server.is_team_enabled:
+ health_failure = "server_disabled"
+ elif gateway_server_id is not None and gateway_server_id in revoked_gateway_server_ids:
+ health_failure = "revoked"
+ elif not _is_oauth_ready(installation):
+ health_failure = "needs_reconnect"
+ # Healthy unselected installations stay in play until the personal-copy dedup has run.
+ if (
+ health_failure is not None
+ and allowed_installation_ids is not None
+ and str(installation.id) not in allowed_installation_ids
+ ):
+ return "not_selected"
+ return health_failure
+
+
+def _unmounted(installation: MCPServerInstallation, reason: UnmountedInstallationReason) -> UnmountedInstallation:
+ return UnmountedInstallation(
+ id=str(installation.id), name=_resolve_name(installation), scope=installation.scope, reason=reason
+ )
+
+
+def resolve_installations_for_sandbox(
+ team_id: int,
+ *,
+ user_id: int | None = None,
+ include_personal: bool = False,
+ task_origin: str | None = None,
+ task_agent_key: str | None = None,
+ credential_owner_id: int | None = None,
+ allowed_installation_ids: list[str] | None = None,
+ allowed_gateway_server_ids: list[str] | None = None,
+) -> SandboxInstallations:
"""Return MCP installations for sandbox agent use.
Generic tasks retain the legacy team-shared installation behavior. A
@@ -406,7 +476,16 @@ def get_installations_for_sandbox(
workflow step's connector selection); see ``_mounts_for_agent_run``. It
binds on both paths: passing ``[]`` mounts no MCP Store servers at all, and
passing ``None`` leaves the mounts unnarrowed.
+
+ ``unmounted`` lists the enabled member-path installations the run reached but
+ left out, with the reason, so a run can tell its user why a connection is
+ missing. The agent path reports none.
"""
+ allowed_installations = (
+ {str(installation_id) for installation_id in allowed_installation_ids}
+ if allowed_installation_ids is not None
+ else None
+ )
try:
base_queryset = MCPServerInstallation.objects.filter(team_id=team_id, is_enabled=True).select_related(
"template", "gateway_server"
@@ -423,14 +502,15 @@ def get_installations_for_sandbox(
team_id=team_id,
task_origin=task_origin,
)
- return []
+ return SandboxInstallations(mounted=())
agent_key = mapped_agent_key
agent_account = get_built_in_agent(team_id, agent_key) if agent_key is not None else None
if agent_key is not None and agent_account is not None and agent_account.status != "active":
- return []
+ return SandboxInstallations(mounted=())
installations: list[MCPServerInstallation] = []
+ unmounted: list[UnmountedInstallation] = []
agent_mounts: list[tuple[MCPServiceAccountServerAccess, MCPServerInstallation]] = []
if agent_key is not None:
if agent_account is not None:
@@ -447,29 +527,38 @@ def get_installations_for_sandbox(
team_id, agent_account, credential_owner_id, allowed_gateway_server_ids
)
else:
- shared_queryset = base_queryset.filter(scope="shared")
- shared_queryset = shared_queryset.filter(
- Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True)
- )
- if allowed_gateway_server_ids is not None:
- # An explicit allowlist binds here too, so a caller that narrowed its mounts does
- # not silently get every shared installation while the team waits for the
- # `mcp-gateway` rollout. An empty list means the run wants no MCP Store servers.
- shared_queryset = shared_queryset.filter(gateway_server_id__in=allowed_gateway_server_ids)
- if user_id is not None:
- shared_queryset = shared_queryset.exclude(gateway_server__member_revocations__user_id=user_id)
# list() evaluates the lazy querysets here so DB errors hit this handler.
- installations = list(shared_queryset)
+ candidates = list(base_queryset.filter(scope="shared"))
if include_personal and user_id is not None:
- personal_queryset = (
- base_queryset.filter(scope="personal", user_id=user_id)
- .filter(Q(gateway_server__isnull=True) | Q(gateway_server__is_team_enabled=True))
- .exclude(gateway_server__member_revocations__user_id=user_id)
+ candidates.extend(base_queryset.filter(scope="personal", user_id=user_id))
+ revoked_gateway_server_ids: set[uuid.UUID] = (
+ set(
+ MCPMemberServerRevocation.objects.for_team(team_id)
+ .filter(user_id=user_id)
+ .values_list("gateway_server_id", flat=True)
)
- installations.extend(personal_queryset)
+ if user_id is not None
+ else set()
+ )
+ # An explicit allowlist binds here too, so a caller that narrowed its mounts does
+ # not silently get every shared installation while the team waits for the
+ # `mcp-gateway` rollout. An empty list means the run wants no MCP Store servers.
+ allowed_servers = (
+ {str(server_id) for server_id in allowed_gateway_server_ids}
+ if allowed_gateway_server_ids is not None
+ else None
+ )
+ for candidate in candidates:
+ reason = _member_unmounted_reason(
+ candidate, revoked_gateway_server_ids, allowed_servers, allowed_installations
+ )
+ if reason is None:
+ installations.append(candidate)
+ else:
+ unmounted.append(_unmounted(candidate, reason))
except Exception as e:
logger.warning("Error fetching MCP installations for sandbox", error=str(e), team_id=team_id)
- return []
+ return SandboxInstallations(mounted=())
results: list[ActiveInstallation]
if agent_key is not None:
@@ -479,16 +568,25 @@ def get_installations_for_sandbox(
else []
)
else:
- ready = [installation for installation in installations if _is_oauth_ready(installation)]
+ ready = installations
if include_personal and user_id is not None:
personal_urls = {installation.url for installation in ready if installation.scope == "personal"}
+ unmounted.extend(
+ _unmounted(installation, "replaced_by_personal")
+ for installation in ready
+ if installation.scope != "personal" and installation.url in personal_urls
+ )
ready = [
installation
for installation in ready
if installation.scope == "personal" or installation.url not in personal_urls
]
- if allowed_installation_ids is not None:
- allowed_installations = {str(installation_id) for installation_id in allowed_installation_ids}
+ if allowed_installations is not None:
+ unmounted.extend(
+ _unmounted(installation, "not_selected")
+ for installation in ready
+ if str(installation.id) not in allowed_installations
+ )
ready = [installation for installation in ready if str(installation.id) in allowed_installations]
results = [_to_info(installation, team_id) for installation in ready]
@@ -499,8 +597,9 @@ def get_installations_for_sandbox(
include_personal=include_personal,
task_origin=task_origin,
has_trusted_agent_key=agent_key is not None,
+ unmounted_count=len(unmounted),
)
- return results
+ return SandboxInstallations(mounted=tuple(results), unmounted=tuple(unmounted))
def get_sandbox_mcp_server_names(
diff --git a/products/mcp_store/backend/facade/contracts.py b/products/mcp_store/backend/facade/contracts.py
index c5ba1336880a..988c228a0741 100644
--- a/products/mcp_store/backend/facade/contracts.py
+++ b/products/mcp_store/backend/facade/contracts.py
@@ -58,3 +58,30 @@ class ActiveInstallation:
# Set only for credentials delegated to a built-in agent. Kept out of reprs so the
# short-lived bearer cannot accidentally land in logs.
proxy_token: str | None = field(default=None, repr=False)
+
+
+UnmountedInstallationReason = Literal[
+ "needs_reconnect",
+ "server_disabled",
+ "revoked",
+ "not_selected",
+ "replaced_by_personal",
+]
+
+
+@dataclass(frozen=True)
+class UnmountedInstallation:
+ """An enabled installation a sandbox run could reach but did not mount."""
+
+ id: str
+ name: str
+ scope: str
+ reason: UnmountedInstallationReason
+
+
+@dataclass(frozen=True)
+class SandboxInstallations:
+ """What a sandbox run mounts from the MCP Store, and what it left out."""
+
+ mounted: tuple[ActiveInstallation, ...]
+ unmounted: tuple[UnmountedInstallation, ...] = ()
diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.py
index e022a5810c67..cdc930bb0115 100644
--- a/products/mcp_store/backend/test/test_facade.py
+++ b/products/mcp_store/backend/test/test_facade.py
@@ -20,8 +20,13 @@ from products.mcp_store.backend.facade.api import (
get_sandbox_mcp_server_names,
member_server_tools,
resolve_agent_gateway_server_ids,
+ resolve_installations_for_sandbox,
+)
+from products.mcp_store.backend.facade.contracts import (
+ ActiveInstallation,
+ UnmountedInstallation,
+ UnmountedInstallationReason,
)
-from products.mcp_store.backend.facade.contracts import ActiveInstallation
from products.mcp_store.backend.models import (
MCPGatewayServer,
MCPMemberServerRevocation,
@@ -292,6 +297,55 @@ class TestGetInstallationsForSandbox(BaseTest):
scopes = {r.scope for r in results}
assert scopes == {"shared", "personal"}
+ @parameterized.expand(
+ [
+ ("needs_reconnect", None, "needs_reconnect"),
+ ("server_disabled", None, "server_disabled"),
+ ("revoked", None, "revoked"),
+ ("replaced_by_personal", None, "replaced_by_personal"),
+ ("needs_reconnect", [], "not_selected"),
+ ("server_disabled", [], "not_selected"),
+ ("revoked", [], "not_selected"),
+ ]
+ )
+ def test_member_run_reports_why_a_reachable_installation_is_not_mounted(
+ self,
+ reason: UnmountedInstallationReason,
+ allowed_installation_ids: list[str] | None,
+ expected_reason: UnmountedInstallationReason,
+ ) -> None:
+ server = self._create_gateway_server(
+ name="Linear", url="https://mcp.linear.app/mcp", is_team_enabled=reason != "server_disabled"
+ )
+ left_out = self._create_installation(
+ scope="shared",
+ display_name="Linear",
+ url=server.url,
+ gateway_server=server,
+ auth_type="oauth",
+ sensitive_configuration={"access_token": "tok", "needs_reauth": True}
+ if reason == "needs_reconnect"
+ else {"access_token": "tok"},
+ )
+ if reason == "revoked":
+ MCPMemberServerRevocation.objects.for_team(self.team.id).create(
+ team_id=self.team.id, gateway_server=server, user=self.user
+ )
+ if reason == "replaced_by_personal":
+ self._create_installation(scope="personal", url=server.url, display_name="My Linear")
+
+ resolution = resolve_installations_for_sandbox(
+ self.team.id,
+ user_id=self.user.id,
+ include_personal=True,
+ allowed_installation_ids=allowed_installation_ids,
+ )
+
+ assert str(left_out.id) not in {installation.id for installation in resolution.mounted}
+ assert resolution.unmounted == (
+ UnmountedInstallation(id=str(left_out.id), name="Linear", scope="shared", reason=expected_reason),
+ )
+
def test_shared_visible_to_any_team_member(self) -> None:
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
self._create_installation(scope="shared", user=other_user, display_name="Other's Shared")
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index 16ba2c57d6d6..a790522598fd 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -57,6 +57,7 @@ from products.tasks.backend.temporal.process_task.utils import (
mcp_exclude_tools_from_state,
record_delivered_message,
sandbox_identity_scope,
+ unmounted_mcp_installations_log_fields,
upgrade_run_to_user_authorship,
)
@@ -787,7 +788,7 @@ def _refresh_sandbox_mcp(
origin_product=task_run.task.origin_product,
exclude_tools=mcp_exclude_tools_from_state(state),
)
- user_mcp_configs = get_user_mcp_server_configs(
+ user_mcp = get_user_mcp_server_configs(
token=access_token,
team_id=task_run.team_id,
user_id=actor_user.id,
@@ -800,8 +801,17 @@ def _refresh_sandbox_mcp(
credential_owner_id=task_run.task.mcp_credential_owner_id,
allowed_gateway_server_ids=task_run.task.mcp_gateway_server_allowlist,
)
- if user_mcp_configs:
- mcp_configs = mcp_configs + user_mcp_configs
+ if user_mcp.configs:
+ mcp_configs = mcp_configs + user_mcp.configs
+ if user_mcp.unmounted:
+ logger.info(
+ "mcp_installations_not_mounted",
+ team_id=task_run.team_id,
+ task_id=str(task_run.task_id),
+ run_id=run_id,
+ user_id=actor_user.id,
+ unmounted=unmounted_mcp_installations_log_fields(user_mcp.unmounted),
+ )
# refresh_session replaces the session's server list wholesale, so the
# run's imported servers must ride along or they vanish mid-run.
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 6e380090d58d..9cbe07f3514c 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -2,6 +2,7 @@ import json
import time
import shlex
import threading
+from collections.abc import Sequence
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import UTC, datetime
@@ -23,6 +24,7 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from posthog.temporal.oauth import PosthogMcpScopes
+from products.mcp_store.backend.facade.contracts import UnmountedInstallation
from products.tasks.backend.constants import SUBSCRIPTION_PLAN_NAMES
from products.tasks.backend.exceptions import (
OAuthTokenError,
@@ -77,6 +79,8 @@ from products.tasks.backend.temporal.process_task.utils import (
loop_mcp_installation_allowlist,
mark_sandbox_mcp_session,
mcp_exclude_tools_from_state,
+ unmounted_mcp_installations_log_fields,
+ unmounted_mcp_installations_notice,
)
from .get_task_processing_context import TaskProcessingContext
@@ -403,6 +407,21 @@ def _record_network_enforcement_observation(ctx: TaskProcessingContext) -> None:
record_network_enforcement("startup_observed", runtime, observation, "success")
+def _report_unmounted_mcp_installations(ctx: TaskProcessingContext, unmounted: Sequence[UnmountedInstallation]) -> None:
+ if not unmounted:
+ return
+ logger.info(
+ "mcp_installations_not_mounted",
+ team_id=ctx.team_id,
+ task_id=ctx.task_id,
+ run_id=ctx.run_id,
+ unmounted=unmounted_mcp_installations_log_fields(unmounted),
+ )
+ notice = unmounted_mcp_installations_notice(unmounted)
+ if notice:
+ emit_agent_log(ctx.run_id, "warn", notice)
+
+
def _include_personal_mcp_for_task(task: Task) -> bool:
"""Whether a run may pull the task creator's *personal* MCP installations.
@@ -515,7 +534,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
exclude_tools=mcp_exclude_tools_from_state(ctx.state),
)
include_personal = _include_personal_mcp_for_task(task)
- user_mcp_configs = get_user_mcp_server_configs(
+ user_mcp = get_user_mcp_server_configs(
token=access_token,
team_id=ctx.team_id,
user_id=actor_user.id if actor_user else None,
@@ -528,8 +547,9 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
credential_owner_id=task.mcp_credential_owner_id,
allowed_gateway_server_ids=task.mcp_gateway_server_allowlist,
)
- if user_mcp_configs:
- mcp_configs = mcp_configs + user_mcp_configs
+ if user_mcp.configs:
+ mcp_configs = mcp_configs + user_mcp.configs
+ _report_unmounted_mcp_installations(ctx, user_mcp.unmounted)
imported_mcp_configs = get_imported_mcp_server_configs(task_run, {config.name for config in mcp_configs})
if imported_mcp_configs:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index ae342dde7e80..82a831c83b79 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -39,6 +39,7 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
launch_agent_server,
start_agent_server,
)
+from products.tasks.backend.temporal.process_task.utils import UserMcpServerConfigs
@pytest.fixture(autouse=True)
@@ -743,7 +744,7 @@ def _mock_prepare_launch_dependencies(mocker) -> None:
mocker.patch(f"{prefix}.create_oauth_access_token_for_run", return_value="access-token")
mocker.patch(f"{prefix}.TaskRun.objects.filter").return_value.first.return_value = mocker.Mock()
mocker.patch(f"{prefix}.get_sandbox_ph_mcp_configs", return_value=[])
- mocker.patch(f"{prefix}.get_user_mcp_server_configs", return_value=[])
+ mocker.patch(f"{prefix}.get_user_mcp_server_configs", return_value=UserMcpServerConfigs(configs=[]))
mocker.patch(f"{prefix}.get_imported_mcp_server_configs", return_value=[])
mocker.patch(f"{prefix}.get_relayed_mcp_server_names", return_value=[])
mocker.patch(f"{prefix}.emit_agent_log")
@@ -1109,7 +1110,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(
)
get_user_mcp_configs = mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.get_user_mcp_server_configs",
- return_value=[],
+ return_value=UserMcpServerConfigs(configs=[]),
)
mocker.patch(
"products.tasks.backend.temporal.process_task.activities.start_agent_server.TaskRun.objects.filter",
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index 6d7ec13c621c..13800b81c9e2 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -28,6 +28,7 @@ from products.tasks.backend.temporal.process_task.activities.send_followup_to_sa
from products.tasks.backend.temporal.process_task.utils import (
McpServerConfig,
PrAuthorshipMode,
+ UserMcpServerConfigs,
_sandbox_identity_cache_key,
get_sandbox_github_identity_user,
get_sandbox_mcp_session_user,
@@ -95,7 +96,7 @@ def _refresh(task_run, actor_id: int | None = 42, scopes="read_only", auth_token
def _arm_success(mock_oauth, mock_ph_configs, mock_user_configs, mock_send_refresh):
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = [_make_mcp_config(token="fresh-token")]
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
mock_send_refresh.return_value = CommandResult(success=True, status_code=200)
@@ -159,7 +160,7 @@ class TestRefreshSandboxMcp:
this, the run's client-imported servers vanish at the first token refresh."""
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = [_make_mcp_config(token="fresh-token")]
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
mock_send_refresh.return_value = CommandResult(success=True, status_code=200)
task_run = _make_task_run_mock()
@@ -272,7 +273,7 @@ class TestRefreshSandboxMcp:
# caller fails the follow-up closed) and the previous binding is left as is.
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = [_make_mcp_config()]
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
mock_send_refresh.return_value = CommandResult(success=False, status_code=502, error="down")
mark_sandbox_mcp_session("run-1", 99)
@@ -291,7 +292,7 @@ class TestRefreshSandboxMcp:
# rebind, the gate reports unsafe so the caller fails closed.
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = [_make_mcp_config()]
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
mock_send_refresh.return_value = CommandResult(success=False, status_code=502, error="down")
actor = MagicMock(id=42)
@@ -393,7 +394,7 @@ class TestSessionIdentityGate:
# Reject the turn rather than run it against the prior actor's session.
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = []
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
mark_sandbox_mcp_session("run-1", 99)
actor = MagicMock(id=42)
@@ -411,7 +412,7 @@ class TestSessionIdentityGate:
# because MCP is unavailable. The binding is recorded for later transitions.
mock_oauth.return_value = "fresh-token"
mock_ph_configs.return_value = []
- mock_user_configs.return_value = []
+ mock_user_configs.return_value = UserMcpServerConfigs(configs=[])
actor = MagicMock(id=42)
failure = _refresh_sandbox_mcp(_make_task_run_mock(), "read_only", None, actor_user=actor, state=None)
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index a19437d0458f..20007657684f 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -12,7 +12,7 @@ from posthog.models.integration import GitHubIntegration
from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
-from products.mcp_store.backend.facade.contracts import ActiveInstallation
+from products.mcp_store.backend.facade.contracts import ActiveInstallation, SandboxInstallations
from products.tasks.backend.constants import (
DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,
DEFAULT_SANDBOX_WORKING_DIR,
@@ -497,7 +497,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
CREDENTIAL_OWNER_ID = 99
API_BASE = "https://us.posthog.com"
- MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.get_installations_for_sandbox"
+ MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.resolve_installations_for_sandbox"
MOCK_API_URL = "products.tasks.backend.temporal.process_task.utils.get_sandbox_api_url"
def _make_installation(self, **kwargs) -> ActiveInstallation:
@@ -523,9 +523,11 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
) -> None:
mock_api_url.return_value = self.API_BASE
installation = self._make_installation()
- mock_facade.return_value = [installation]
+ mock_facade.return_value = SandboxInstallations(mounted=(installation,))
- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, origin_product=origin_product)
+ configs = get_user_mcp_server_configs(
+ self.TOKEN, self.TEAM_ID, self.USER_ID, origin_product=origin_product
+ ).configs
if not mounts_store:
assert configs == []
@@ -556,11 +558,11 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
# Connectors are mounted unconnected, so the agent's tool search matches them on this
# description; without it "Linear" is only findable by literally searching "linear".
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = [
- self._make_installation(description="Manage Linear issues, projects, and workflows.")
- ]
+ mock_facade.return_value = SandboxInstallations(
+ mounted=(self._make_installation(description="Manage Linear issues, projects, and workflows."),)
+ )
- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)
+ configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID).configs
assert configs[0].description == "Manage Linear issues, projects, and workflows."
@@ -574,7 +576,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
# the member path (and only there), so this layer must hand it over untouched, an empty
# selection included.
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = []
+ mock_facade.return_value = SandboxInstallations(mounted=())
get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, allowed_installation_ids=allowed)
@@ -617,7 +619,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
mock_api_url,
) -> None:
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = [self._make_installation()]
+ mock_facade.return_value = SandboxInstallations(mounted=(self._make_installation(),))
configs = get_user_mcp_server_configs(
self.TOKEN,
@@ -626,7 +628,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
interaction_origin=interaction_origin,
slack_reply_context=slack_reply_context,
origin_product=origin_product,
- )
+ ).configs
assert configs[0].headers == self._expected_user_headers(consumer=expected_consumer)
@@ -636,15 +638,17 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
self, mock_facade, mock_api_url
) -> None:
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = [
- self._make_installation(
- id="shared-id",
- name="Shared",
- proxy_path="/api/mcp_store/gateway/servers/server-id/proxy/",
- scope="shared",
- proxy_token="agent-token",
- ),
- ]
+ mock_facade.return_value = SandboxInstallations(
+ mounted=(
+ self._make_installation(
+ id="shared-id",
+ name="Shared",
+ proxy_path="/api/mcp_store/gateway/servers/server-id/proxy/",
+ scope="shared",
+ proxy_token="agent-token",
+ ),
+ )
+ )
configs = get_user_mcp_server_configs(
self.TOKEN,
@@ -654,7 +658,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
task_agent_key="support",
credential_owner_id=self.CREDENTIAL_OWNER_ID,
allowed_gateway_server_ids=["server-1"],
- )
+ ).configs
# The credential owner is forwarded separately from the acting user: the sandbox acts
# as `user_id`, but it may only mount the grants belonging to the owner. The per-scout
@@ -687,7 +691,7 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
@patch(MOCK_FACADE)
def test_include_personal_is_forwarded_to_facade(self, include_personal: bool, mock_facade, mock_api_url) -> None:
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = []
+ mock_facade.return_value = SandboxInstallations(mounted=())
get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID, include_personal=include_personal)
@@ -706,17 +710,17 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
@patch(MOCK_FACADE)
def test_returns_empty_when_no_installations(self, mock_facade, mock_api_url) -> None:
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = []
+ mock_facade.return_value = SandboxInstallations(mounted=())
- assert get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID) == []
+ assert get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID).configs == []
@patch(MOCK_API_URL)
@patch(MOCK_FACADE)
def test_strips_trailing_slash_from_api_url(self, mock_facade, mock_api_url) -> None:
mock_api_url.return_value = "https://us.posthog.com/"
- mock_facade.return_value = [self._make_installation()]
+ mock_facade.return_value = SandboxInstallations(mounted=(self._make_installation(),))
- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)
+ configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID).configs
assert configs[0].url.startswith("https://us.posthog.com/api/")
@@ -724,16 +728,18 @@ class TestFetchUserMcpServerConfigs(SimpleTestCase):
@patch(MOCK_FACADE)
def test_multiple_installations(self, mock_facade, mock_api_url) -> None:
mock_api_url.return_value = self.API_BASE
- mock_facade.return_value = [
- self._make_installation(
- id="abc-1", name="Linear", proxy_path="/api/environments/42/mcp_server_installations/abc-1/proxy/"
- ),
- self._make_installation(
- id="abc-2", name="Notion", proxy_path="/api/environments/42/mcp_server_installations/abc-2/proxy/"
- ),
- ]
+ mock_facade.return_value = SandboxInstallations(
+ mounted=(
+ self._make_installation(
+ id="abc-1", name="Linear", proxy_path="/api/environments/42/mcp_server_installations/abc-1/proxy/"
+ ),
+ self._make_installation(
+ id="abc-2", name="Notion", proxy_path="/api/environments/42/mcp_server_installations/abc-2/proxy/"
+ ),
+ )
+ )
- configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID)
+ configs = get_user_mcp_server_configs(self.TOKEN, self.TEAM_ID, self.USER_ID).configs
assert len(configs) == 2
assert configs[0].name == "Linear"
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 9a8c6748dc8f..11845aa2de0d 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -13,6 +13,7 @@ from django.db import transaction
from pydantic import BaseModel
+from posthog.dataclasses import frozen
from posthog.egress.limiter.policies import Priority
from posthog.enums import LabeledStrEnum
from posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_ready
@@ -27,7 +28,8 @@ from posthog.models.user_integration import (
)
from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopes
-from products.mcp_store.backend.facade.api import get_installations_for_sandbox
+from products.mcp_store.backend.facade.api import resolve_installations_for_sandbox
+from products.mcp_store.backend.facade.contracts import UnmountedInstallation, UnmountedInstallationReason
from products.tasks.backend import model_catalog
from products.tasks.backend.constants import (
ALLOWED_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATHS,
@@ -590,6 +592,43 @@ def loop_mcp_installation_allowlist(state: dict | None) -> list[str] | None:
return [str(i) for i in ids] if isinstance(ids, list) else []
+@frozen
+class UserMcpServerConfigs:
+ configs: list[McpServerConfig]
+ unmounted: tuple[UnmountedInstallation, ...] = ()
+
+
+_UNMOUNTED_REASON_NOTICES: dict[UnmountedInstallationReason, str] = {
+ "needs_reconnect": "reconnect it in the MCP Store",
+ "server_disabled": "a project admin turned this server off",
+ "revoked": "a project admin turned this server off for you",
+}
+
+
+def unmounted_mcp_installations_notice(unmounted: Sequence[UnmountedInstallation]) -> str | None:
+ """The run-log warning for connections the user expects but the run left out.
+
+ A connection the run's own selection excluded, or one the user's personal copy replaced,
+ is the expected outcome, so it is not reported.
+ """
+ missing = [
+ f"{installation.name} ({_UNMOUNTED_REASON_NOTICES[installation.reason]})"
+ for installation in unmounted
+ if installation.reason in _UNMOUNTED_REASON_NOTICES
+ ]
+ if not missing:
+ return None
+ noun = "connection was" if len(missing) == 1 else "connections were"
+ return f"{len(missing)} MCP Store {noun} not added to this run: {', '.join(missing)}."
+
+
+def unmounted_mcp_installations_log_fields(unmounted: Sequence[UnmountedInstallation]) -> list[dict[str, str]]:
+ return [
+ {"id": installation.id, "name": installation.name, "scope": installation.scope, "reason": installation.reason}
+ for installation in unmounted
+ ]
+
+
def get_user_mcp_server_configs(
token: str,
team_id: int,
@@ -603,7 +642,7 @@ def get_user_mcp_server_configs(
task_agent_key: str | None = None,
credential_owner_id: int | None = None,
allowed_gateway_server_ids: list[str] | None = None,
-) -> list[McpServerConfig]:
+) -> UserMcpServerConfigs:
"""Fetch MCP Store installations for sandbox use and return configs.
Unmapped tasks include shared team installations. Built-in agent tasks only
@@ -634,12 +673,14 @@ def get_user_mcp_server_configs(
identity propagates through the MCP Store proxy to whichever upstream MCP
the user installed. Non-PostHog upstreams ignore the header.
- Returns an empty list on errors (non-fatal).
+ ``unmounted`` carries the installations the run reached but left out, with the reason.
+
+ Returns no configs on errors (non-fatal).
"""
if origin_product == "account_audit":
- return []
+ return UserMcpServerConfigs(configs=[])
- installations = get_installations_for_sandbox(
+ resolution = resolve_installations_for_sandbox(
team_id,
user_id=user_id,
include_personal=include_personal,
@@ -655,7 +696,7 @@ def get_user_mcp_server_configs(
)
configs: list[McpServerConfig] = []
- for installation in installations:
+ for installation in resolution.mounted:
headers = [
{"name": "Authorization", "value": f"Bearer {installation.proxy_token or token}"},
{"name": "x-posthog-mcp-consumer", "value": consumer},
@@ -670,7 +711,7 @@ def get_user_mcp_server_configs(
)
)
- return configs
+ return UserMcpServerConfigs(configs=configs, unmounted=resolution.unmounted)
def build_imported_mcp_server_configs(