:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): scout runs mount their creator's MCP grants (#77857)
Chris Volzer02d8ec71cdef
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8064e85f4c0d..50be5fe77694 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4758,10 +4758,10 @@ snapshots:hash: v1.k794b7964.ea754a4783f7653247f127337c407a8cdd4a9c6bc3f1b908d8d00dd1a090b966.KQ3yKnRzi4l3ZeYVThZdmo4L6mAbxtNa2uQh7y-kGWAproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues--tile-filters-read-only--light:hash: v1.k794b7964.b2ca2efc52a9ccf56953159c66d3c8766acd1d3a17379d5faec45a4715ae24a9.fK76p7ZVcgvFJNcKJ5Ixy3YnBm_BcBSFnoytLS2jZdU- ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark- : hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw- ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light- : hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsI+ products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark:+ hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw+ products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light:+ hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsIproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--dark:hash: v1.k794b7964.b1e0f5f542426e34dec73826f3135902a392c0c13dade4fec14037c615186b13.kbxxijyDI1SdvgdKwkRnIRLLgmsine5AYvOcD79DYsYproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--light:diff --git a/products/mcp_store/backend/agents.py b/products/mcp_store/backend/agents.pyindex 4211dbdd78f2..50d90d187b2b 100644--- a/products/mcp_store/backend/agents.py+++ b/products/mcp_store/backend/agents.py@@ -10,9 +10,10 @@ from django.utils import timezoneimport structlogimport posthoganalytics-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.scoping.manager import TeamScopeErrorfrom posthog.models.utils import hash_key_value+from posthog.user_permissions import UserPermissionsfrom .models import MCPServiceAccount@@ -167,6 +168,28 @@ class GatewayAgentPrincipal:credential_owner_id: int+def credential_owner_eligible(credential_owner_id: int, team_id: int) -> bool:+ """Fresh check that the person whose MCP grants an agent run borrows is+ still an active user with effective access to the team (org membership+ plus any project access control).++ Grant rows and the owner's User row both outlive offboarding, so+ eligibility is re-read wherever grants are resolved instead of being+ trusted from when the grant was created. No row locks are taken, unlike+ the loop-run token mint in products/tasks: gateway agent tokens are+ stateless and re-validated on every proxied call, so a revocation takes+ effect on the next request rather than racing a persisted credential.+ """+ owner = User.objects.filter(id=credential_owner_id, is_active=True).first()+ if owner is None:+ return False+ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ return False+ return UserPermissions(user=owner, team=team).current_team.effective_membership_level is not None++def create_gateway_agent_token(account: MCPServiceAccount, *, credential_owner_id: int) -> str:payload = {"service_account_id": str(account.id),@@ -207,4 +230,8 @@ def resolve_gateway_agent_token(token: str) -> GatewayAgentPrincipal | None:)except (MCPServiceAccount.DoesNotExist, TeamScopeError, ValueError):return None+ # A token outlives offboarding (its max age is hours), so the owner's+ # eligibility is re-checked on every resolution, not just at mint time.+ if not credential_owner_eligible(credential_owner_id, team_id):+ return Nonereturn GatewayAgentPrincipal(account=account, credential_owner_id=credential_owner_id)diff --git a/products/mcp_store/backend/facade/api.py b/products/mcp_store/backend/facade/api.pyindex 3db5e5247f1e..cb530099f5f9 100644--- a/products/mcp_store/backend/facade/api.py+++ b/products/mcp_store/backend/facade/api.py@@ -14,6 +14,7 @@ import structlogfrom products.mcp_store.backend.agents import (built_in_agent_key_for_task_origin,create_gateway_agent_token,+ credential_owner_eligible,get_built_in_agent,is_builtin_agent_enforcement_enabled,)@@ -185,9 +186,13 @@ def get_installations_for_sandbox(Generic tasks retain the legacy team-shared installation behavior. Aserver-stamped built-in agent task gets only the credentials explicitlydelegated through its service-account grants by ``credential_owner_id``,- the person the run acts for, and only while the gateway server stays- enabled for the team. Grants are personal, so an agent task without a- credential owner gets no Store installations at all. Origin alone is not+ the person whose credentials the run may borrow (not necessarily the user+ it acts as), and only while the gateway server stays enabled for the team.+ Grants are personal, so an agent task without a credential owner gets no+ Store installations at all, and the owner's eligibility (active user with+ current effective team access) is re-checked on every call, so an+ offboarded owner's grants stop mounting even though the grant rows+ persist. Origin alone is nottrusted: the persisted task agent key must match the origin mapping. Amapped origin without that marker gets no MCP Store installations. Built-in agenthandling is gated per team on the `mcp-gateway` rollout flag; teams@@ -225,6 +230,15 @@ def get_installations_for_sandbox(if agent_key is not None:if agent_account is None or credential_owner_id is None:installations = []+ elif not credential_owner_eligible(credential_owner_id, team_id):+ # Grants survive offboarding, so an owner who was deactivated+ # or lost team access since delegating mounts nothing.+ logger.warning(+ "Refusing MCP installations for an ineligible credential owner",+ team_id=team_id,+ task_origin=task_origin,+ )+ installations = []else:access_rows = list(MCPServiceAccountServerAccess.objects.for_team(team_id)diff --git a/products/mcp_store/backend/test/test_facade.py b/products/mcp_store/backend/test/test_facade.pyindex 623677699ec2..11be4df67fbb 100644--- a/products/mcp_store/backend/test/test_facade.py+++ b/products/mcp_store/backend/test/test_facade.py@@ -4,8 +4,13 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.models import User+from posthog.models.organization import OrganizationMembership-from products.mcp_store.backend.agents import get_built_in_agent+from products.mcp_store.backend.agents import (+ create_gateway_agent_token,+ get_built_in_agent,+ resolve_gateway_agent_token,+)from products.mcp_store.backend.facade.api import get_active_installations, get_installations_for_sandboxfrom products.mcp_store.backend.facade.contracts import ActiveInstallationInfofrom products.mcp_store.backend.models import (@@ -358,10 +363,57 @@ class TestGetInstallationsForSandbox(BaseTest):credential_owner_id=credential_owner_id,)- assert [result.id for result in resolve(self.user.id)] == [str(delegated.id)]+ owned = resolve(self.user.id)+ assert [result.id for result in owned] == [str(delegated.id)]assert resolve(other_user.id) == []assert resolve(None) == []+ # The proxy token must name the same owner the grants were resolved under, or the+ # gateway would serve the run under a different person's credentials.+ principal = resolve_gateway_agent_token(owned[0].proxy_token or "")+ assert principal is not None+ assert principal.credential_owner_id == self.user.id++ @parameterized.expand([("deactivated",), ("removed_from_org",)])+ def test_built_in_agent_mounts_nothing_once_credential_owner_loses_eligibility(self, revocation: str) -> None:+ account = self._support_agent()+ server = self._create_gateway_server(name="Granted", url="https://granted.example.com/mcp")+ delegated = self._create_installation(scope="personal", gateway_server=server, url=server.url)+ MCPServiceAccountServerAccess.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ user=self.user,+ service_account=account,+ gateway_server=server,+ installation=delegated,+ granted_by=self.user,+ )++ def resolve() -> list[ActiveInstallationInfo]:+ return get_installations_for_sandbox(+ self.team.id,+ task_origin="support_reply",+ task_agent_key="support",+ credential_owner_id=self.user.id,+ )++ assert [result.id for result in resolve()] == [str(delegated.id)]++ if revocation == "deactivated":+ User.objects.filter(id=self.user.id).update(is_active=False)+ else:+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).delete()++ assert resolve() == []++ def test_agent_token_stops_resolving_once_credential_owner_loses_eligibility(self) -> None:+ account = self._support_agent()+ token = create_gateway_agent_token(account, credential_owner_id=self.user.id)+ assert resolve_gateway_agent_token(token) is not None++ User.objects.filter(id=self.user.id).update(is_active=False)++ assert resolve_gateway_agent_token(token) is None+def test_built_in_agent_does_not_fall_back_after_delegated_credential_is_deleted(self) -> None:account = self._support_agent()server = self._create_gateway_server(diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 5d8c2d95e9c5..aabf4618b5e3 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -677,6 +677,10 @@ async def _spawn_and_run(verbose=verbose,origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT,mcp_builtin_agent_key="scout",+ # MCP Store grants are personal, so the run mounts the connections its scout's creator+ # delegated to the Scout agent — not the acting user's, and not the team's. A scout the+ # coordinator auto-discovered has no creator, and mounts no Store connections at all.+ mcp_credential_owner_id=config.created_by_id,# Tag every scout $ai_generation with its stage AND its scout, so scout spend is both# splittable out of the ai_product='signals' bucket (scouts carry no signal_report_id)# and attributable to one scout. `ai_stage` is the only run-shaped value the harnessdiff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex a8e95cf1e03a..2a784384ca31 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -1034,6 +1034,50 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):assert captured["ai_stage"] == "scout:custom"[email protected]("with_creator", [True, False])+async def test_run_delegates_the_scout_creator_as_mcp_credential_owner(ateam, aerrors_skill, with_creator):+ # MCP Store grants are personal, so a scout run mounts the connections its creator delegated+ # to the Scout agent — never the acting user's. A scout with no creator (coordinator+ # auto-discovered) stays fail-closed and mounts nothing.+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)+ captured: dict = {}++ def _seed_config() -> int | None:+ creator = (+ User.objects.create(email=f"scout-owner-{random.randint(1, 99999)}@example.com") if with_creator else None+ )+ SignalScoutConfig.objects.unscoped().create(+ team_id=ateam.id, skill_name="signals-scout-errors", created_by=creator+ )+ return creator.id if creator is not None else None++ owner_id = await database_sync_to_async(_seed_config, thread_sensitive=False)()++ async def _capture_start(*args, on_task_run_created=None, **kwargs):+ captured.update(kwargs)+ if on_task_run_created is not None:+ await on_task_run_created(session.task_run)+ return session, result++ with (+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),+ patch(+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",+ return_value="env-id",+ ),+ patch(+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ return_value=42,+ ),+ ):+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert captured["mcp_builtin_agent_key"] == "scout"+ assert captured["mcp_credential_owner_id"] == owner_id++@pytest.mark.asyncio@pytest.mark.django_db@pytest.mark.parametrize(diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex 65fc973f5d7a..bac42b821d4b 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -210,6 +210,7 @@ async def create_task_and_trigger(internal: bool = False,workflow_id_prefix: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,+ mcp_credential_owner_id: int | None = None,):title = f"[sandbox_prompt:{step_name}] {description[:80]}" if step_name else description[:100]team = await sync_to_async(Team.objects.get)(id=context.team_id)@@ -242,6 +243,7 @@ async def create_task_and_trigger(workflow_id_prefix=workflow_id_prefix,github_read_access=context.github_read_access,mcp_builtin_agent_key=mcp_builtin_agent_key,+ mcp_credential_owner_id=mcp_credential_owner_id,interaction_origin=context.interaction_origin,)# lambda wrap: task.latest_run is a lazy ORM property; sync_to_async needs a callablediff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.pyindex 85290cfbd9ab..dcfd67a093b2 100644--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py@@ -68,6 +68,7 @@ class MultiTurnSession:fallback_from_text: Callable[[str], _ModelT] | None = None,workflow_id_prefix: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,+ mcp_credential_owner_id: int | None = None,) -> tuple[MultiTurnSession, _ModelT]:"""Start a multi-turn sandbox session and wait for the first structured response.@@ -102,6 +103,7 @@ class MultiTurnSession:max_poll_seconds=max_poll_seconds,workflow_id_prefix=workflow_id_prefix,mcp_builtin_agent_key=mcp_builtin_agent_key,+ mcp_credential_owner_id=mcp_credential_owner_id,)try:parsed = cls._parse_and_validate(last_message, model, label="initial turn")@@ -157,6 +159,7 @@ class MultiTurnSession:max_poll_seconds: int | None = None,workflow_id_prefix: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,+ mcp_credential_owner_id: int | None = None,) -> tuple[MultiTurnSession, str]:"""Start a multi-turn sandbox session and return the first raw agent response.@@ -164,6 +167,10 @@ class MultiTurnSession:BEFORE the agent's first turn runs — see `start` for the rationale.`max_poll_seconds` caps each turn's poll budget — see the field docstring.++ `mcp_credential_owner_id` names the person whose MCP Store grants the run may+ mount. It is separate from the acting user in `context`: the sandbox still acts+ as the acting user, but grants are personal, so a run with no owner mounts none."""task, task_run = await create_task_and_trigger(prompt,@@ -176,6 +183,7 @@ class MultiTurnSession:internal=internal,workflow_id_prefix=workflow_id_prefix,mcp_builtin_agent_key=mcp_builtin_agent_key,+ mcp_credential_owner_id=mcp_credential_owner_id,)logger.info("multi_turn: started task=%s run=%s step=%s", task.id, task_run.id, step_name or "unknown")# Get session's parent workflow to send heartbeats to keep the agent alive while waiting for turns.diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 3b40494426a6..0c8435752fbd 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -52,6 +52,7 @@ logger = structlog.get_logger(__name__)LogLevel = Literal["debug", "info", "warn", "error"]MCPBuiltInAgentKey = Literal["support", "scout"]MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"+MCP_CREDENTIAL_OWNER_STATE_KEY = "mcp_credential_owner_id"MCP_BUILT_IN_AGENT_KEY_BY_ORIGIN: dict[str, MCPBuiltInAgentKey] = {"support_reply": "support","signals_scout": "scout",@@ -366,6 +367,19 @@ class Task(DeletedMetaFields, models.Model):marker = (self.state or {}).get(MCP_BUILT_IN_AGENT_STATE_KEY)return expected_key if marker == expected_key else None+ @property+ def mcp_credential_owner_id(self) -> int | None:+ """The person whose MCP Store grants this run may mount.++ Only meaningful on a stamped built-in agent task, so it reads through+ `mcp_builtin_agent_key` — an unstamped or untrusted origin can never+ borrow someone's grants, and a task with no owner mounts nothing.+ """+ if self.mcp_builtin_agent_key is None:+ return None+ owner_id = (self.state or {}).get(MCP_CREDENTIAL_OWNER_STATE_KEY)+ return owner_id if isinstance(owner_id, int) else None+def capture_event(self, event: str, properties: dict | None = None, capture_fn: Callable[..., None] | None = None) -> None:@@ -595,6 +609,7 @@ class Task(DeletedMetaFields, models.Model):custom_image_id: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,client_provenance: TaskClientProvenance | None = None,+ mcp_credential_owner_id: int | None = None,) -> tuple["Task", dict[str, Any]]:"""Create the Task row and assemble the initial run's `extra_state`.@@ -673,6 +688,14 @@ class Task(DeletedMetaFields, models.Model):if mcp_builtin_agent_key is not None and mcp_builtin_agent_key != expected_agent_key:raise ValueError(f"Agent key {mcp_builtin_agent_key!r} does not match task origin {origin_product!r}")+ initial_state: dict[str, Any] = {}+ if mcp_builtin_agent_key:+ initial_state[MCP_BUILT_IN_AGENT_STATE_KEY] = mcp_builtin_agent_key+ # Only ever recorded alongside the agent marker: without one there is no agent+ # run to delegate to, and a stray owner id must not be able to ride on a task.+ if mcp_credential_owner_id is not None:+ initial_state[MCP_CREDENTIAL_OWNER_STATE_KEY] = mcp_credential_owner_id+task = Task.objects.create(team=team,title=title,@@ -686,7 +709,7 @@ class Task(DeletedMetaFields, models.Model):channel=channel,internal=internal,json_schema=resolve_schema(output_schema) if output_schema else None,- state={MCP_BUILT_IN_AGENT_STATE_KEY: mcp_builtin_agent_key} if mcp_builtin_agent_key else {},+ state=initial_state,**({"signal_report_id": signal_report_id} if signal_report_id else {}),)@@ -821,6 +844,7 @@ class Task(DeletedMetaFields, models.Model):initial_permission_mode: str | None = None,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,client_provenance: TaskClientProvenance | None = None,+ mcp_credential_owner_id: int | None = None,) -> "Task":"""Create the Task row without an initial run or workflow.@@ -848,6 +872,7 @@ class Task(DeletedMetaFields, models.Model):initial_permission_mode=initial_permission_mode,mcp_builtin_agent_key=mcp_builtin_agent_key,client_provenance=client_provenance,+ mcp_credential_owner_id=mcp_credential_owner_id,)return task@@ -890,6 +915,7 @@ class Task(DeletedMetaFields, models.Model):custom_image_id: str | None = None,github_read_access: bool = False,mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,+ mcp_credential_owner_id: int | None = None,) -> "Task":from products.tasks.backend.temporal.client import _normalize_slack_context, execute_task_processing_workflow@@ -924,6 +950,7 @@ class Task(DeletedMetaFields, models.Model):custom_image_builder_id=custom_image_builder_id,custom_image_id=custom_image_id,mcp_builtin_agent_key=mcp_builtin_agent_key,+ mcp_credential_owner_id=mcp_credential_owner_id,)run_extra_state = dict(extra_state or {})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.pyindex 507bfbfc8fa2..0e95faa276a9 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@@ -386,6 +386,7 @@ def _refresh_sandbox_mcp(allowed_installation_ids=loop_mcp_installation_allowlist(state),origin_product=task_run.task.origin_product,task_agent_key=task_run.task.mcp_builtin_agent_key,+ credential_owner_id=task_run.task.mcp_credential_owner_id,)if user_mcp_configs:mcp_configs = mcp_configs + user_mcp_configsdiff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 78b6339def20..c5cd6c67a439 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@@ -265,6 +265,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandboallowed_installation_ids=loop_mcp_installation_allowlist(ctx.state),origin_product=task.origin_product,task_agent_key=task.mcp_builtin_agent_key,+ credential_owner_id=task.mcp_credential_owner_id,)if user_mcp_configs:mcp_configs = mcp_configs + user_mcp_configsdiff --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.pyindex 717e9c933649..f0bedbf591fe 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@@ -196,6 +196,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockerinternal=True,origin_product="support_reply",mcp_builtin_agent_key="support",+ mcp_credential_owner_id=17,)task_queryset = mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Task.objects.select_related"@@ -244,6 +245,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockerallowed_installation_ids=None,origin_product="support_reply",task_agent_key="support",+ credential_owner_id=17,)sandbox.start_agent_server.assert_called_once()assert sandbox.start_agent_server.call_args.kwargs["event_ingest_token"] == "event-ingest-token"@@ -267,6 +269,7 @@ async def test_start_agent_server_forwards_imported_and_relayed_mcp_servers(mockinternal=False,origin_product="user_created",mcp_builtin_agent_key=None,+ mcp_credential_owner_id=None,)mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.create_oauth_access_token_for_run",@@ -323,6 +326,7 @@ async def test_start_agent_server_passes_initial_permission_mode(mocker) -> Noneinternal=False,origin_product="user_created",mcp_builtin_agent_key=None,+ mcp_credential_owner_id=None,)mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.create_oauth_access_token_for_run",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.pyindex 746d2d5b8ee3..f73bdf5016b7 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@@ -55,6 +55,7 @@ def _make_task_run_mock(team_id: int = 7, created_by_id: int | None = 42, state:task.internal = Falsetask.origin_product = "user_created"task.mcp_builtin_agent_key = None+ task.mcp_credential_owner_id = Noneif created_by_id is not None:task.created_by = MagicMock(id=created_by_id, distinct_id=f"user-{created_by_id}")else:@@ -101,6 +102,7 @@ class TestRefreshSandboxMcp:task_run.task.internal = Truetask_run.task.origin_product = "support_reply"task_run.task.mcp_builtin_agent_key = "support"+ task_run.task.mcp_credential_owner_id = 99_refresh(task_run, auth_token="jwt")mock_oauth.assert_called_once_with(task_run.task, task_run.state, scopes="read_only")@@ -116,6 +118,7 @@ class TestRefreshSandboxMcp:allowed_installation_ids=None,origin_product="support_reply",task_agent_key="support",+ credential_owner_id=99,)mock_send_refresh.assert_called_once()_, kwargs = mock_send_refresh.call_argsdiff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 970c81974359..b21b03f3bc76 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -336,6 +336,7 @@ class TestFetchUserMcpServerConfigs(TestCase):TOKEN = "phx_test_token"TEAM_ID = 42USER_ID = 7+ CREDENTIAL_OWNER_ID = 99API_BASE = "https://us.posthog.com"MOCK_FACADE = "products.tasks.backend.temporal.process_task.utils.get_installations_for_sandbox"@@ -371,6 +372,7 @@ class TestFetchUserMcpServerConfigs(TestCase):include_personal=True,task_origin=None,task_agent_key=None,+ credential_owner_id=None,)assert configs == [McpServerConfig(@@ -462,14 +464,18 @@ class TestFetchUserMcpServerConfigs(TestCase):self.USER_ID,origin_product="support_reply",task_agent_key="support",+ credential_owner_id=self.CREDENTIAL_OWNER_ID,)+ # 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.mock_facade.assert_called_once_with(self.TEAM_ID,user_id=self.USER_ID,include_personal=True,task_origin="support_reply",task_agent_key="support",+ credential_owner_id=self.CREDENTIAL_OWNER_ID,)assert configs == [McpServerConfig(@@ -499,6 +505,7 @@ class TestFetchUserMcpServerConfigs(TestCase):include_personal=include_personal,task_origin=None,task_agent_key=None,+ credential_owner_id=None,)@patch(MOCK_API_URL)diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex b62195adecaa..eea69cc49327 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -574,16 +574,16 @@ def get_user_mcp_server_configs(allowed_installation_ids: list[str] | None = None,origin_product: str | None = None,task_agent_key: str | None = None,+ credential_owner_id: int | None = None,) -> list[McpServerConfig]:"""Fetch MCP Store installations for sandbox use and return configs.Unmapped tasks include shared team installations. Built-in agent tasks only- include the connections granted to that agent by the person the run acts- for, and never include a member's personal installations. This path does- not resolve that person yet, so built-in agent tasks currently get no Store- installations. A mapped origin without its persisted agent marker gets no- Store installations. Built-in agent handling is- gated per team on the ``mcp-gateway`` rollout flag; teams without it+ include the connections ``credential_owner_id`` granted to that agent, and+ never include a member's personal installations. Grants are personal, so an+ agent task whose persisted owner is missing mounts nothing. A mapped origin+ without its persisted agent marker gets no Store installations. Built-in+ agent handling is gated per team on the ``mcp-gateway`` rollout flag; teams without itresolve mapped origins like unmapped tasks. For unmapped tasks,``include_personal`` includes the user's personal installations when a``user_id`` is provided.@@ -608,6 +608,7 @@ def get_user_mcp_server_configs(include_personal=include_personal,task_origin=origin_product,task_agent_key=task_agent_key,+ credential_owner_id=credential_owner_id,)if allowed_installation_ids is not None:allowed = {str(i) for i in allowed_installation_ids}diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.pyindex c06640e12a91..18848bf7c7e1 100644--- a/products/tasks/backend/temporal/tests/test_oauth.py+++ b/products/tasks/backend/temporal/tests/test_oauth.py@@ -137,6 +137,7 @@ def test_server_created_task_persists_trusted_mcp_agent_marker(organization = Organization.objects.create(name=f"agent-marker-{agent_key}")team = Team.objects.create(organization=organization, name="agent-marker-team")creator = User.objects.create(email=f"agent-marker-{agent_key}@example.com")+ owner = User.objects.create(email=f"agent-owner-{agent_key}@example.com")task = Task.create_without_run(team=team,@@ -145,10 +146,14 @@ def test_server_created_task_persists_trusted_mcp_agent_marker(origin_product=origin_product,user_id=creator.id,mcp_builtin_agent_key=agent_key,+ mcp_credential_owner_id=owner.id,)- assert task.state == {"mcp_builtin_agent_key": agent_key}+ assert task.state == {"mcp_builtin_agent_key": agent_key, "mcp_credential_owner_id": owner.id}assert task.mcp_builtin_agent_key == agent_key+ # The credential owner is its own value, not the task's creator: the run acts as `creator`+ # but may only mount `owner`'s MCP grants.+ assert task.mcp_credential_owner_id == owner.id@pytest.mark.django_db@@ -162,9 +167,24 @@ def test_reserved_origin_without_matching_server_marker_is_untrusted() -> None:title="Legacy",description="Untrusted origin",origin_product=Task.OriginProduct.SUPPORT_REPLY,+ state={"mcp_credential_owner_id": creator.id},)assert legacy_task.mcp_builtin_agent_key is None+ # An owner id without the server-stamped agent marker resolves to nothing, so an+ # untrusted task can never borrow that person's grants.+ assert legacy_task.mcp_credential_owner_id is None++ unstamped = Task.create_without_run(+ team=team,+ title="Unstamped",+ description="No agent marker",+ origin_product=Task.OriginProduct.USER_CREATED,+ user_id=creator.id,+ mcp_credential_owner_id=creator.id,+ )+ assert unstamped.state == {}+ assert unstamped.mcp_credential_owner_id is Nonewith pytest.raises(ValueError, match="does not match task origin"):Task.create_without_run(