: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(desktop/mcp-gateway): grant scope toggle and member audit log (#83211)
Chris Volzerab8c46e6bf34
diff --git a/products/desktop/packages/api-client/src/mcp-gateway.ts b/products/desktop/packages/api-client/src/mcp-gateway.tsindex fa6037b27ddb..64bfdbb4cd16 100644--- a/products/desktop/packages/api-client/src/mcp-gateway.ts+++ b/products/desktop/packages/api-client/src/mcp-gateway.ts@@ -9,6 +9,11 @@ import type { McpApprovalState, McpAuthType, McpCategory } from "./types";export type McpGatewayUser = Schemas.UserBasic;export type McpGatewayScopeType = "team" | "member" | "agent";+/**+ * How far an agent grant reaches: "personal" backs only the sharer's own+ * runs, "team" backs every run of the agent in the project.+ */+export type McpAgentGrantScope = "personal" | "team";export type McpServiceAccountStatus = "active" | "paused";export type McpAuditDecision = "auto" | "approved" | "pending" | "blocked";export type McpAuditQuickFilter = "all" | "agents" | "approvals" | "blocked";@@ -39,9 +44,15 @@ export interface McpGatewayYourConnection {last_used_at: string | null;}-/** One agent's access to a gateway server. */+/**+ * One agent's access to a gateway server, on behalf of one member. A server+ * can carry several rows for the same agent when multiple members share it.+ */export interface McpGatewayAgentAccess {service_account_id: string;+ /** The member whose connection the agent uses. */+ user: McpGatewayUser;+ scope: McpAgentGrantScope;name: string;/** Agent identity handle, e.g. posthog-support. */handle: string;@@ -153,6 +164,13 @@ export interface McpAuditEvent {actor_service_account: McpAuditActorServiceAccount | null;/** Denormalized actor label (email or handle) that survives deletion. */actor_label: string;+ /**+ * Member whose connection an agent call used. Null for member calls and+ * for owners whose account has since been deleted.+ */+ credential_owner: McpGatewayUser | null;+ /** Scope of the agent grant the call used. Empty for member calls. */+ grant_scope: McpAgentGrantScope | "";}export interface McpAuditCounts {diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex 2d112ed22ad2..a218a8fef4c3 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -124,6 +124,7 @@ import {} from "./fetcher";import { createApiClient, type Schemas } from "./generated";import type {+ McpAgentGrantScope,McpAuditCounts,McpAuditEvent,McpAuditPage,@@ -5234,6 +5235,11 @@ export class PostHogAPIClient {options: {gateway_server_id: string;enabled: boolean;+ /**+ * Reach of the caller's own share. The server defaults an omitted+ * scope to "personal", so re-enabling without it resets a team share.+ */+ scope?: McpAgentGrantScope;/** Agent-scope tool policies to set alongside the grant. */policies?: McpToolPolicyEntry[];},diff --git a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.tsindex cb70f8594904..6f1d95662402 100644--- a/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts+++ b/products/desktop/packages/core/src/mcp-gateway/gatewayServers.ts@@ -1,4 +1,5 @@import type {+ McpAgentGrantScope,McpApprovalState,McpAuditDecision,McpGatewayScopeType,@@ -281,6 +282,27 @@ export const AUDIT_DECISION_LABELS: Record<McpAuditDecision, string> = {blocked: "Blocked",};+/** Audit-row attribution: whose connection an agent call used. */+export function credentialOwnerLabel(+ ownerName: string,+ grantScope: McpAgentGrantScope | "",+): string {+ return grantScope === "team"+ ? `via ${ownerName}'s connection (team share)`+ : `via ${ownerName}'s connection`;+}++/** Toast confirming a share of the caller's connection and how far it reaches. */+export function agentShareMessage(+ serverName: string,+ agentName: string,+ scope: McpAgentGrantScope,+): string {+ return scope === "team"+ ? `${serverName} shared with ${agentName}. Every ${agentName} run in this project can use your connection.`+ : `${serverName} shared with ${agentName}. Only your own ${agentName} runs use your connection.`;+}+// Mirrors the backend's destructive-tool heuristic; only used to seed the// per-tool defaults when sharing a server with an agent.const DESTRUCTIVE_TOOL_RE =diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/AgentScopeToggle.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/AgentScopeToggle.tsxnew file mode 100644index 000000000000..bc8afed147e6--- /dev/null+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/AgentScopeToggle.tsx@@ -0,0 +1,78 @@+import type { McpAgentGrantScope } from "@posthog/api-client/posthog-client";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@posthog/quill";++const OPTIONS: { id: McpAgentGrantScope; label: string; hint: string }[] = [+ {+ id: "personal",+ label: "Just my agents",+ hint: "The agent uses your connection only when it runs for you.",+ },+ {+ id: "team",+ label: "All team agents",+ hint: "The agent uses your connection for every run in this project, including runs nobody started. Teammates can't use the connection directly, but agents act through it on their runs too.",+ },+];++/**+ * Reach of the caller's own agent share: their runs only, or every run of+ * the agent in the project. Shown only on shares the caller owns.+ */+export function AgentScopeToggle({+ value,+ disabled,+ onChange,+}: {+ value: McpAgentGrantScope;+ disabled?: boolean;+ onChange: (scope: McpAgentGrantScope) => void;+}) {+ return (+ <TooltipProvider>+ <div+ role="radiogroup"+ aria-label="Which runs use your connection"+ className="inline-flex items-stretch overflow-hidden rounded-md border border-gray-5 bg-gray-2"+ >+ {OPTIONS.map((option, index) => {+ const active = value === option.id;+ return (+ <Tooltip key={option.id}>+ <TooltipTrigger+ render={+ // biome-ignore lint/a11y/useSemanticElements: segmented radio group needs custom button styling+ <button+ type="button"+ role="radio"+ aria-checked={active}+ disabled={disabled}+ onClick={() => {+ if (!active) onChange(option.id);+ }}+ className={`whitespace-nowrap px-2 py-1 text-xs transition-colors disabled:opacity-50 ${+ index > 0 ? "border-gray-5 border-l" : ""+ } ${+ active+ ? "bg-accent-4 font-medium text-accent-11"+ : "text-gray-11 hover:bg-gray-3"+ }`}+ >+ {option.label}+ </button>+ }+ />+ <TooltipContent className="max-w-[280px]">+ {option.hint}+ </TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ </TooltipProvider>+ );+}diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAgentDetail.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAgentDetail.tsxindex d108d3a1b600..b8b4f4dd734b 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAgentDetail.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAgentDetail.tsx@@ -1,14 +1,24 @@import { ArrowLeft, Clock, Sliders } from "@phosphor-icons/react";import type {+ McpAgentGrantScope,McpAuditEvent,+ McpGatewayAgentAccess,McpGatewayServer,} from "@posthog/api-client/posthog-client";import {AUDIT_DECISION_LABELS,+ agentShareMessage,+ credentialOwnerLabel,formatAgo,formatAuditTime,} from "@posthog/core/mcp-gateway/gatewayServers";-import { RobotAvatar } from "@posthog/ui/features/mcp-gateway/components/parts/avatars";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import { AgentScopeToggle } from "@posthog/ui/features/mcp-gateway/components/parts/AgentScopeToggle";+import {+ gatewayUserName,+ RobotAvatar,+} from "@posthog/ui/features/mcp-gateway/components/parts/avatars";import type { GatewayRoute } from "@posthog/ui/features/mcp-gateway/gatewayRoute";import { useAgentRecentCalls } from "@posthog/ui/features/mcp-gateway/hooks/useGatewayAudit";import { useGatewayServers } from "@posthog/ui/features/mcp-gateway/hooks/useGatewayServers";@@ -47,6 +57,8 @@ export function GatewayAgentDetail({const { servers, templatesById } = useGatewayServers();const { events, eventsLoading } = useAgentRecentCalls(accountId);const [shownCalls, setShownCalls] = useState(5);+ const apiClient = useOptionalAuthenticatedClient();+ const { data: currentUser } = useCurrentUser({ client: apiClient });const account = serviceAccounts.accounts.find((entry) => entry.id === accountId,@@ -75,13 +87,22 @@ export function GatewayAgentDetail({month: "long",year: "numeric",});+ // Several members can each share one server, so server_ids carries one+ // entry per share and needs deduping before counting.+ const sharedServerIds = new Set(account.server_ids);// Shared servers float to the top so the agent's actual reach reads first.const sharedServers = servers.filter((server) =>- account.server_ids.includes(server.id),+ sharedServerIds.has(server.id),);const otherServers = servers.filter(- (server) => !account.server_ids.includes(server.id),+ (server) => !sharedServerIds.has(server.id),);+ const yourShareFor = (server: McpGatewayServer) =>+ server.agents.find(+ (agent) =>+ agent.service_account_id === accountId &&+ agent.user.id === currentUser?.id,+ ) ?? null;return (<Flex direction="column" gap="4" className="min-w-0">@@ -144,7 +165,7 @@ export function GatewayAgentDetail({<Flex align="center" gap="2"><Text className="font-medium text-base">Shared servers</Text><Badge color="gray" variant="soft" size="1">- {account.server_ids.length} of {servers.length}+ {sharedServerIds.size} of {servers.length}</Badge></Flex><div className="overflow-hidden rounded border border-gray-5">@@ -154,6 +175,8 @@ export function GatewayAgentDetail({server={server}account={account}shared+ yourShare={yourShareFor(server)}+ accessPending={serviceAccounts.setAccessPending}iconDomain={server.template_id? templatesById.get(server.template_id)?.icon_domain@@ -179,6 +202,8 @@ export function GatewayAgentDetail({server={server}account={account}shared={false}+ yourShare={null}+ accessPending={serviceAccounts.setAccessPending}iconDomain={server.template_id? templatesById.get(server.template_id)?.icon_domain@@ -234,13 +259,23 @@ export function GatewayAgentDetail({<Text color="gray" className="text-xs tabular-nums">{formatAuditTime(event.created_at)}</Text>- <Flex align="baseline" gap="2" className="min-w-0">- <Text truncate className="font-medium text-xs">- {event.server_name}- </Text>- <Text color="gray" truncate className="text-xs">- {event.tool_name}()- </Text>+ <Flex direction="column" className="min-w-0">+ <Flex align="baseline" gap="2" className="min-w-0">+ <Text truncate className="font-medium text-xs">+ {event.server_name}+ </Text>+ <Text color="gray" truncate className="text-xs">+ {event.tool_name}()+ </Text>+ </Flex>+ {event.credential_owner && (+ <Text color="gray" truncate className="text-[11px]">+ {credentialOwnerLabel(+ gatewayUserName(event.credential_owner),+ event.grant_scope,+ )}+ </Text>+ )}</Flex><Badgecolor={DECISION_COLORS[event.decision]}@@ -274,6 +309,8 @@ function ServerAccessRow({server,account,shared,+ yourShare,+ accessPending,iconDomain,onNavigate,onSetAccess,@@ -281,15 +318,24 @@ function ServerAccessRow({server: McpGatewayServer;account: { id: string; name: string };shared: boolean;+ /** The caller's own share of this server with the agent, when one exists. */+ yourShare: McpGatewayAgentAccess | null;+ accessPending: boolean;iconDomain: string | undefined;onNavigate: (route: GatewayRoute) => void;onSetAccess: (vars: {accountId: string;serverId: string;enabled: boolean;+ scope?: McpAgentGrantScope;successMessage?: string;}) => void;}) {+ const sharedByOthers = server.agents.filter(+ (agent) =>+ agent.service_account_id === account.id &&+ agent.user.id !== yourShare?.user.id,+ );return (<Flexalign="center"@@ -301,9 +347,13 @@ function ServerAccessRow({<Text truncate className="font-medium text-sm">{server.name}</Text>- <Text color="gray" className="text-xs">+ <Text color="gray" truncate className="text-xs">{server.tool_count} tools{shared ? " available to this agent" : ""}+ {sharedByOthers.length > 0 &&+ ` · shared by ${sharedByOthers+ .map((agent) => gatewayUserName(agent.user))+ .join(", ")}`}</Text></Flex>{shared && (@@ -326,17 +376,39 @@ function ServerAccessRow({<Sliders size={11} /> Tool policies</Button>)}+ {yourShare && (+ <AgentScopeToggle+ value={yourShare.scope}+ disabled={accessPending}+ onChange={(scope) =>+ onSetAccess({+ accountId: account.id,+ serverId: server.id,+ enabled: true,+ scope,+ successMessage: agentShareMessage(+ server.name,+ account.name,+ scope,+ ),+ })+ }+ />+ )}+ {/* The mutation only creates or removes the caller's own share, so the+ switch tracks that share, not a teammate's. */}<Switchsize="1"- checked={shared}+ checked={!!yourShare}onCheckedChange={(enabled) =>onSetAccess({accountId: account.id,serverId: server.id,enabled,+ ...(enabled ? { scope: "personal" as const } : {}),successMessage: enabled- ? `${account.name} can now use ${server.name}`- : `${account.name} no longer has access to ${server.name}`,+ ? agentShareMessage(server.name, account.name, "personal")+ : `${account.name} no longer has access to your ${server.name} connection`,})}/>diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAuditLog.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAuditLog.tsxindex 8cac031ff642..1c0c0fc79956 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAuditLog.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayAuditLog.tsx@@ -4,6 +4,7 @@ import type {} from "@posthog/api-client/posthog-client";import {AUDIT_DECISION_LABELS,+ credentialOwnerLabel,formatAuditTime,} from "@posthog/core/mcp-gateway/gatewayServers";import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";@@ -15,6 +16,7 @@ import {AUDIT_PAGE_SIZE,useGatewayAudit,} from "@posthog/ui/features/mcp-gateway/hooks/useGatewayAudit";+import { useGatewayConfig } from "@posthog/ui/features/mcp-gateway/hooks/useGatewayConfig";import { useServiceAccounts } from "@posthog/ui/features/mcp-gateway/hooks/useServiceAccounts";import {Badge,@@ -44,12 +46,18 @@ const DECISION_COLORS: Record<blocked: "red",};-/** Every tool call routed through the gateway, with how it was decided. */+/**+ * Tool calls routed through the gateway, with how each was decided. Admins+ * see every call in the project; members see calls made through their own+ * connections, including agent calls that used a connection they shared.+ * The backend scopes the rows, so this view renders whatever it may see.+ */export function GatewayAuditLog() {const [quickFilter, setQuickFilter] = useState<McpAuditQuickFilter>("all");const [agentFilter, setAgentFilter] = useState<string>("all");const [page, setPage] = useState(0);+ const { isAdmin } = useGatewayConfig();const { accounts } = useServiceAccounts();const { events, totalCount, auditLoading, counts } = useGatewayAudit({quickFilter,@@ -71,9 +79,9 @@ export function GatewayAuditLog() {<Flex direction="column" gap="1"><Heading className="font-bold text-2xl">Audit log</Heading><Text color="gray" className="max-w-[620px] text-sm">- Every tool call routed through the gateway — each row is one call to a- tool on one of your team's MCP servers, and how the gateway decided- it.+ {isAdmin+ ? "Every tool call routed through the gateway. Each row is one call to a tool on one of your team's MCP servers, and how the gateway decided it."+ : "Tool calls made through your MCP server connections, including calls from agents you shared them with, and how the gateway decided each one."}</Text></Flex>@@ -252,27 +260,37 @@ function AuditRow({ event }: { event: McpAuditEvent }) {<Text color="gray" className="text-xs tabular-nums">{formatAuditTime(event.created_at)}</Text>- <Flex align="center" gap="2" className="min-w-0">- {agent ? (- <RobotAvatar size="sm" />- ) : user ? (- <UserAvatar user={user} size="xs" />- ) : null}- <Text truncate className="text-xs">- {agent- ? agent.name- : user- ? gatewayUserName(user)- : event.actor_label}- </Text>- <Badge- color={agent ? "indigo" : "gray"}- variant="soft"- size="1"- className="uppercase"- >- {agent ? "agent" : user ? "human" : "deleted"}- </Badge>+ <Flex direction="column" className="min-w-0">+ <Flex align="center" gap="2" className="min-w-0">+ {agent ? (+ <RobotAvatar size="sm" />+ ) : user ? (+ <UserAvatar user={user} size="xs" />+ ) : null}+ <Text truncate className="text-xs">+ {agent+ ? agent.name+ : user+ ? gatewayUserName(user)+ : event.actor_label}+ </Text>+ <Badge+ color={agent ? "indigo" : "gray"}+ variant="soft"+ size="1"+ className="uppercase"+ >+ {agent ? "agent" : user ? "human" : "deleted"}+ </Badge>+ </Flex>+ {event.credential_owner && (+ <Text color="gray" truncate className="text-[11px]">+ {credentialOwnerLabel(+ gatewayUserName(event.credential_owner),+ event.grant_scope,+ )}+ </Text>+ )}</Flex><Flex align="baseline" gap="2" className="min-w-0"><Text truncate className="font-medium text-xs">diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.test.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.test.tsxindex ae8719551da9..6493ad8c54e5 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.test.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.test.tsx@@ -49,6 +49,16 @@ function renderRail(servers: McpGatewayServer[]) {}describe("GatewayRail", () => {+ // The audit log is member-visible (the backend scopes its rows); the other+ // manage views stay admin-only.+ it("offers a member the audit log but not the admin views", () => {+ renderRail([]);++ expect(screen.getByText("Audit log")).toBeInTheDocument();+ expect(screen.queryByText("Team & agents")).not.toBeInTheDocument();+ expect(screen.queryByText("Team settings")).not.toBeInTheDocument();+ });+it("lists a server the caller has connected", () => {renderRail([server({diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.tsxindex 6172779335b4..6426d729862d 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayRail.tsx@@ -168,14 +168,12 @@ export function GatewayRail({onClick={() => onNavigate({ view: "settings" })}/>)}- {isAdmin && (- <RailLink- icon={Rows}- label="Audit log"- active={route.view === "audit"}- onClick={() => onNavigate({ view: "audit" })}- />- )}+ <RailLink+ icon={Rows}+ label="Audit log"+ active={route.view === "audit"}+ onClick={() => onNavigate({ view: "audit" })}+ /></Flex></ScrollArea></aside>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 9b88818bc809..d425079238c3 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@@ -7,6 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({gateway: {} as Record<string, unknown>,setMemberAccess: vi.fn(),+ setAgentAccess: vi.fn(),currentUser: null as { id: number } | null,refresh: vi.fn(),}));@@ -50,7 +51,7 @@ vi.mock("@posthog/ui/features/mcp-gateway/hooks/useServiceAccounts", () => ({useServiceAccounts: () => ({accounts: [],accountsLoading: false,- setAccess: vi.fn(),+ setAccess: mocks.setAgentAccess,setAccessPending: false,}),}));@@ -196,6 +197,15 @@ describe("GatewayServerDetail", () => {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",@@ -228,6 +238,76 @@ describe("GatewayServerDetail", () => {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 };+ const yourShare = {+ 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,+ };+ const teammateShare = {+ ...yourShare,+ user: {+ ...yourShare.user,+ id: 8,+ uuid: "user-8",+ first_name: "Grace",+ last_name: "Hopper",+ email: "[email protected]",+ },+ scope: "team",+ };+ mocks.gateway.servers = [+ { ...server, agents: [yourShare, teammateShare] } as McpGatewayServer,+ ];++ const user = userEvent.setup();+ render(+ <Theme>+ <GatewayServerDetail+ serverId={server.id}+ isAdmin={false}+ canManageAgentAccess+ onNavigate={vi.fn()}+ />+ </Theme>,+ );++ // The teammate's team share is attributed but not editable, so exactly+ // one toggle renders: the caller's own.+ expect(+ screen.getAllByRole("radiogroup", {+ name: "Which runs use your connection",+ }),+ ).toHaveLength(1);+ expect(+ screen.getByText(/shared to the team by Grace Hopper/),+ ).toBeInTheDocument();++ await user.click(screen.getByRole("radio", { name: "All team agents" }));++ expect(mocks.setAgentAccess).toHaveBeenCalledWith({+ accountId: "sa-1",+ serverId: server.id,+ enabled: true,+ scope: "team",+ successMessage:+ "Linear shared with Deploy bot. Every Deploy bot run in this project can use your connection.",+ });+ });+it("collects credentials before connecting a custom server", async () => {const user = userEvent.setup();render(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 935a8b0d13cf..be518d9e03ec 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@@ -15,6 +15,7 @@ import {X,} from "@phosphor-icons/react";import type {+ McpAgentGrantScope,McpApprovalState,McpGatewayServer,} from "@posthog/api-client/posthog-client";@@ -24,6 +25,7 @@ import {gatewayConnectNeedsCredentials,} from "@posthog/core/mcp-gateway/gatewayConnect";import {+ agentShareMessage,countPoliciesByState,formatAgo,getGatewayServerRemovalAction,@@ -32,6 +34,7 @@ import { usableInstallationId } from "@posthog/core/mcp-gateway/gatewayToolDiscoimport { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";+import { AgentScopeToggle } from "@posthog/ui/features/mcp-gateway/components/parts/AgentScopeToggle";import {gatewayUserName,RobotAvatar,@@ -143,7 +146,12 @@ export function GatewayServerDetail({list.push(initialScope);}if (canManageAgentAccess) {+ // One chip per agent: an agent shared by several members carries one+ // access row per sharer, but its tool policy is a single agent scope.+ const seenAgentIds = new Set<string>();for (const agent of server.agents) {+ if (seenAgentIds.has(agent.service_account_id)) continue;+ seenAgentIds.add(agent.service_account_id);list.push({scopeType: "agent",scopeServiceAccountId: agent.service_account_id,@@ -401,6 +409,8 @@ export function GatewayServerDetail({server={server}gateway={gateway}isAdmin={isAdmin}+ currentUserId={currentUser?.id ?? null}+ accessPending={serviceAccounts.setAccessPending}onShareWithAgent={() => setGiveAccessOpen(true)}onSetMemberAccess={(userId, name, enabled) =>members.setMemberAccess({@@ -412,12 +422,21 @@ export function GatewayServerDetail({: `${name} can no longer use ${server.name}`,})}+ onSetAgentScope={(accountId, name, scope) =>+ serviceAccounts.setAccess({+ accountId,+ serverId: server.id,+ enabled: true,+ scope,+ successMessage: agentShareMessage(server.name, name, scope),+ })+ }onRevokeAgent={(accountId, name) =>serviceAccounts.setAccess({accountId,serverId: server.id,enabled: false,- successMessage: `${name} no longer has access to ${server.name}`,+ successMessage: `${name} no longer has access to your ${server.name} connection`,})}/>@@ -615,10 +634,11 @@ export function GatewayServerDetail({open={giveAccessOpen}server={server}accounts={serviceAccounts.accounts}+ currentUserId={currentUser?.id ?? null}toolPolicies={teamTools.policies}pending={serviceAccounts.setAccessPending}onClose={() => setGiveAccessOpen(false)}- onGrant={(accountId, policies) => {+ onGrant={(accountId, policies, scope) => {const account = serviceAccounts.accounts.find((entry) => entry.id === accountId,);@@ -627,8 +647,13 @@ export function GatewayServerDetail({accountId,serverId: server.id,enabled: true,+ scope,policies,- successMessage: `${account?.name ?? "Agent"} can now use ${server.name}`,+ successMessage: agentShareMessage(+ server.name,+ account?.name ?? "agent",+ scope,+ ),},{ onSuccess: () => setGiveAccessOpen(false) },);@@ -785,12 +810,20 @@ interface AccessSectionProps {server: McpGatewayServer;gateway: ReturnType<typeof useGatewayServers>;isAdmin: boolean;+ currentUserId: number | null;+ /** True while any agent-access mutation is in flight. */+ accessPending: boolean;onShareWithAgent: () => void;onSetMemberAccess: (userId: number,firstName: string,enabled: boolean,) => void;+ onSetAgentScope: (+ accountId: string,+ name: string,+ scope: McpAgentGrantScope,+ ) => void;onRevokeAgent: (accountId: string, name: string) => void;}@@ -798,8 +831,11 @@ function AccessSection({server,gateway,isAdmin,+ currentUserId,+ accessPending,onShareWithAgent,onSetMemberAccess,+ onSetAgentScope,onRevokeAgent,}: AccessSectionProps) {const yourInstallationId = server.your_connection?.installation_id;@@ -981,54 +1017,75 @@ function AccessSection({</Text>) : (<div className="rounded-md border border-gray-5 bg-gray-2">- {server.agents.map((agent) => (- <Flex- key={agent.service_account_id}- align="center"- gap="3"- className="group border-gray-5 border-b px-3 py-2 last:border-b-0"- >- <RobotAvatar />- <Flex direction="column" className="min-w-0 flex-1">- <Text truncate className="font-medium text-sm">- {agent.name}- </Text>- <Text color="gray" truncate className="text-xs">- <span className="font-mono">{agent.handle}</span>- {agent.granted_by- ? ` · shared by ${gatewayUserName(agent.granted_by)}`- : " · shared with this agent"}- </Text>- </Flex>- <Button- variant="ghost"- color="red"- size="1"- className="opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100"- onClick={() =>- onRevokeAgent(agent.service_account_id, agent.name)- }+ {server.agents.map((agent) => {+ const isYourShare = agent.user.id === currentUserId;+ const teamShared = agent.scope === "team";+ return (+ <Flex+ key={`${agent.service_account_id}:${agent.user.id}`}+ align="center"+ gap="3"+ className="group border-gray-5 border-b px-3 py-2 last:border-b-0">- <X size={11} /> Revoke- </Button>- <Flex align="center" gap="2" className="shrink-0">- <span- className={`h-[6px] w-[6px] rounded-full ${- agent.status === "active" ? "bg-(--green-9)" : "bg-gray-8"- }`}- />- <Text color="gray" className="text-xs">- {agent.status === "active"- ? `Active${- formatAgo(agent.last_active_at)- ? ` ${formatAgo(agent.last_active_at)}`- : ""- }`- : "Paused"}- </Text>+ <RobotAvatar />+ <Flex direction="column" className="min-w-0 flex-1">+ <Text truncate className="font-medium text-sm">+ {agent.name}+ </Text>+ <Text color="gray" truncate className="text-xs">+ <span className="font-mono">{agent.handle}</span>+ {` · shared ${teamShared ? "to the team " : ""}by ${+ isYourShare ? "you" : gatewayUserName(agent.user)+ }`}+ </Text>+ </Flex>+ {isYourShare && (+ <AgentScopeToggle+ value={agent.scope}+ disabled={accessPending}+ onChange={(scope) =>+ onSetAgentScope(+ agent.service_account_id,+ agent.name,+ scope,+ )+ }+ />+ )}+ {/* Revoking removes only the caller's own share, so it is+ offered only on rows backed by the caller's connection. */}+ {isYourShare && (+ <Button+ variant="ghost"+ color="red"+ size="1"+ className="opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100"+ onClick={() =>+ onRevokeAgent(agent.service_account_id, agent.name)+ }+ >+ <X size={11} /> Revoke+ </Button>+ )}+ <Flex align="center" gap="2" className="shrink-0">+ <span+ className={`h-[6px] w-[6px] rounded-full ${+ agent.status === "active" ? "bg-(--green-9)" : "bg-gray-8"+ }`}+ />+ <Text color="gray" className="text-xs">+ {agent.status === "active"+ ? `Active${+ formatAgo(agent.last_active_at)+ ? ` ${formatAgo(agent.last_active_at)}`+ : ""+ }`+ : "Paused"}+ </Text>+ </Flex></Flex>- </Flex>- ))}+ );+ })}</div>)}</Flex>diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayTeamView.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayTeamView.tsxindex aa42a3e415c2..03eeed2e3331 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayTeamView.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GatewayTeamView.tsx@@ -170,8 +170,10 @@ function AgentCard({onToggleStatus: (paused: boolean) => void;}) {const active = account.status === "active";+ // server_ids carries one entry per member's share, so dedupe before counting.+ const sharedServerIds = new Set(account.server_ids);const toolCount = servers- .filter((server) => account.server_ids.includes(server.id))+ .filter((server) => sharedServerIds.has(server.id)).reduce((total, server) => total + server.tool_count, 0);return (@@ -187,8 +189,8 @@ function AgentCard({{account.name}</Text><Text color="gray" className="text-xs">- {account.server_ids.length} server- {account.server_ids.length === 1 ? "" : "s"} · {toolCount} tools+ {sharedServerIds.size} server+ {sharedServerIds.size === 1 ? "" : "s"} · {toolCount} tools</Text></Flex></button>diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.test.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.test.tsxindex 117de6095ced..955c5373542e 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.test.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.test.tsx@@ -65,6 +65,26 @@ const secondAccount: McpServiceAccount = {handle: "posthog-docs",};+function agentShare(accountId: string, userId: number) {+ return {+ service_account_id: accountId,+ user: {+ id: userId,+ uuid: `user-${userId}`,+ first_name: "",+ last_name: "",+ email: `user-${userId}@example.com`,+ hedgehog_config: null,+ },+ scope: "personal",+ name: "Agent",+ handle: "agent",+ status: "active",+ last_active_at: null,+ granted_by: null,+ } as McpGatewayServer["agents"][number];+}+describe("GiveAccessDialog", () => {it("only offers allow or block when configuring an agent", async () => {const user = userEvent.setup();@@ -74,6 +94,7 @@ describe("GiveAccessDialog", () => {openserver={server}accounts={[account]}+ currentUserId={7}toolPolicies={[toolPolicy]}pending={false}onClose={vi.fn()}@@ -102,6 +123,7 @@ describe("GiveAccessDialog", () => {openserver={server}accounts={[account]}+ currentUserId={7}toolPolicies={[toolPolicy]}pending={false}onClose={vi.fn()}@@ -122,6 +144,7 @@ describe("GiveAccessDialog", () => {open={open}server={server}accounts={[account]}+ currentUserId={7}toolPolicies={[toolPolicy]}pending={false}onClose={vi.fn()}@@ -150,6 +173,7 @@ describe("GiveAccessDialog", () => {openserver={server}accounts={[account, secondAccount]}+ currentUserId={7}toolPolicies={[toolPolicy]}pending={false}onClose={vi.fn()}@@ -168,9 +192,77 @@ describe("GiveAccessDialog", () => {expect(screen.getByRole("radio", { name: "Blocked" })).not.toBeChecked();await user.click(screen.getByRole("button", { name: "Share access" }));- expect(onGrant).toHaveBeenCalledWith("agent-2", [- { tool_name: "search_pages", policy_state: "approved" },- ]);+ expect(onGrant).toHaveBeenCalledWith(+ "agent-2",+ [{ tool_name: "search_pages", policy_state: "approved" }],+ "personal",+ );+ });++ it("passes the chosen team scope through the grant", async () => {+ const user = userEvent.setup();+ const onGrant = vi.fn();+ render(+ <Theme>+ <GiveAccessDialog+ open+ server={server}+ accounts={[account]}+ currentUserId={7}+ toolPolicies={[toolPolicy]}+ pending={false}+ onClose={vi.fn()}+ onGrant={onGrant}+ />+ </Theme>,+ );++ screen.getByRole("combobox").focus();+ await user.keyboard("{ArrowDown}{Enter}");+ await user.click(screen.getByRole("radio", { name: "All team agents" }));+ await user.click(screen.getByRole("button", { name: "Share access" }));++ expect(onGrant).toHaveBeenCalledWith(+ "agent-1",+ [{ tool_name: "search_pages", policy_state: "approved" }],+ "team",+ );+ });++ // Several members may back the same agent side by side, so a teammate's+ // share must not remove the agent from the caller's picker.+ it("filters out only the agents the caller already shared with", async () => {+ const user = userEvent.setup();+ const onGrant = vi.fn();+ render(+ <Theme>+ <GiveAccessDialog+ open+ server={{+ ...server,+ agents: [agentShare("agent-1", 7), agentShare("agent-2", 8)],+ }}+ accounts={[account, secondAccount]}+ currentUserId={7}+ toolPolicies={[toolPolicy]}+ pending={false}+ onClose={vi.fn()}+ onGrant={onGrant}+ />+ </Theme>,+ );++ // agent-1 is already backed by the caller, so the first offered agent is+ // agent-2 even though a teammate already shared it.+ screen.getByRole("combobox").focus();+ await user.keyboard("{ArrowDown}{Enter}");+ await user.click(screen.getByRole("button", { name: "Share access" }));++ expect(onGrant).toHaveBeenCalledWith(+ "agent-2",+ [{ tool_name: "search_pages", policy_state: "approved" }],+ "personal",+ );});it("shows a spinner and prevents closing while access is being shared", () => {@@ -181,6 +273,7 @@ describe("GiveAccessDialog", () => {openserver={server}accounts={[account]}+ currentUserId={7}toolPolicies={[]}pendingonClose={onClose}diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.tsxindex 0b57ddf96775..772df95c43b5 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/components/parts/GiveAccessDialog.tsx@@ -1,5 +1,6 @@import { Check, Prohibit } from "@phosphor-icons/react";import type {+ McpAgentGrantScope,McpGatewayServer,McpResolvedToolPolicy,McpServiceAccount,@@ -11,6 +12,7 @@ import {defaultAgentGrantPolicy,isAgentPolicyState,} from "@posthog/core/mcp-gateway/gatewayServers";+import { AgentScopeToggle } from "@posthog/ui/features/mcp-gateway/components/parts/AgentScopeToggle";import { RobotAvatar } from "@posthog/ui/features/mcp-gateway/components/parts/avatars";import { ToolPolicyToggle } from "@posthog/ui/features/mcp-servers/components/parts/ToolPolicyToggle";import {@@ -28,13 +30,18 @@ import { useMemo, useState } from "react";interface GiveAccessDialogProps {open: boolean;server: McpGatewayServer;- /** Every service account; ones that already have access are filtered out. */+ /** Every service account; ones the caller already shared with are filtered out. */accounts: McpServiceAccount[];+ currentUserId: number | null;/** Team-scope rows, used for tool names and rule locks. */toolPolicies: McpResolvedToolPolicy[];pending: boolean;onClose: () => void;- onGrant: (accountId: string, policies: McpToolPolicyEntry[]) => void;+ onGrant: (+ accountId: string,+ policies: McpToolPolicyEntry[],+ scope: McpAgentGrantScope,+ ) => void;}/** "Share <server> with an agent" — agent picker plus per-tool starting policies. */@@ -48,12 +55,14 @@ function GiveAccessDialogDraft({open,server,accounts,+ currentUserId,toolPolicies,pending,onClose,onGrant,}: GiveAccessDialogProps) {const [selectedId, setSelectedId] = useState<string | null>(null);+ const [scope, setScope] = useState<McpAgentGrantScope>("personal");const [policyMap, setPolicyMap] = useState<Record<string, AgentPolicyState>>({},);@@ -63,12 +72,17 @@ function GiveAccessDialogDraft({setPolicyMap({});};+ // A teammate's share doesn't block the caller's own — several members may+ // each back the same agent, so only agents the caller already shared with+ // drop out of the picker.const available = useMemo(() => {- const withAccess = new Set(- server.agents.map((agent) => agent.service_account_id),+ const sharedByYou = new Set(+ server.agents+ .filter((agent) => agent.user.id === currentUserId)+ .map((agent) => agent.service_account_id),);- return accounts.filter((account) => !withAccess.has(account.id));- }, [accounts, server.agents]);+ return accounts.filter((account) => !sharedByYou.has(account.id));+ }, [accounts, server.agents, currentUserId]);const selected = available.find((account) => account.id === selectedId);@@ -95,7 +109,7 @@ function GiveAccessDialogDraft({tool_name: policy.tool_name,policy_state: policyFor(policy.tool_name),}));- onGrant(selected.id, policies);+ onGrant(selected.id, policies, scope);};return (@@ -129,12 +143,25 @@ function GiveAccessDialogDraft({))}{available.length === 0 && (<Text color="gray" className="block px-3 py-2 text-sm italic">- Every agent already has access to {server.name}.+ You've already shared {server.name} with every agent.</Text>)}</Select.Content></Select.Root>+ {selected && (+ <Flex align="center" justify="between" gap="3">+ <Text color="gray" className="text-[13px]">+ Applies to+ </Text>+ <AgentScopeToggle+ value={scope}+ disabled={pending}+ onChange={setScope}+ />+ </Flex>+ )}+{selected && (<Flex direction="column" gap="2"><Flex align="center" justify="between">diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.test.ts b/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.test.tsnew file mode 100644index 000000000000..e43dd7c318c4--- /dev/null+++ b/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { type GatewayRoute, isRouteAllowed } from "./gatewayRoute";++describe("isRouteAllowed", () => {+ // The route guard is what actually keeps a member on or off a view, since+ // the rail only hides links. Audit must stay member-reachable; the admin+ // views must not become so.+ it.each([+ [{ view: "servers" }, true],+ [{ view: "audit" }, true],+ [{ view: "team" }, false],+ [{ view: "agent", accountId: "sa-1" }, false],+ [{ view: "member", userId: 1 }, false],+ [{ view: "settings" }, false],+ ] as [GatewayRoute, boolean][])(+ "member access to %o is %s",+ (route, allowed) => {+ expect(+ isRouteAllowed(route, { isAdmin: false, canAddServers: false }),+ ).toBe(allowed);+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.ts b/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.tsindex d630bd36cd1e..55f2955582c1 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.ts+++ b/products/desktop/packages/ui/src/features/mcp-gateway/gatewayRoute.ts@@ -11,12 +11,13 @@ export type GatewayRoute =| { view: "settings" }| { view: "audit" };+// The audit log is open to every member: the backend scopes it to calls made+// through the caller's own connections unless they administer the gateway.const ADMIN_ONLY_VIEWS: GatewayRoute["view"][] = ["team","agent","member","settings",- "audit",];/** Keep the route inside what the caller's role may see. */diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.test.tsx b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.test.tsxindex 5678d4742f5e..e22bad32dfc9 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.test.tsx+++ b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.test.tsx@@ -1,5 +1,6 @@import type {McpGatewayServer,+ McpGatewayUser,McpServiceAccount,} from "@posthog/api-client/posthog-client";import { gatewayKeys } from "@posthog/ui/features/mcp-gateway/hooks/gatewayKeys";@@ -59,18 +60,43 @@ const account = {updated_at: "2026-07-23T12:00:00Z",} satisfies McpServiceAccount;+const you = {+ id: 7,+ uuid: "user-uuid-7",+ distinct_id: "distinct-7",+ first_name: "Ada",+ last_name: "Lovelace",+ email: "[email protected]",+ is_email_verified: true,+ hedgehog_config: null,+} as McpGatewayUser;++const teammate = {+ ...you,+ id: 8,+ uuid: "user-uuid-8",+ distinct_id: "distinct-8",+ first_name: "Grace",+ last_name: "Hopper",+ email: "[email protected]",+} as McpGatewayUser;++function agentShare(user: McpGatewayUser, scope: "personal" | "team") {+ return {+ service_account_id: account.id,+ user,+ scope,+ name: account.name,+ handle: account.handle,+ status: account.status,+ last_active_at: account.last_active_at,+ granted_by: user,+ };+}+const server = {id: "server-1",- agents: [- {- service_account_id: account.id,- name: account.name,- handle: account.handle,- status: account.status,- last_active_at: account.last_active_at,- granted_by: null,- },- ],+ agents: [agentShare(you, "personal")],} as McpGatewayServer;let queryClient: QueryClient;@@ -120,11 +146,74 @@ describe("useServiceAccounts", () => {);});- it("stamps the current user as grantor on a fresh grant without a refetch", async () => {+ // An omitted scope makes the server reset an existing team share back to+ // personal, so the request must always carry it explicitly on enable.+ it.each([+ [undefined, "personal"],+ ["team", "team"],+ ] as const)(+ "sends scope %s as %s and stamps the caller's share on a fresh grant",+ async (scope, expectedScope) => {+ queryClient.setQueryData(gatewayKeys.servers, [+ { ...server, agents: [] } as McpGatewayServer,+ ]);+ mocks.setAccess.mockResolvedValue({+ ...account,+ server_ids: [server.id],+ });+ const { result } = renderHook(() => useServiceAccounts(), { wrapper });++ await waitFor(() => expect(result.current.accounts).toEqual([account]));++ act(() => {+ result.current.setAccess({+ accountId: account.id,+ serverId: server.id,+ enabled: true,+ ...(scope ? { scope } : {}),+ });+ });++ await waitFor(() =>+ expect(+ queryClient.getQueryData<McpGatewayServer[]>(gatewayKeys.servers)?.[0]+ ?.agents,+ ).toHaveLength(1),+ );++ expect(mocks.setAccess).toHaveBeenCalledWith(account.id, {+ gateway_server_id: server.id,+ enabled: true,+ scope: expectedScope,+ });+ expect(+ queryClient.getQueryData<McpGatewayServer[]>(gatewayKeys.servers)?.[0]+ ?.agents[0],+ ).toMatchObject({+ service_account_id: account.id,+ scope: expectedScope,+ user: { id: mocks.currentUser.id },+ granted_by: {+ id: mocks.currentUser.id,+ uuid: mocks.currentUser.uuid,+ first_name: "Ada",+ last_name: "Lovelace",+ email: "[email protected]",+ hedgehog_config: null,+ },+ });+ expect(mocks.getAccounts).toHaveBeenCalledTimes(1);+ },+ );++ it("keeps a teammate's share of the same agent when revoking your own", async () => {+ const teammateShare = agentShare(teammate, "team");queryClient.setQueryData(gatewayKeys.servers, [- { ...server, agents: [] } as McpGatewayServer,+ {+ ...server,+ agents: [agentShare(you, "personal"), teammateShare],+ } as McpGatewayServer,]);- mocks.setAccess.mockResolvedValue({ ...account, server_ids: [server.id] });const { result } = renderHook(() => useServiceAccounts(), { wrapper });await waitFor(() => expect(result.current.accounts).toEqual([account]));@@ -133,7 +222,7 @@ describe("useServiceAccounts", () => {result.current.setAccess({accountId: account.id,serverId: server.id,- enabled: true,+ enabled: false,});});@@ -141,23 +230,7 @@ describe("useServiceAccounts", () => {expect(queryClient.getQueryData<McpGatewayServer[]>(gatewayKeys.servers)?.[0]?.agents,- ).toHaveLength(1),+ ).toEqual([teammateShare]),);-- expect(- queryClient.getQueryData<McpGatewayServer[]>(gatewayKeys.servers)?.[0]- ?.agents[0],- ).toMatchObject({- service_account_id: account.id,- granted_by: {- id: mocks.currentUser.id,- uuid: mocks.currentUser.uuid,- first_name: "Ada",- last_name: "Lovelace",- email: "[email protected]",- hedgehog_config: null,- },- });- expect(mocks.getAccounts).toHaveBeenCalledTimes(1);});});diff --git a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.ts b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.tsindex 822b2f4d9589..78eb6f6461da 100644--- a/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.ts+++ b/products/desktop/packages/ui/src/features/mcp-gateway/hooks/useServiceAccounts.ts@@ -1,4 +1,5 @@import type {+ McpAgentGrantScope,McpGatewayServer,McpGatewayUser,McpServiceAccount,@@ -120,6 +121,8 @@ export function useServiceAccounts() {accountId: string;serverId: string;enabled: boolean;+ /** Reach of the caller's own share; defaults to personal. */+ scope?: McpAgentGrantScope;policies?: McpToolPolicyEntry[];/** Toast copy, e.g. "Support can now use Linear". */successMessage?: string;@@ -128,14 +131,15 @@ export function useServiceAccounts() {client.setMcpServiceAccountAccess(vars.accountId, {gateway_server_id: vars.serverId,enabled: vars.enabled,+ // Always sent on enable: an omitted scope makes the server reset an+ // existing team share back to personal.+ ...(vars.enabled ? { scope: vars.scope ?? "personal" } : {}),...(vars.policies ? { policies: vars.policies } : {}),}),{onSuccess: (account, vars) => {// The response is the updated account, so keep both access views in// sync without racing it against a potentially stale list refetch.- // The backend stamps `granted_by` with the requesting user on every- // enable, so mirror that with the current user here.queryClient.setQueryData<McpServiceAccount[]>(gatewayKeys.accounts,(current) =>@@ -143,37 +147,46 @@ export function useServiceAccounts() {entry.id === account.id ? account : entry,),);- queryClient.setQueryData<McpGatewayServer[]>(- gatewayKeys.servers,- (current) =>- current?.map((server) => {- if (server.id !== vars.serverId) return server;- const currentAccess = server.agents.find(- (agent) => agent.service_account_id === account.id,- );- const withoutAccount = server.agents.filter(- (agent) => agent.service_account_id !== account.id,- );- return {- ...server,- agents: vars.enabled- ? [- ...withoutAccount,- {- service_account_id: account.id,- name: account.name,- handle: account.handle,- status: account.status,- last_active_at: account.last_active_at,- granted_by: currentUser- ? toGatewayUser(currentUser)- : (currentAccess?.granted_by ?? null),- },- ]- : withoutAccount,- };- }),- );+ const you = currentUser ? toGatewayUser(currentUser) : null;+ if (you) {+ // Only the caller's own share changes; teammates' rows for the+ // same agent stay. The backend stamps the requesting user as both+ // credential owner and grantor on every enable.+ queryClient.setQueryData<McpGatewayServer[]>(+ gatewayKeys.servers,+ (current) =>+ current?.map((server) => {+ if (server.id !== vars.serverId) return server;+ const withoutYourShare = server.agents.filter(+ (agent) =>+ agent.service_account_id !== account.id ||+ agent.user.id !== you.id,+ );+ return {+ ...server,+ agents: vars.enabled+ ? [+ ...withoutYourShare,+ {+ service_account_id: account.id,+ user: you,+ scope: vars.scope ?? "personal",+ name: account.name,+ handle: account.handle,+ status: account.status,+ last_active_at: account.last_active_at,+ granted_by: you,+ },+ ]+ : withoutYourShare,+ };+ }),+ );+ } else {+ // Without the session user there is no telling which share row is+ // the caller's, so refetch instead of guessing.+ queryClient.invalidateQueries({ queryKey: gatewayKeys.servers });+ }if (vars.successMessage) {if (vars.enabled) toast.success(vars.successMessage);else toast.info(vars.successMessage);