: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): add Pi runtime MCP support (#77402)
Jonathan Mieloo892ee8a01cbb
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.tsindex 34f2f02e37e9..6cae27301a7a 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts@@ -7,8 +7,23 @@ import { describe, expect, it, vi } from "vitest";import { DesktopPiRpcClientFactory } from "./desktop-pi-rpc-client-factory";const createPiRpcClient = vi.hoisted(() => vi.fn());+const createRuntimeMcpServers = vi.hoisted(() =>+ vi.fn(() => ({+ posthog: {+ args: [],+ directTools: false,+ headers: { "x-posthog-project-id": "1" },+ lifecycle: "lazy",+ transport: "streamable-http",+ url: "http://127.0.0.1:4321/posthog",+ },+ })),+);-vi.mock("@posthog/agent/pi/rpc-client", () => ({ createPiRpcClient }));+vi.mock("@posthog/agent/pi/rpc-client", () => ({+ createPiRpcClient,+ createRuntimeMcpServers,+}));describe("DesktopPiRpcClientFactory", () => {it("routes Pi through the shared host auth proxy", async () => {@@ -23,18 +38,58 @@ describe("DesktopPiRpcClientFactory", () => {const authProxy = {start: vi.fn(async () => "http://127.0.0.1:1234"),} as unknown as AuthProxyService;+ const policies = [+ {+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ approvalState: "needs_approval" as const,+ },+ ];+ const mcpServerSource = {+ getMcpRuntimeConfiguration: vi.fn(async () => ({+ servers: [+ {+ name: "posthog",+ type: "http" as const,+ url: "http://127.0.0.1:4321/posthog",+ headers: [{ name: "x-posthog-project-id", value: "1" }],+ },+ ],+ policies,+ })),+ };const client = {} as PiRpcClient;createPiRpcClient.mockReturnValue(client);- const factory = new DesktopPiRpcClientFactory(auth, authProxy);+ const factory = new DesktopPiRpcClientFactory(+ auth,+ authProxy,+ mcpServerSource,+ );await expect(- factory.create({ cwd: "/workspace", projectTrusted: true }),+ factory.create({+ taskId: "task-1",+ cwd: "/workspace",+ projectTrusted: true,+ }),).resolves.toBe(client);expect(authProxy.start).toHaveBeenCalledWith(getLlmGatewayUrl(getCloudUrlFromRegion("eu")),);expect(createPiRpcClient).toHaveBeenCalledWith({cwd: "/workspace",+ mcpToolPolicies: policies,+ runtimeMcpServers: {+ posthog: {+ args: [],+ directTools: false,+ headers: { "x-posthog-project-id": "1" },+ lifecycle: "lazy",+ transport: "streamable-http",+ url: "http://127.0.0.1:4321/posthog",+ },+ },projectTrusted: true,providerOptions: {region: "eu",diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.tsindex 5165a8e26551..073198af8b57 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts@@ -1,11 +1,18 @@import {createPiRpcClient,+ createRuntimeMcpServers,type PiRpcClient,} from "@posthog/agent/pi/rpc-client";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";import { type CloudRegion, getCloudUrlFromRegion } from "@posthog/shared";-import { AGENT_AUTH } from "@posthog/workspace-server/services/agent/identifiers";-import type { AgentAuth } from "@posthog/workspace-server/services/agent/ports";+import {+ AGENT_AUTH,+ MCP_SERVER_CONNECTION_SOURCE,+} from "@posthog/workspace-server/services/agent/identifiers";+import type {+ AgentAuth,+ McpServerConnectionSource,+} from "@posthog/workspace-server/services/agent/ports";import type { AuthProxyService } from "@posthog/workspace-server/services/auth-proxy/auth-proxy";import { AUTH_PROXY_SERVICE } from "@posthog/workspace-server/services/auth-proxy/identifiers";import type { PiRpcClientFactory } from "@posthog/workspace-server/services/pi-session/identifiers";@@ -22,6 +29,8 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {@inject(AGENT_AUTH) private readonly auth: AgentAuth,@inject(AUTH_PROXY_SERVICE)private readonly authProxy: AuthProxyService,+ @inject(MCP_SERVER_CONNECTION_SOURCE)+ private readonly mcpServerSource: McpServerConnectionSource,) {}async create(@@ -34,8 +43,17 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {const baseUrl = await this.getProxyUrl(credentials.region);+ const mcpConfiguration =+ await this.mcpServerSource.getMcpRuntimeConfiguration();+ const runtimeMcpServers = createRuntimeMcpServers(mcpConfiguration.servers);+return createPiRpcClient({- ...input,+ cwd: input.cwd,+ model: input.model,+ sessionFile: input.sessionFile,+ projectTrusted: input.projectTrusted,+ runtimeMcpServers,+ mcpToolPolicies: mcpConfiguration.policies,providerOptions: {region: credentials.region,baseUrl,diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.tsindex e575d6e9fdae..1053c890b78b 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-runtime-factory.test.ts@@ -12,6 +12,7 @@ describe("DesktopPiRuntimeFactory", () => {const factory = new DesktopPiRuntimeFactory(clientFactory);const runtime = await factory.create({+ taskId: "task-1",cwd: "/workspace",projectTrusted: true,});@@ -19,6 +20,7 @@ describe("DesktopPiRuntimeFactory", () => {expect(runtime).toBeInstanceOf(PiRuntime);expect(runtime.client).toBe(client);expect(clientFactory.create).toHaveBeenCalledWith({+ taskId: "task-1",cwd: "/workspace",projectTrusted: true,});diff --git a/products/desktop/packages/agent/src/pi/rpc-client.test.ts b/products/desktop/packages/agent/src/pi/rpc-client.test.tsindex 2d894ca279be..3b21c7d46869 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.test.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.test.ts@@ -3,7 +3,64 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { RpcClient } from "@earendil-works/pi-coding-agent";import { describe, expect, it, vi } from "vitest";-import { createPiRpcClient } from "./rpc-client";+import {+ createPiRpcClient,+ createRuntimeMcpServers,+ createRuntimeMcpStdioServers,+} from "./rpc-client";++describe("createRuntimeMcpServers", () => {+ it("maps agent-server HTTP and SSE servers to Harness configuration", () => {+ expect(+ createRuntimeMcpServers([+ {+ name: "posthog",+ type: "http",+ url: "https://mcp.example/mcp",+ headers: [{ name: "authorization", value: "Bearer token" }],+ },+ {+ name: "legacy",+ type: "sse",+ url: "https://mcp.example/sse",+ headers: [],+ },+ ]),+ ).toMatchObject({+ posthog: {+ transport: "streamable-http",+ url: "https://mcp.example/mcp",+ headers: { authorization: "Bearer token" },+ },+ legacy: {+ transport: "sse",+ url: "https://mcp.example/sse",+ },+ });+ });++ it("maps local tools to an eager direct stdio server", () => {+ expect(+ createRuntimeMcpStdioServers([+ {+ name: "posthog-code-tools",+ command: process.execPath,+ args: ["local-tools-mcp-server.js"],+ env: [{ name: "POSTHOG_LOCAL_TOOLS_ENABLED", value: "finish" }],+ },+ ]),+ ).toEqual({+ "posthog-code-tools": {+ command: process.execPath,+ args: ["local-tools-mcp-server.js"],+ env: { POSTHOG_LOCAL_TOOLS_ENABLED: "finish" },+ transport: "stdio",+ lifecycle: "eager",+ directTools: true,+ },+ });+ });+});describe("createPiRpcClient", () => {it("does not put provider credentials in the child environment", () => {@@ -168,6 +225,102 @@ createInterface({ input: process.stdin }).on("line", (line) => {}});+ it("passes runtime MCP servers through the bootstrap channel", async () => {+ const directory = await mkdtemp(join(tmpdir(), "pi-runtime-mcp-"));+ const hostPath = join(directory, "host.mjs");+ const capturePath = join(directory, "capture.json");+ await writeFile(+ hostPath,+ `+import { readFileSync, writeFileSync } from "node:fs";++writeFileSync(${JSON.stringify(capturePath)}, readFileSync(3, "utf8"));+process.stdin.resume();+`,+ );+ const client = createPiRpcClient({+ cliPath: hostPath,+ cwd: directory,+ providerOptions: { apiKey: "proxy-key" },+ runtimeMcpServers: {+ posthog: {+ args: [],+ directTools: false,+ lifecycle: "lazy",+ transport: "streamable-http",+ url: "http://127.0.0.1:4321/posthog",+ },+ },+ });++ try {+ await client.start();+ await vi.waitFor(async () => {+ await expect(readFile(capturePath, "utf8")).resolves.toContain(+ '"runtimeMcpServers"',+ );+ });+ } finally {+ await client.stop();+ await rm(directory, { recursive: true });+ }+ });++ it("routes MCP permission requests over the private host channel", async () => {+ const directory = await mkdtemp(join(tmpdir(), "pi-mcp-permission-"));+ const hostPath = join(directory, "host.mjs");+ const capturePath = join(directory, "capture.json");+ await writeFile(+ hostPath,+ `+import { closeSync, writeFileSync } from "node:fs";++closeSync(3);+process.stdin.resume();+process.send({+ type: "posthog_pi_mcp_permission_request",+ request: {+ requestId: "call-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ },+});+process.on("message", (response) => {+ if (response.type === "posthog_pi_mcp_permission_response") {+ writeFileSync(${JSON.stringify(capturePath)}, JSON.stringify(response));+ }+});+`,+ );+ const requestMcpToolPermission = vi.fn();+ const client = createPiRpcClient({+ cliPath: hostPath,+ cwd: directory,+ providerOptions: { apiKey: "proxy-key" },+ });+ client.onMcpToolPermissionRequest((request) => {+ requestMcpToolPermission(request);+ client.respondMcpToolPermission(request.requestId, "allow");+ });++ try {+ await client.start();+ await vi.waitFor(async () => {+ await expect(readFile(capturePath, "utf8")).resolves.toContain(+ '"decision":"allow"',+ );+ });+ expect(requestMcpToolPermission).toHaveBeenCalledWith(+ expect.objectContaining({ requestId: "call-1" }),+ );+ } finally {+ await client.stop();+ await rm(directory, { recursive: true });+ }+ });+it("uses the private host channel without changing Pi RPC", async () => {const directory = await mkdtemp(join(tmpdir(), "pi-host-channel-"));const hostPath = join(directory, "host.mjs");diff --git a/products/desktop/packages/agent/src/pi/rpc-client.ts b/products/desktop/packages/agent/src/pi/rpc-client.tsindex 769cb2bffe91..0785704ee7e0 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.ts@@ -9,6 +9,13 @@ import {type RpcClientOptions,type RpcEventListener,} from "@earendil-works/pi-coding-agent";+import type { McpConfig } from "@posthog/harness/extensions/mcp/config";+import type {+ McpServerConnection,+ McpToolPermissionDecision,+ McpToolPermissionRequest,+ McpToolPolicy,+} from "@posthog/shared";import { safePiEnvironment } from "./rpc-environment";import type {PiExtensionEvent,@@ -24,6 +31,13 @@ export type PiRpcClient = RpcClient & {onEvent(listener: PiRpcEventListener): () => void;getQueue(): Promise<PiQueueSnapshot>;clearQueue(): Promise<PiQueueSnapshot>;+ onMcpToolPermissionRequest(+ listener: (request: McpToolPermissionRequest) => void,+ ): () => void;+ respondMcpToolPermission(+ requestId: string,+ decision: McpToolPermissionDecision,+ ): void;respondToExtensionUI(response: RpcExtensionUIResponse): Promise<void>;};@@ -35,6 +49,8 @@ export interface PiRpcProviderOptions {interface PiRpcBootstrap {providerOptions: PiRpcProviderOptions;+ runtimeMcpServers?: PiRuntimeMcpServers;+ mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;channelMode?: boolean;}@@ -56,12 +72,75 @@ interface RpcClientInternals {rejectPendingRequests(error: Error): void;}+export type PiRuntimeMcpServers = McpConfig["mcpServers"];++export interface PiStdioMcpServer {+ name: string;+ command: string;+ args?: string[];+ env?: Array<{ name: string; value: string }>;+}++export function createRuntimeMcpServers(+ servers: McpServerConnection[],+): PiRuntimeMcpServers {+ return Object.fromEntries(+ servers.map((server) => [+ server.name,+ {+ transport:+ server.type === "http"+ ? ("streamable-http" as const)+ : ("sse" as const),+ url: server.url,+ headers: Object.fromEntries(+ (server.headers ?? []).map((header) => [header.name, header.value]),+ ),+ lifecycle: "lazy" as const,+ args: [],+ directTools: false,+ },+ ]),+ );+}++export function createRuntimeMcpStdioServers(+ servers: PiStdioMcpServer[],+): PiRuntimeMcpServers {+ return Object.fromEntries(+ servers.map((server) => [+ server.name,+ {+ command: server.command,+ args: server.args ?? [],+ env: Object.fromEntries(+ (server.env ?? []).map((variable) => [variable.name, variable.value]),+ ),+ transport: "stdio" as const,+ lifecycle: "eager" as const,+ directTools: true,+ },+ ]),+ );+}+interface PiHostRequest {type: "posthog_pi_host_request";id: string;method: "get_queue" | "clear_queue";}+interface PiMcpPermissionRequestMessage {+ type: "posthog_pi_mcp_permission_request";+ request: McpToolPermissionRequest;+}++interface PiMcpPermissionResponseMessage {+ type: "posthog_pi_mcp_permission_response";+ requestId: string;+ decision: McpToolPermissionDecision;+}+interface PiHostResponse {type: "posthog_pi_host_response";id: string;@@ -90,6 +169,9 @@ function attachJsonlReader(}class SecurePiRpcClient extends RpcClient {+ private readonly mcpPermissionListeners = new Set<+ (request: McpToolPermissionRequest) => void+ >();private readonly hostRequests = new Map<string,{@@ -101,9 +183,7 @@ class SecurePiRpcClient extends RpcClient {constructor(private readonly secureOptions: RpcClientOptions,- private readonly providerOptions: PiRpcProviderOptions,- private readonly projectTrusted: boolean,- private readonly channelMode: boolean,+ private readonly bootstrap: PiRpcBootstrap,) {super(secureOptions);}@@ -161,7 +241,10 @@ class SecurePiRpcClient extends RpcClient {internals.rejectPendingRequests(error);this.rejectHostRequests(error);});- child.on("message", (message: unknown) => this.handleHostResponse(message));+ child.on("message", (message: unknown) => {+ this.handleHostResponse(message);+ this.handleMcpPermissionRequest(message);+ });child.once("error", (error) => {if (internals.process !== child) {return;@@ -189,13 +272,7 @@ class SecurePiRpcClient extends RpcClient {const bootstrapPipe = child.stdio[3] as Writable | null;bootstrapPipe?.on("error", () => {});- bootstrapPipe?.end(- JSON.stringify({- providerOptions: this.providerOptions,- projectTrusted: this.projectTrusted,- channelMode: this.channelMode,- } satisfies PiRpcBootstrap),- );+ bootstrapPipe?.end(JSON.stringify(this.bootstrap));await new Promise((resolve) => setTimeout(resolve, 100));if (child.exitCode !== null) {@@ -294,6 +371,39 @@ class SecurePiRpcClient extends RpcClient {request.resolve(response.data);}+ onMcpToolPermissionRequest(+ listener: (request: McpToolPermissionRequest) => void,+ ): () => void {+ this.mcpPermissionListeners.add(listener);+ return () => this.mcpPermissionListeners.delete(listener);+ }++ respondMcpToolPermission(+ requestId: string,+ decision: McpToolPermissionDecision,+ ): void {+ const child = (this as unknown as RpcClientProcessAccess).process;+ child?.send({+ type: "posthog_pi_mcp_permission_response",+ requestId,+ decision,+ } satisfies PiMcpPermissionResponseMessage);+ }++ private handleMcpPermissionRequest(message: unknown): void {+ const permissionMessage = message as Partial<PiMcpPermissionRequestMessage>;+ if (+ permissionMessage.type !== "posthog_pi_mcp_permission_request" ||+ !permissionMessage.request+ ) {+ return;+ }++ for (const listener of this.mcpPermissionListeners) {+ listener(permissionMessage.request);+ }+ }+private rejectHostRequests(error: Error): void {for (const request of this.hostRequests.values()) {clearTimeout(request.timeout);@@ -315,6 +425,8 @@ export type PiRpcClientOptions = Pick<> & {sessionFile?: string;providerOptions: PiRpcProviderOptions;+ runtimeMcpServers?: PiRuntimeMcpServers;+ mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;channelMode?: boolean;};@@ -323,6 +435,8 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {const {sessionFile,providerOptions,+ runtimeMcpServers,+ mcpToolPolicies,projectTrusted,channelMode,...rpcOptions@@ -338,8 +452,12 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {cliPath,provider: "posthog",},- providerOptions,- projectTrusted ?? false,- channelMode === true,+ {+ providerOptions,+ runtimeMcpServers,+ mcpToolPolicies,+ projectTrusted: projectTrusted ?? false,+ channelMode: channelMode === true,+ } satisfies PiRpcBootstrap,);}diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.tsindex 9b7654f47a6e..1752a4239040 100644--- a/products/desktop/packages/agent/src/pi/rpc-host.ts+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts@@ -1,8 +1,14 @@import { readFileSync } from "node:fs";import { SessionManager } from "@earendil-works/pi-coding-agent";import { createHarnessRuntime, runRpcMode } from "@posthog/harness";+import type { McpConfig } from "@posthog/harness/extensions/mcp/config";import type { PosthogProviderOptions } from "@posthog/harness/extensions/posthog-provider/provider";import { createPiRuntimeTrustResolver } from "@posthog/harness/project-trust";+import type {+ McpToolPermissionDecision,+ McpToolPermissionRequest,+ McpToolPolicy,+} from "@posthog/shared";import {POSTHOG_PI_QUEUE_ENTRY_TYPE,readPersistedPiQueue,@@ -12,6 +18,8 @@ import { sanitizePiHostEnvironment } from "./rpc-environment";interface PiRpcBootstrap {providerOptions?: PosthogProviderOptions;+ runtimeMcpServers?: McpConfig["mcpServers"];+ mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;channelMode?: boolean;}@@ -39,6 +47,31 @@ const sessionFile = argumentValue("--session-file");const sessionManager = sessionFile? SessionManager.open(sessionFile, undefined, cwd): SessionManager.create(cwd);+function requestMcpToolPermission(+ request: McpToolPermissionRequest,+): Promise<McpToolPermissionDecision> {+ return new Promise((resolve) => {+ const onMessage = (message: unknown) => {+ const response = message as {+ type?: string;+ requestId?: string;+ decision?: McpToolPermissionDecision;+ };+ if (+ response.type !== "posthog_pi_mcp_permission_response" ||+ response.requestId !== request.requestId ||+ !response.decision+ ) {+ return;+ }+ process.off("message", onMessage);+ resolve(response.decision);+ };+ process.on("message", onMessage);+ process.send?.({ type: "posthog_pi_mcp_permission_request", request });+ });+}+const runtime = await createHarnessRuntime({cwd,sessionManager,@@ -54,6 +87,9 @@ const runtime = await createHarnessRuntime({}: {}),...providerOptions,+ runtimeMcpServers: bootstrap.runtimeMcpServers,+ mcpToolPolicies: bootstrap.mcpToolPolicies,+ requestMcpToolPermission,});const persistedQueue = readPersistedPiQueue(sessionManager.getEntries());diff --git a/products/desktop/packages/agent/src/pi/rpc-transport.ts b/products/desktop/packages/agent/src/pi/rpc-transport.tsindex 37b2f86710ed..0e826d8105b0 100644--- a/products/desktop/packages/agent/src/pi/rpc-transport.ts+++ b/products/desktop/packages/agent/src/pi/rpc-transport.ts@@ -8,6 +8,13 @@ import { z } from "zod/v4";export type { RpcCommand, RpcResponse } from "@earendil-works/pi-coding-agent";+export interface PiMcpPermissionResponseCommand {+ id: string;+ type: "mcp_permission_response";+ requestId: string;+ decision: "allow" | "allow_always" | "reject";+}+export const piRpcCommandSchema = z.object({id: z.string().optional(),diff --git a/products/desktop/packages/agent/src/posthog-api.test.ts b/products/desktop/packages/agent/src/posthog-api.test.tsindex cbc600ebf4d9..54d543f045ae 100644--- a/products/desktop/packages/agent/src/posthog-api.test.ts+++ b/products/desktop/packages/agent/src/posthog-api.test.ts@@ -46,6 +46,82 @@ describe("PostHogAPIClient", () => {expect(mockFetch).toHaveBeenCalledTimes(2);});+ it("loads policies for managed MCP servers and keeps unmanaged servers", async () => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ mockFetch.mockResolvedValueOnce({+ ok: true,+ json: vi.fn().mockResolvedValue({+ results: [+ {+ tool_name: "search",+ approval_state: "needs_approval",+ description: "Search resources",+ },+ ],+ }),+ });++ await expect(+ client.getMcpRuntimeConfiguration([+ {+ type: "http",+ name: "Cloudflare",+ url: "https://app.posthog.com/api/environments/7/mcp_server_installations/installation-1/proxy/",+ headers: [],+ },+ {+ type: "http",+ name: "custom",+ url: "https://mcp.example.com/mcp",+ headers: [],+ },+ ]),+ ).resolves.toEqual({+ servers: [+ expect.objectContaining({ name: "Cloudflare" }),+ expect.objectContaining({ name: "custom" }),+ ],+ policies: [+ {+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ approvalState: "needs_approval",+ description: "Search resources",+ },+ ],+ });+ });++ it("omits a managed MCP server when its policies cannot be loaded", async () => {+ const client = new PostHogAPIClient({+ apiUrl: "https://app.posthog.com",+ getApiKey: vi.fn().mockResolvedValue("token"),+ projectId: 7,+ });+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 500,+ statusText: "Server error",+ json: vi.fn().mockResolvedValue({ detail: "failed" }),+ });++ const configuration = await client.getMcpRuntimeConfiguration([+ {+ type: "http",+ name: "broken",+ url: "https://app.posthog.com/api/environments/7/mcp_server_installations/installation-1/proxy/",+ headers: [],+ },+ ]);++ expect(configuration).toEqual({ servers: [], policies: [] });+ });+it("downloads artifacts through the backend endpoint", async () => {const client = new PostHogAPIClient({apiUrl: "https://app.posthog.com",diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.tsindex f9d1488eb3eb..74f0b2ab7f0b 100644--- a/products/desktop/packages/agent/src/posthog-api.ts+++ b/products/desktop/packages/agent/src/posthog-api.ts@@ -1,4 +1,9 @@-import type { StoredLogEntry } from "@posthog/shared";+import type {+ McpServerConnection,+ McpToolApprovalState,+ McpToolPolicy,+ StoredLogEntry,+} from "@posthog/shared";import packageJson from "../package.json" with { type: "json" };import type {ArtifactSource,@@ -180,6 +185,82 @@ export class PostHogAPIClient {return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`);}+ async getMcpRuntimeConfiguration(+ servers: McpServerConnection[],+ ): Promise<{ servers: McpServerConnection[]; policies: McpToolPolicy[] }> {+ const resolved = await Promise.all(+ servers.map(async (server) => {+ const installationId = this.mcpInstallationId(server.url);+ if (!installationId) {+ return { server, policies: [] };+ }++ try {+ const response = await this.apiRequest<{+ results?: Array<{+ tool_name: string;+ approval_state?: McpToolApprovalState;+ description?: string;+ }>;+ }>(+ `/api/environments/${this.getTeamId()}/mcp_server_installations/${installationId}/tools/`,+ );+ const policies = (response.results ?? []).flatMap((tool) =>+ tool.approval_state+ ? [+ {+ serverName: server.name,+ toolName: tool.tool_name,+ installationId,+ approvalState: tool.approval_state,+ ...(tool.description+ ? { description: tool.description }+ : {}),+ } satisfies McpToolPolicy,+ ]+ : [],+ );+ return { server, policies };+ } catch {+ return null;+ }+ }),+ );++ return {+ servers: resolved.flatMap((entry) => (entry ? [entry.server] : [])),+ policies: resolved.flatMap((entry) => entry?.policies ?? []),+ };+ }++ async approveMcpTool(+ installationId: string,+ toolName: string,+ ): Promise<void> {+ await this.apiRequest(+ `/api/environments/${this.getTeamId()}/mcp_server_installations/${installationId}/tools/${encodeURIComponent(toolName)}/`,+ {+ method: "PATCH",+ body: JSON.stringify({ approval_state: "approved" }),+ },+ );+ }++ private mcpInstallationId(url: string): string | null {+ try {+ const serverUrl = new URL(url);+ if (serverUrl.origin !== new URL(this.baseUrl).origin) {+ return null;+ }+ const match = serverUrl.pathname.match(+ /\/mcp_server_installations\/([^/]+)\/proxy\/?$/,+ );+ return match?.[1] ? decodeURIComponent(match[1]) : null;+ } catch {+ return null;+ }+ }+async getTaskRun(taskId: string, runId: string): Promise<TaskRun> {const teamId = this.getTeamId();return this.apiRequest<TaskRun>(diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex 0d80b1681fff..414b9e845619 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -21,6 +21,7 @@ import {type Adapter,buildPrOutput,getErrorMessage,+ type McpServerConnection,mergePrUrls,parseMcpToolName,readMcpToolDescriptor,@@ -117,7 +118,6 @@ import { RunUsageAccumulator } from "./run-usage";import {handoffLocalGitStateSchema,jsonRpcRequestSchema,- type RemoteMcpServer,validateCommandParams,} from "./schemas";import type { AgentServerConfig } from "./types";@@ -439,7 +439,7 @@ export class AgentServer {* servers and return their session mcpServers entries. No designations →* no relay server, no entries.*/- private async startMcpRelayServer(): Promise<RemoteMcpServer[]> {+ private async startMcpRelayServer(): Promise<McpServerConnection[]> {const names = this.config.relayMcpServers ?? [];if (names.length === 0) return [];if (!this.mcpRelayServer) {@@ -1789,7 +1789,7 @@ export class AgentServer {let effectiveSessionMeta: typeof sessionMeta & {nativeGoal?: NonNullable<ResumeState["nativeGoal"]>;} = sessionMeta;- let sessionMcpServers: RemoteMcpServer[];+ let sessionMcpServers: McpServerConnection[];try {await this.installSkillBundleArtifacts(payload.task_id,diff --git a/products/desktop/packages/agent/src/server/mcp-relay-server.ts b/products/desktop/packages/agent/src/server/mcp-relay-server.tsindex 8a72ef333e21..87bca18a6468 100644--- a/products/desktop/packages/agent/src/server/mcp-relay-server.ts+++ b/products/desktop/packages/agent/src/server/mcp-relay-server.ts@@ -1,8 +1,8 @@import crypto from "node:crypto";import { type ServerType, serve } from "@hono/node-server";+import type { McpServerConnection } from "@posthog/shared";import { Hono } from "hono";import type { Logger } from "../utils/logger";-import type { RemoteMcpServer } from "./schemas";export const DEFAULT_RELAY_TIMEOUT_MS = 60_000;/** Request payloads above this are rejected before any event is emitted. */@@ -103,7 +103,7 @@ export class McpRelayServer {}/** Session mcpServers entries for the relay endpoints. Call after start(). */- get mcpServers(): RemoteMcpServer[] {+ get mcpServers(): McpServerConnection[] {if (this.port === null) return [];return [...this.serverNames].map((name) => ({type: "http" as const,diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts b/products/desktop/packages/agent/src/server/pi-agent-server.test.tsindex 21c246322360..61d809ed2099 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.test.ts@@ -139,6 +139,64 @@ describe("PiAgentServer", () => {]);});+ it("relays MCP permission requests and persists always-allow responses", async () => {+ const approveMcpTool = vi.fn(async () => {});+ const respondMcpToolPermission = vi.fn();+ const server = new PiAgentServer(config()) as unknown as {+ posthogAPI: { approveMcpTool: typeof approveMcpTool };+ session: unknown;+ pendingEvents: Record<string, unknown>[];+ handleMcpToolPermissionRequest(request: Record<string, unknown>): void;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.posthogAPI.approveMcpTool = approveMcpTool;+ server.session = {+ runtime: { client: { respondMcpToolPermission } },+ };+ const request = {+ requestId: "request-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ description: "Search resources",+ };++ server.handleMcpToolPermissionRequest(request);++ expect(server.pendingEvents).toContainEqual(+ expect.objectContaining({+ type: "permission_request",+ requestId: "request-1",+ toolCall: expect.objectContaining({+ rawInput: { query: "workers" },+ }),+ options: [+ expect.objectContaining({ optionId: "allow_always" }),+ expect.objectContaining({ optionId: "reject" }),+ ],+ }),+ );++ await server.executeCommand("pi/rpc", {+ command: {+ id: "response-1",+ type: "mcp_permission_response",+ requestId: "request-1",+ decision: "allow_always",+ },+ });++ expect(approveMcpTool).toHaveBeenCalledWith("installation-1", "search");+ expect(respondMcpToolPermission).toHaveBeenCalledWith(+ "request-1",+ "allow_always",+ );+ });+it("bounds events retained while no SSE client is connected", () => {const server = new PiAgentServer(config()) as unknown as {broadcast(event: Record<string, unknown>): void;diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex 13269d83e3ca..465fc8570f89 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -3,17 +3,28 @@ import { access, mkdir, readFile, writeFile } from "node:fs/promises";import { basename, dirname, join } from "node:path";import type { ServerType } from "@hono/node-server";import { serve } from "@hono/node-server";-import type {- AgentConversationEvent,- StoredLogEntry,- TaskRunArtifact,+import {+ type AgentConversationEvent,+ MCP_TOOL_PERMISSION_OPTIONS,+ type McpToolPermissionDecision,+ type McpToolPermissionRequest,+ mcpToolKey,+ posthogToolMeta,+ type StoredLogEntry,+ serializeError,+ type TaskRunArtifact,} from "@posthog/shared";-import { serializeError } from "@posthog/shared";import { Hono } from "hono";import { z } from "zod/v4";import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";+import { buildLocalToolsServer } from "../adapters/codex-app-server/local-tools-mcp";import { OtelRunTelemetry } from "../otel-telemetry";-import { createPiRpcClient, type PiRpcClient } from "../pi/rpc-client";+import {+ createPiRpcClient,+ createRuntimeMcpServers,+ createRuntimeMcpStdioServers,+ type PiRpcClient,+} from "../pi/rpc-client";import { piRpcCommandSchema, type RpcCommand } from "../pi/rpc-transport";import { PiRuntime } from "../pi/runtime";import { PostHogAPIClient } from "../posthog-api";@@ -53,6 +64,13 @@ const userMessageCommandSchema = z"Either content or artifacts are required",);+const mcpPermissionResponseCommandSchema = z.object({+ id: z.string().min(1),+ type: z.literal("mcp_permission_response"),+ requestId: z.string().min(1),+ decision: z.enum(["allow", "allow_always", "reject"]),+});+const commandSchemas = {user_message: userMessageCommandSchema,cancel: emptySchema,@@ -110,6 +128,10 @@ export class PiAgentServer {private logFlushActive = false;private logFlushRequested = false;private readonly canceledSseControllers = new WeakSet<SseController>();+ private readonly pendingMcpPermissions = new Map<+ string,+ McpToolPermissionRequest+ >();constructor(private readonly config: AgentServerConfig) {this.posthogAPI = new PostHogAPIClient({@@ -217,6 +239,7 @@ export class PiAgentServer {);}this.session = null;+ this.pendingMcpPermissions.clear();await this.flushConversationLog().catch((error) =>this.logger.error("Failed to persist Pi events during shutdown", error),);@@ -488,11 +511,30 @@ export class PiAgentServer {this.lastSyncedSessionContent = persistedSessionContent;this.sessionContentSha256 = sessionStorage.content_sha256;+ const localTools = buildLocalToolsServer(+ { cwd },+ {+ environment: "cloud",+ taskId: this.config.taskId,+ taskRunId: this.config.runId,+ baseBranch: this.config.baseBranch,+ },+ );+ const mcpConfiguration = await this.posthogAPI.getMcpRuntimeConfiguration(+ this.config.mcpServers ?? [],+ );+ const runtimeMcpServers = {+ ...createRuntimeMcpServers(mcpConfiguration.servers),+ ...createRuntimeMcpStdioServers(localTools ? [localTools] : []),+ };+const client = createPiRpcClient({cliPath: this.config.piRpcHostPath,cwd,model: this.config.model,sessionFile: restoredSessionFile,+ runtimeMcpServers,+ mcpToolPolicies: mcpConfiguration.policies,providerOptions: {apiKey: this.config.apiKey,baseUrl: resolveLlmGatewayUrl(@@ -515,6 +557,9 @@ export class PiAgentServer {});}});+ const unsubscribeMcpPermissions = client.onMcpToolPermissionRequest(+ (request) => this.handleMcpToolPermissionRequest(request),+ );await client.start();if (this.config.reasoningEffort) {// Pi's ThinkingLevel has no ultracode notch; run it at its xhigh equivalent.@@ -529,6 +574,7 @@ export class PiAgentServer {const unsubscribe = () => {unsubscribeConversation();unsubscribeRuntime();+ unsubscribeMcpPermissions();};this.session = { payload, runtime, sseController: null, unsubscribe };@@ -560,6 +606,56 @@ export class PiAgentServer {}}+ private handleMcpToolPermissionRequest(+ request: McpToolPermissionRequest,+ ): void {+ this.pendingMcpPermissions.set(request.requestId, request);+ const mcp = { server: request.serverName, tool: request.toolName };+ this.broadcast({+ type: "permission_request",+ requestId: request.requestId,+ toolCall: {+ toolCallId: request.requestId,+ title: `The agent wants to call ${request.toolName} (${request.serverName})`,+ kind: "other",+ content: request.description+ ? [+ {+ type: "content",+ content: { type: "text", text: request.description },+ },+ ]+ : [],+ rawInput: request.arguments,+ _meta: posthogToolMeta({+ toolName: mcpToolKey(mcp),+ mcp,+ mcpInstallationId: request.installationId,+ }),+ },+ options: MCP_TOOL_PERMISSION_OPTIONS,+ });+ }++ private async respondMcpToolPermission(+ requestId: string,+ decision: McpToolPermissionDecision,+ ): Promise<{ resolved: true }> {+ const request = this.pendingMcpPermissions.get(requestId);+ if (!request) {+ throw new Error(`No pending MCP permission ${requestId}`);+ }+ if (decision === "allow_always") {+ await this.posthogAPI.approveMcpTool(+ request.installationId,+ request.toolName,+ );+ }+ this.pendingMcpPermissions.delete(requestId);+ this.session?.runtime.client.respondMcpToolPermission(requestId, decision);+ return { resolved: true };+ }+private async executeCommand(method: PiCommandMethod,params: Record<string, unknown>,@@ -581,8 +677,19 @@ export class PiAgentServer {runtime.clearPendingQueuedUserMessages();return queue;}- case "pi/rpc":- return runtime.sendCommand(params.command as RpcCommand);+ case "pi/rpc": {+ const command = params.command as RpcCommand;+ if (+ (command as { type?: unknown }).type === "mcp_permission_response"+ ) {+ const response = mcpPermissionResponseCommandSchema.parse(command);+ return this.respondMcpToolPermission(+ response.requestId,+ response.decision,+ );+ }+ return runtime.sendCommand(command);+ }}}diff --git a/products/desktop/packages/agent/src/server/schemas.ts b/products/desktop/packages/agent/src/server/schemas.tsindex 56fa3b608bcd..e77d71d42bf6 100644--- a/products/desktop/packages/agent/src/server/schemas.ts+++ b/products/desktop/packages/agent/src/server/schemas.ts@@ -1,3 +1,4 @@+import type { McpServerConnection } from "@posthog/shared";import { z } from "zod/v4";export { posthogExecPermissionRegexSchema } from "../posthog-exec-permission";@@ -20,7 +21,7 @@ export const handoffLocalGitStateSchema = z.object({upstreamMergeRef: nullishString,});-const remoteMcpServerSchema = z.object({+const remoteMcpServerSchema: z.ZodType<McpServerConnection> = z.object({type: z.enum(["http", "sse"]),name: z.string().min(1, "MCP server name is required"),url: z.url({ error: "MCP server url must be a valid URL" }),@@ -29,8 +30,6 @@ const remoteMcpServerSchema = z.object({export const mcpServersSchema = z.array(remoteMcpServerSchema);-export type RemoteMcpServer = z.infer<typeof remoteMcpServerSchema>;-export const claudeCodeConfigSchema = z.object({systemPrompt: z.union([diff --git a/products/desktop/packages/agent/src/server/types.ts b/products/desktop/packages/agent/src/server/types.tsindex 50a24c095e53..33cc5b7877f7 100644--- a/products/desktop/packages/agent/src/server/types.ts+++ b/products/desktop/packages/agent/src/server/types.ts@@ -1,8 +1,7 @@-import type { Adapter } from "@posthog/shared";+import type { Adapter, McpServerConnection } from "@posthog/shared";import type { EffortLevel } from "@posthog/shared/domain-types";import type { AgentMode } from "../types";import type { RtkSavingsSummary } from "./rtk-savings";-import type { RemoteMcpServer } from "./schemas";export interface ClaudeCodeConfig {systemPrompt?:@@ -41,7 +40,7 @@ export interface AgentServerConfig {// manual (non-automated-origin) cloud runs. createPr=false still wins.autoPublish?: boolean;version?: string;- mcpServers?: RemoteMcpServer[];+ mcpServers?: McpServerConnection[];/*** Case-insensitive JavaScript regex matched against PostHog `exec` sub-tool* names. Overrides the default approval regex for interactive calls.diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.tsindex e427e84349a5..2c5df489f998 100644--- a/products/desktop/packages/api-client/src/posthog-client.ts+++ b/products/desktop/packages/api-client/src/posthog-client.ts@@ -1,11 +1,11 @@import "./generated.augment";import type {Adapter,- CloudMcpServerImport,CloudMcpServerRelayDesignation,CloudRunSource,CreateTaskAutomationOptions,ExecutionMode,+ McpServerConnection,PrAuthorshipMode,SourceProduct,SourceType,@@ -712,7 +712,7 @@ export interface CloudRunOptions {* Local url-based MCP servers to make available inside the sandbox. The* backend merges these into the agent server's `--mcpServers` at spawn.*/- importedMcpServers?: CloudMcpServerImport[];+ importedMcpServers?: McpServerConnection[];relayedMcpServers?: CloudMcpServerRelayDesignation[];}diff --git a/products/desktop/packages/core/src/local-mcp/localMcpImport.ts b/products/desktop/packages/core/src/local-mcp/localMcpImport.tsindex bafab32ec24c..5cbb4adf0789 100644--- a/products/desktop/packages/core/src/local-mcp/localMcpImport.ts+++ b/products/desktop/packages/core/src/local-mcp/localMcpImport.ts@@ -1,8 +1,8 @@import type {Adapter,- CloudMcpServerImport,CloudMcpServerRelayDesignation,LocalMcpServerDescriptor,+ McpServerConnection,} from "@posthog/shared";import { isPrivateIpv4Octets, isPrivateIpv6Literal } from "@posthog/shared";import { inject, injectable } from "inversify";@@ -43,7 +43,7 @@ export interface LocalMcpCloudClassification {availability: LocalMcpCloudAvailability;reason: LocalMcpCloudReason;/** Sandbox-shaped config; present only when availability is "importable". */- remote?: CloudMcpServerImport;+ remote?: McpServerConnection;}function parseIpv4(host: string): [number, number, number, number] | null {@@ -147,7 +147,7 @@ export function classifyLocalMcpServer(const MAX_RELAYED_MCP_SERVERS = 20;export interface LocalMcpServersForRun {- imported: CloudMcpServerImport[];+ imported: McpServerConnection[];relayed: CloudMcpServerRelayDesignation[];}diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.tsindex 14ff92b77e60..e79d0d2870b1 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts@@ -1,5 +1,9 @@import type { TaskService } from "@posthog/core/task-detail/taskService";-import type { AgentConversationEvent } from "@posthog/shared";+import {+ type AgentConversationEvent,+ mcpToolKey,+ posthogToolMeta,+} from "@posthog/shared";import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";import { describe, expect, it, vi } from "vitest";import type { CloudTaskClient } from "../cloud-task/cloudTaskClient";@@ -10,19 +14,19 @@ import {} from "./piSessionController";function createCloudTaskClient(autoStart = true) {- let onUpdate: (update: CloudTaskUpdatePayload) => void = () => {};- let onError: (error: unknown) => void = () => {};- let onStarted: () => void = () => {};+ const subscriptions: Array<{+ onUpdate: (update: CloudTaskUpdatePayload) => void;+ onError: (error: unknown) => void;+ onStarted: () => void;+ }> = [];const unsubscribe = vi.fn();const client: CloudTaskClient = {getContext: vi.fn(async () => null),watch: vi.fn(async () => {}),unwatch: vi.fn(async () => {}),retry: vi.fn(async () => {}),- subscribe: vi.fn((_taskId, _runId, handler, errorHandler, started) => {- onUpdate = handler;- onError = errorHandler;- onStarted = started;+ subscribe: vi.fn((_taskId, _runId, onUpdate, onError, onStarted) => {+ subscriptions.push({ onUpdate, onError, onStarted });if (autoStart) {onStarted();}@@ -33,9 +37,21 @@ function createCloudTaskClient(autoStart = true) {return {client,- startSubscription: () => onStarted(),- sendUpdate: (update: CloudTaskUpdatePayload) => onUpdate(update),- sendError: (error: unknown) => onError(error),+ startSubscription: () => {+ for (const subscription of subscriptions) {+ subscription.onStarted();+ }+ },+ sendUpdate: (update: CloudTaskUpdatePayload) => {+ for (const subscription of subscriptions) {+ subscription.onUpdate(update);+ }+ },+ sendError: (error: unknown) => {+ for (const subscription of subscriptions) {+ subscription.onError(error);+ }+ },unsubscribe,};}@@ -57,6 +73,74 @@ const snapshotEvent: AgentConversationEvent = {};describe("CloudPiSessionClient", () => {+ it("relays MCP permission requests and responses through the cloud task", async () => {+ const cloud = createCloudTaskClient();+ const session = new CloudPiSessionClient(+ cloud.client,+ context("in_progress"),+ );+ const onRequest = vi.fn();+ session.onMcpToolPermissionRequest(onRequest, vi.fn());++ const mcp = { server: "Cloudflare", tool: "search" };+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "permission_request",+ requestId: "request-1",+ toolCall: {+ toolCallId: "request-1",+ title: "Search Cloudflare",+ kind: "other",+ content: [+ {+ type: "content",+ content: { type: "text", text: "Search Cloudflare resources" },+ },+ ],+ rawInput: { query: "workers" },+ _meta: posthogToolMeta({+ toolName: mcpToolKey(mcp),+ mcp,+ mcpInstallationId: "installation-1",+ }),+ },+ options: [],+ });++ const request = {+ requestId: "request-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ description: "Search Cloudflare resources",+ };+ expect(onRequest).toHaveBeenCalledWith(request);++ vi.mocked(cloud.client.sendCommand).mockResolvedValue({ success: true });+ await session.respondMcpToolPermission(request, "allow_always");++ const commandInput = vi.mocked(cloud.client.sendCommand).mock.calls[0]?.[0];+ expect(commandInput).toMatchObject({+ taskId: "task-1",+ runId: "run-1",+ apiHost: "https://us.posthog.com",+ teamId: 1,+ method: "pi/rpc",+ params: {+ command: {+ type: "mcp_permission_response",+ requestId: "request-1",+ decision: "allow_always",+ },+ },+ });+ expect(commandInput?.id).toBe(+ (commandInput?.params?.command as { id?: string }).id,+ );+ });+it("waits for the native Pi readiness event before startup RPC commands", async () => {const cloud = createCloudTaskClient();vi.mocked(cloud.client.sendCommand).mockResolvedValue({@@ -384,7 +468,7 @@ describe("CloudPiSessionClient", () => {const connection = controller.connect("task-1");await vi.waitFor(() => {- expect(cloud.client.subscribe).toHaveBeenCalledTimes(1);+ expect(cloud.client.subscribe).toHaveBeenCalledTimes(2);});cloud.sendUpdate({taskId: "task-1",diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.tsindex 238d5081018d..5cd8ed8063f8 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts@@ -2,16 +2,23 @@ import {type PiRemoteRpcClient,RemotePiRpcClient,} from "@posthog/agent/pi/remote-rpc-client";-import type { RpcCommand } from "@posthog/agent/pi/rpc-transport";+import type {+ PiMcpPermissionResponseCommand,+ RpcCommand,+} from "@posthog/agent/pi/rpc-transport";import type {PiPersistedSessionConfig,PiQueueSnapshot,} from "@posthog/agent/pi/types";-import type {- AgentConversationEvent,- PiRuntimeHealth,- StoredLogEntry,- TaskRunStatus,+import {+ type AgentConversationEvent,+ type McpToolPermissionDecision,+ type McpToolPermissionRequest,+ type PiRuntimeHealth,+ readMcpInstallationId,+ readMcpToolDescriptor,+ type StoredLogEntry,+ type TaskRunStatus,} from "@posthog/shared";import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";import type { CloudTaskClient } from "../cloud-task/cloudTaskClient";@@ -59,6 +66,28 @@ function createTerminalPiRpcClient(};}+function permissionDescription(+ content: unknown[] | undefined,+): string | undefined {+ for (const item of content ?? []) {+ if (!item || typeof item !== "object") {+ continue;+ }+ const block = item as { type?: unknown; content?: unknown };+ if (block.type !== "content" || !block.content) {+ continue;+ }+ if (typeof block.content !== "object") {+ continue;+ }+ const text = block.content as { type?: unknown; text?: unknown };+ if (text.type === "text" && typeof text.text === "string") {+ return text.text;+ }+ }+ return undefined;+}+export interface CloudPiSessionContext {taskId: string;runId: string;@@ -200,6 +229,62 @@ export class CloudPiSessionClient implements PiSession {return this.snapshotEvents;}+ onMcpToolPermissionRequest(+ onRequest: (request: McpToolPermissionRequest) => void,+ onError: (error: unknown) => void,+ ): () => void {+ return this.cloudTaskClient.subscribe(+ this.context.taskId,+ this.context.runId,+ (update) => {+ if (update.kind !== "permission_request") {+ return;+ }+ const mcp = readMcpToolDescriptor(update.toolCall._meta);+ const installationId = readMcpInstallationId(update.toolCall._meta);+ if (!mcp || !installationId) {+ return;+ }+ const description = permissionDescription(update.toolCall.content);+ onRequest({+ requestId: update.requestId,+ serverName: mcp.server,+ toolName: mcp.tool,+ installationId,+ arguments: update.toolCall.rawInput ?? {},+ ...(description ? { description } : {}),+ });+ },+ onError,+ () => {},+ );+ }++ async respondMcpToolPermission(+ request: McpToolPermissionRequest,+ decision: McpToolPermissionDecision,+ ): Promise<void> {+ const commandId = globalThis.crypto.randomUUID();+ const command: PiMcpPermissionResponseCommand = {+ id: commandId,+ type: "mcp_permission_response",+ requestId: request.requestId,+ decision,+ };+ const result = await this.cloudTaskClient.sendCommand({+ taskId: this.context.taskId,+ id: commandId,+ runId: this.context.runId,+ apiHost: this.context.apiHost,+ teamId: this.context.teamId,+ method: "pi/rpc",+ params: { command },+ });+ if (!result.success) {+ throw new Error(result.error ?? "MCP permission response failed");+ }+ }+onConversationEvent(onEvent: (event: AgentConversationEvent) => void,onError: (error: unknown) => void,diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.tsindex fddca2b007f7..2f9999665d3d 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts@@ -1,7 +1,10 @@import type { PiRemoteRpcClient } from "@posthog/agent/pi/remote-rpc-client";import type { AuthService } from "@posthog/core/auth/auth";import type { TaskService } from "@posthog/core/task-detail/taskService";-import type { AgentConversationEvent } from "@posthog/shared";+import type {+ AgentConversationEvent,+ McpToolPermissionRequest,+} from "@posthog/shared";import { describe, expect, it, vi } from "vitest";import {PiOperationError,@@ -79,6 +82,40 @@ function createSession(): PiSession {}describe("PiSessionController", () => {+ it("queues concurrent MCP permission requests", async () => {+ const session = createSession();+ let onRequest: ((request: McpToolPermissionRequest) => void) | undefined;+ session.onMcpToolPermissionRequest = vi.fn((callback) => {+ onRequest = callback;+ return () => {};+ });+ session.respondMcpToolPermission = vi.fn(async () => {});+ const controller = createController(session);+ await controller.ensureConnected("task-1");+ const first = {+ requestId: "call-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: {},+ };+ const second = { ...first, requestId: "call-2" };++ onRequest?.(first);+ onRequest?.(second);++ expect(+ controller.store.getState().sessions["task-1"]?.mcpToolPermissionRequests+ .size,+ ).toBe(2);+ await controller.respondMcpToolPermission("task-1", first, "reject");+ expect(+ controller.store+ .getState()+ .sessions["task-1"]?.mcpToolPermissionRequests.has("call-2"),+ ).toBe(true);+ });+it.each([{text: "hello",diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.tsindex 8fb294effeb7..d9ff0d6a3acd 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts@@ -10,6 +10,8 @@ import type {import {type AgentConversationEvent,classifyPromptFailure,+ type McpToolPermissionDecision,+ type McpToolPermissionRequest,type PiMessagingMode,type PiRuntimeHealth,type PromptFailure,@@ -72,6 +74,14 @@ export interface PiSession {onError: (error: unknown) => void,onCloudStatus?: (status: TaskRunStatus) => void,): () => void;+ onMcpToolPermissionRequest?(+ onRequest: (request: McpToolPermissionRequest) => void,+ onError: (error: unknown) => void,+ ): () => void;+ respondMcpToolPermission?(+ request: McpToolPermissionRequest,+ decision: McpToolPermissionDecision,+ ): Promise<void>;onExtensionEvent?(onEvent: (event: PiExtensionEvent) => void,onError: (error: unknown) => void,@@ -223,6 +233,7 @@ export class PiSessionController {this.queueRevisions.delete(taskId);this.queuesToRestore.delete(taskId);this.activeTaskIds.delete(taskId);+ this.updateSession(taskId, { mcpToolPermissionRequests: new Map() });}async retry(taskId: string): Promise<void> {@@ -245,6 +256,21 @@ export class PiSessionController {}}+ async respondMcpToolPermission(+ taskId: string,+ request: McpToolPermissionRequest,+ decision: McpToolPermissionDecision,+ ): Promise<void> {+ const session = await this.getPiSession(taskId);+ if (!session.respondMcpToolPermission) {+ throw new Error("MCP tool permissions are unavailable for this session");+ }+ await session.respondMcpToolPermission(request, decision);+ const requests = new Map(this.getSession(taskId).mcpToolPermissionRequests);+ requests.delete(request.requestId);+ this.updateSession(taskId, { mcpToolPermissionRequests: requests });+ }+async clearQueue(taskId: string): Promise<PiQueueSnapshot> {try {const session = await this.getPiSession(taskId);@@ -607,7 +633,8 @@ export class PiSessionController {}let disposed = false;- let unsubscribe: (() => void) | undefined;+ let unsubscribeConversation: (() => void) | undefined;+ let unsubscribePermission: (() => void) | undefined;void this.getPiSession(taskId).then((session) => {if (disposed) {@@ -615,16 +642,29 @@ export class PiSessionController {}this.applyPersistedConfig(taskId, session);this.updateSession(taskId, { cloudStatus: session.cloudStatus });- unsubscribe = session.onConversationEvent(+ unsubscribeConversation = session.onConversationEvent((event) => this.handleEvent(taskId, event),(error) => this.applySessionError(taskId, error),(cloudStatus) => this.updateSession(taskId, { cloudStatus }),);+ unsubscribePermission = session.onMcpToolPermissionRequest?.(+ (request) => {+ const requests = new Map(+ this.getSession(taskId).mcpToolPermissionRequests,+ );+ requests.set(request.requestId, request);+ this.updateSession(taskId, {+ mcpToolPermissionRequests: requests,+ });+ },+ (error) => this.applySessionError(taskId, error),+ );}).catch((error) => this.applySessionError(taskId, error));this.subscriptions.set(taskId, () => {disposed = true;- unsubscribe?.();+ unsubscribeConversation?.();+ unsubscribePermission?.();});}@@ -735,6 +775,7 @@ export class PiSessionController {: undefined,authRestoring: currentSession.authRestoring,isBashRunning: false,+ mcpToolPermissionRequests: currentSession.mcpToolPermissionRequests,projectTrust,});diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts b/products/desktop/packages/core/src/pi-runtime/piSessionStore.tsindex 903199386fdf..301d14615fb2 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts@@ -9,6 +9,7 @@ import type {import type {AgentConversationEvent,GatewayLimitCause,+ McpToolPermissionRequest,PromptFailureKind,SessionStatus,TaskRunStatus,@@ -46,6 +47,7 @@ export interface PiControllerSessionState {error?: PiSessionError;authRestoring: boolean;isBashRunning: boolean;+ mcpToolPermissionRequests: Map<string, McpToolPermissionRequest>;projectTrust?: PiProjectTrustState;}@@ -69,6 +71,7 @@ export function createEmptyPiControllerSession(): PiControllerSessionState {thinkingLevelsLoaded: false,commands: [],queue: { steering: [], followUp: [] },+ mcpToolPermissionRequests: new Map(),authRestoring: false,isBashRunning: false,};diff --git a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.tsindex 6243aeb8396a..004eccf808b3 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationApiClient.ts@@ -1,9 +1,9 @@import type { TaskSessionStorageAccess } from "@posthog/api-client/posthog-client";import type {Adapter,- CloudMcpServerImport,CloudMcpServerRelayDesignation,CloudRunSource,+ McpServerConnection,PrAuthorshipMode,} from "@posthog/shared";import type { Task, TaskRun } from "@posthog/shared/domain-types";@@ -26,7 +26,7 @@ export interface CreateTaskRunClientOptions {runSource?: CloudRunSource;signalReportId?: string;initialPermissionMode?: string;- importedMcpServers?: CloudMcpServerImport[];+ importedMcpServers?: McpServerConnection[];relayedMcpServers?: CloudMcpServerRelayDesignation[];}diff --git a/products/desktop/packages/core/src/task-detail/taskInput.ts b/products/desktop/packages/core/src/task-detail/taskInput.tsindex 64544f9f3297..df9c7e0af666 100644--- a/products/desktop/packages/core/src/task-detail/taskInput.ts+++ b/products/desktop/packages/core/src/task-detail/taskInput.ts@@ -2,8 +2,8 @@ import { buildCloudTaskDescription } from "@posthog/core/editor/cloud-prompt";import type {Adapter,AgentRuntime,- CloudMcpServerImport,CloudMcpServerRelayDesignation,+ McpServerConnection,TaskCreationInput,WorkspaceMode,} from "@posthog/shared";@@ -38,7 +38,7 @@ export interface PrepareTaskInputOptions {autoPublishCloudRuns?: boolean;rtkEnabledCloud?: boolean;allowNoRepo?: boolean;- importedMcpServers?: CloudMcpServerImport[];+ importedMcpServers?: McpServerConnection[];relayedMcpServers?: CloudMcpServerRelayDesignation[];}diff --git a/products/desktop/packages/harness/src/extensions/mcp/config.test.ts b/products/desktop/packages/harness/src/extensions/mcp/config.test.tsindex 80889712dd2c..e3f42fe5e4b2 100644--- a/products/desktop/packages/harness/src/extensions/mcp/config.test.ts+++ b/products/desktop/packages/harness/src/extensions/mcp/config.test.ts@@ -2,7 +2,12 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { loadConfig, mergeRawConfigs, parseConfig } from "./config";+import {+ loadConfig,+ mergeRawConfigs,+ mergeRuntimeServers,+ parseConfig,+} from "./config";import { McpError } from "./errors";describe("parseConfig", () => {@@ -106,6 +111,25 @@ describe("mergeRawConfigs", () => {});});+describe("mergeRuntimeServers", () => {+ it("replaces file servers with runtime servers of the same name", () => {+ const merged = mergeRuntimeServers(+ parseConfig({ mcpServers: { shared: { command: "file" } } }, "file"),+ {+ shared: {+ args: [],+ command: "runtime",+ directTools: false,+ lifecycle: "lazy",+ transport: "stdio",+ },+ },+ );++ expect(merged.mcpServers.shared?.command).toBe("runtime");+ });+});+describe("loadConfig", () => {let dir: string;let globalPath: string;diff --git a/products/desktop/packages/harness/src/extensions/mcp/config.ts b/products/desktop/packages/harness/src/extensions/mcp/config.tsindex 93102b3acea4..5a5db9fa9673 100644--- a/products/desktop/packages/harness/src/extensions/mcp/config.ts+++ b/products/desktop/packages/harness/src/extensions/mcp/config.ts@@ -147,6 +147,20 @@ export function emptyConfig(): McpConfig {return mcpConfigSchema.parse({});}+export function mergeRuntimeServers(+ config: McpConfig,+ runtimeServers: Record<string, McpServerConfig> | undefined,+): McpConfig {+ if (!runtimeServers || Object.keys(runtimeServers).length === 0) {+ return config;+ }++ return {+ ...config,+ mcpServers: { ...config.mcpServers, ...runtimeServers },+ };+}+async function readJsonFile(path: string): Promise<unknown | null> {let text: string;try {diff --git a/products/desktop/packages/harness/src/extensions/mcp/extension.ts b/products/desktop/packages/harness/src/extensions/mcp/extension.tsindex 70f149590c08..2f88ef9d5603 100644--- a/products/desktop/packages/harness/src/extensions/mcp/extension.ts+++ b/products/desktop/packages/harness/src/extensions/mcp/extension.ts@@ -30,7 +30,7 @@ import { runOAuthFlow } from "./auth-flow";import { McpAuthStorage } from "./auth-storage";import { CallbackServer } from "./callback-server";import type { ConfigLoader, McpConfig } from "./config";-import { emptyConfig, loadConfig } from "./config";+import { emptyConfig, loadConfig, mergeRuntimeServers } from "./config";import { describeError } from "./errors";import { createMcpProxyTool } from "./proxy-tool";import type { TransportFactory } from "./server-manager";@@ -39,6 +39,7 @@ import { ToolBridge } from "./tool-bridge";import { McpToolCache } from "./tool-cache";export interface McpExtensionOptions {+ runtimeServers?: McpConfig["mcpServers"];/** Override config loading (tests). Default: read mcp.json files. */configLoader?: ConfigLoader;/** Override transport creation (tests). Default: stdio/http/sse via SDK. */@@ -228,9 +229,12 @@ export function createMcpExtension(pi.on("session_start", async (_event, ctx) => {let nextConfig: McpConfig;try {- nextConfig = await configLoader(ctx.cwd, {- includeProject: ctx.isProjectTrusted(),- });+ nextConfig = mergeRuntimeServers(+ await configLoader(ctx.cwd, {+ includeProject: ctx.isProjectTrusted(),+ }),+ options.runtimeServers,+ );} catch (err) {if (ctx.hasUI) {ctx.ui.notify(`mcp: config error — ${describeError(err)}`, "error");diff --git a/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.test.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.test.tsnew file mode 100644index 000000000000..2e76152c1d56--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.test.ts@@ -0,0 +1,116 @@+import type {+ ExtensionAPI,+ ToolCallEvent,+} from "@earendil-works/pi-coding-agent";+import type { McpToolPermissionDecision } from "@posthog/shared";+import { describe, expect, it, vi } from "vitest";+import { createPosthogMcpPolicyExtension } from "./extension";++function setup(approvalState: "approved" | "needs_approval" | "do_not_use") {+ let handler: ((event: ToolCallEvent) => Promise<unknown>) | undefined;+ const pi = {+ on: vi.fn((event: string, callback: typeof handler) => {+ if (event === "tool_call") {+ handler = callback;+ }+ }),+ } as unknown as ExtensionAPI;+ const requestMcpToolPermission = vi.fn<+ () => Promise<McpToolPermissionDecision>+ >(async () => "allow");++ createPosthogMcpPolicyExtension({+ mcpToolPolicies: [+ {+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ approvalState,+ },+ ],+ requestMcpToolPermission,+ })(pi);++ return {+ requestMcpToolPermission,+ call: (toolName: string, input: Record<string, unknown> = {}) =>+ handler?.({+ type: "tool_call",+ toolCallId: "call-1",+ toolName,+ input,+ } as ToolCallEvent),+ };+}++describe("posthog MCP policy extension", () => {+ it("allows approved tools without prompting", async () => {+ const runtime = setup("approved");++ await expect(+ runtime.call("mcp_Cloudflare_search"),+ ).resolves.toBeUndefined();+ expect(runtime.requestMcpToolPermission).not.toHaveBeenCalled();+ });++ it("prompts again after a one-time approval", async () => {+ const runtime = setup("needs_approval");++ await expect(+ runtime.call("mcp_Cloudflare_search"),+ ).resolves.toBeUndefined();+ await expect(+ runtime.call("mcp_Cloudflare_search"),+ ).resolves.toBeUndefined();+ expect(runtime.requestMcpToolPermission).toHaveBeenCalledTimes(2);+ expect(runtime.requestMcpToolPermission).toHaveBeenCalledWith({+ requestId: "call-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: {},+ });+ });++ it("remembers an always-allow approval", async () => {+ const runtime = setup("needs_approval");+ runtime.requestMcpToolPermission.mockResolvedValue("allow_always");++ await runtime.call("mcp_Cloudflare_search");+ await runtime.call("mcp_Cloudflare_search");++ expect(runtime.requestMcpToolPermission).toHaveBeenCalledOnce();+ });++ it("blocks a rejected approval", async () => {+ const runtime = setup("needs_approval");+ runtime.requestMcpToolPermission.mockResolvedValue("reject");++ await expect(runtime.call("mcp_Cloudflare_search")).resolves.toEqual({+ block: true,+ reason: "Permission rejected for Cloudflare.search.",+ });+ });++ it("blocks disabled tools", async () => {+ const runtime = setup("do_not_use");++ await expect(runtime.call("mcp_Cloudflare_search")).resolves.toEqual({+ block: true,+ reason: "The Cloudflare tool search is disabled in PostHog MCP settings.",+ });+ });++ it("handles calls through the MCP proxy tool", async () => {+ const runtime = setup("needs_approval");++ await runtime.call("mcp", {+ tool: "mcp_Cloudflare_search",+ args: '{"query":"workers"}',+ });++ expect(runtime.requestMcpToolPermission).toHaveBeenCalledWith(+ expect.objectContaining({ arguments: { query: "workers" } }),+ );+ });+});diff --git a/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.tsnew file mode 100644index 000000000000..b0ee9ab59daf--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/extension.ts@@ -0,0 +1,98 @@+import type {+ ExtensionAPI,+ ExtensionFactory,+ ToolCallEvent,+} from "@earendil-works/pi-coding-agent";+import type {+ McpToolPermissionDecision,+ McpToolPermissionRequest,+ McpToolPolicy,+} from "@posthog/shared";+import { buildToolName } from "../mcp/tool-bridge";++export interface PosthogMcpPolicyOptions {+ mcpToolPolicies?: McpToolPolicy[];+ requestMcpToolPermission?: (+ request: McpToolPermissionRequest,+ ) => Promise<McpToolPermissionDecision>;+}++function requestedArguments(event: ToolCallEvent): Record<string, unknown> {+ if (event.toolName !== "mcp" || typeof event.input.args !== "string") {+ return event.input;+ }++ try {+ const parsed: unknown = JSON.parse(event.input.args);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ } catch {+ return {};+ }+ return {};+}++function requestedToolName(event: ToolCallEvent): string | undefined {+ if (event.toolName === "mcp") {+ return typeof event.input.tool === "string" ? event.input.tool : undefined;+ }++ return event.toolName;+}++export function createPosthogMcpPolicyExtension(+ options: PosthogMcpPolicyOptions = {},+): ExtensionFactory {+ return (pi: ExtensionAPI) => {+ const policies = new Map(+ (options.mcpToolPolicies ?? []).map((policy) => [+ buildToolName("mcp", policy.serverName, policy.toolName),+ { ...policy },+ ]),+ );++ pi.on("tool_call", async (event) => {+ const piToolName = requestedToolName(event);+ const policy = piToolName ? policies.get(piToolName) : undefined;+ if (!policy || policy.approvalState === "approved") {+ return;+ }++ if (policy.approvalState === "do_not_use") {+ return {+ block: true,+ reason: `The ${policy.serverName} tool ${policy.toolName} is disabled in PostHog MCP settings.`,+ };+ }++ if (!options.requestMcpToolPermission) {+ return {+ block: true,+ reason: `The ${policy.serverName} tool ${policy.toolName} requires approval in PostHog MCP settings.`,+ };+ }++ const decision = await options.requestMcpToolPermission({+ requestId: event.toolCallId,+ serverName: policy.serverName,+ toolName: policy.toolName,+ installationId: policy.installationId,+ arguments: requestedArguments(event),+ ...(policy.description ? { description: policy.description } : {}),+ });+ if (decision === "reject") {+ return {+ block: true,+ reason: `Permission rejected for ${policy.serverName}.${policy.toolName}.`,+ };+ }++ if (decision === "allow_always") {+ policy.approvalState = "approved";+ }+ });+ };+}++export default createPosthogMcpPolicyExtension();diff --git a/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.ts b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.tsnew file mode 100644index 000000000000..8ab1b728d353--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/posthog-mcp-policy/index.ts@@ -0,0 +1 @@+export { default } from "./extension";diff --git a/products/desktop/packages/harness/src/extensions/registry.ts b/products/desktop/packages/harness/src/extensions/registry.tsindex ac813b00c482..4b614d61e8d0 100644--- a/products/desktop/packages/harness/src/extensions/registry.ts+++ b/products/desktop/packages/harness/src/extensions/registry.ts@@ -5,13 +5,19 @@ import type {} from "@earendil-works/pi-coding-agent";import type { HogBrandingOptions } from "./hog-branding/extension";import { createHogBrandingExtension } from "./hog-branding/extension";+import type { McpConfig } from "./mcp/config";import { createMcpExtension } from "./mcp/extension";+import type { PosthogMcpPolicyOptions } from "./posthog-mcp-policy/extension";+import { createPosthogMcpPolicyExtension } from "./posthog-mcp-policy/extension";import { createPosthogProviderExtension } from "./posthog-provider/extension";import type { PosthogProviderOptions } from "./posthog-provider/provider";import { createWebAccessExtension } from "./web-access/extension";export type HarnessExtensionOptions = PosthogProviderOptions &- HogBrandingOptions;+ HogBrandingOptions &+ PosthogMcpPolicyOptions & {+ runtimeMcpServers?: McpConfig["mcpServers"];+ };interface HarnessExtension {name: string;@@ -22,9 +28,15 @@ const EXTENSIONS: HarnessExtension[] = [{ name: "hog-branding", create: createHogBrandingExtension },{ name: "posthog-provider", create: createPosthogProviderExtension },{ name: "web-access", create: createWebAccessExtension },- // createMcpExtension's options are test seams (config loader, transport- // factory), not HarnessExtensionOptions, so drop the registry options.- { name: "mcp", create: () => createMcpExtension() },+ {+ name: "mcp",+ create: (options) =>+ createMcpExtension({ runtimeServers: options.runtimeMcpServers }),+ },+ {+ name: "posthog-mcp-policy",+ create: createPosthogMcpPolicyExtension,+ },];export const HARNESS_EXTENSION_NAMES: readonly string[] = EXTENSIONS.map(diff --git a/products/desktop/packages/harness/src/runtime.ts b/products/desktop/packages/harness/src/runtime.tsindex 8563a4e44dc4..961f9e845e4a 100644--- a/products/desktop/packages/harness/src/runtime.ts+++ b/products/desktop/packages/harness/src/runtime.ts@@ -71,6 +71,9 @@ export async function createHarnessRuntime(const {credentialStore,posthogOAuthCredentials,+ runtimeMcpServers: _runtimeMcpServers,+ mcpToolPolicies: _mcpToolPolicies,+ requestMcpToolPermission: _requestMcpToolPermission,projectTrusted,...runtimeOptions} = options;diff --git a/products/desktop/packages/harness/tsup.config.ts b/products/desktop/packages/harness/tsup.config.tsindex 2e9509969100..39706204dcce 100644--- a/products/desktop/packages/harness/tsup.config.ts+++ b/products/desktop/packages/harness/tsup.config.ts@@ -18,6 +18,8 @@ export default defineConfig({"src/extensions/posthog-provider/oauth.ts","src/extensions/posthog-provider/gateway.ts","src/extensions/posthog-provider/gateway-auth.ts",+ "src/extensions/posthog-mcp-policy/extension.ts",+ "src/extensions/posthog-mcp-policy/index.ts","src/extensions/background-jobs/extension.ts","src/extensions/background-jobs/index.ts","src/extensions/background-jobs/jobs.ts",diff --git a/products/desktop/packages/host-router/src/pi-session-factory.ts b/products/desktop/packages/host-router/src/pi-session-factory.tsindex 0b73cfea1239..34f4ad2b79b3 100644--- a/products/desktop/packages/host-router/src/pi-session-factory.ts+++ b/products/desktop/packages/host-router/src/pi-session-factory.ts@@ -44,6 +44,33 @@ class TrpcPiSession implements PiSession {return this.hostClient.piSession.clearQueue.mutate({ taskId: this.taskId });}+ onMcpToolPermissionRequest(+ onRequest: Parameters<+ NonNullable<PiSession["onMcpToolPermissionRequest"]>+ >[0],+ onError: Parameters<+ NonNullable<PiSession["onMcpToolPermissionRequest"]>+ >[1],+ ): () => void {+ const subscription =+ this.hostClient.piSession.onMcpToolPermissionRequest.subscribe(+ { taskId: this.taskId },+ { onData: onRequest, onError },+ );+ return () => subscription.unsubscribe();+ }++ respondMcpToolPermission(+ request: Parameters<NonNullable<PiSession["respondMcpToolPermission"]>>[0],+ decision: Parameters<NonNullable<PiSession["respondMcpToolPermission"]>>[1],+ ): Promise<void> {+ return this.hostClient.piSession.respondMcpToolPermission.mutate({+ taskId: this.taskId,+ request,+ decision,+ });+ }+getProjectTrust() {return this.hostClient.piSession.getProjectTrust.query({taskId: this.taskId,diff --git a/products/desktop/packages/host-router/src/routers/pi-session.router.ts b/products/desktop/packages/host-router/src/routers/pi-session.router.tsindex 740cbd5a8dd5..b853a5c58783 100644--- a/products/desktop/packages/host-router/src/routers/pi-session.router.ts+++ b/products/desktop/packages/host-router/src/routers/pi-session.router.ts@@ -12,6 +12,7 @@ import {piSessionRpcInput,piSessionStartOutput,piSessionTaskInput,+ respondMcpToolPermissionInput,resumePiSessionInput,setPiProjectTrustInput,startPiSessionInput,@@ -67,6 +68,35 @@ export const piSessionRouter = router({getService(ctx.container).clearQueue(input.taskId),),+ respondMcpToolPermission: publicProcedure+ .input(respondMcpToolPermissionInput)+ .mutation(({ ctx, input }) =>+ getService(ctx.container).respondMcpToolPermission(+ input.taskId,+ input.request,+ input.decision,+ ),+ ),++ onMcpToolPermissionRequest: publicProcedure+ .input(piSessionTaskInput)+ .subscription(async function* (opts) {+ const service = getService(opts.ctx.container);+ const iterable = service.toIterable("mcpPermissionRequest", {+ signal: opts.signal,+ });+ for (const request of service.getPendingMcpToolPermissions(+ opts.input.taskId,+ )) {+ yield request;+ }+ for await (const payload of iterable) {+ if (payload.taskId === opts.input.taskId) {+ yield payload.request;+ }+ }+ }),+getProjectTrust: publicProcedure.input(piSessionTaskInput).output(piProjectTrustOutput)diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.tsindex 3cb7f7df0334..bdeb1115a995 100644--- a/products/desktop/packages/shared/src/index.ts+++ b/products/desktop/packages/shared/src/index.ts@@ -213,12 +213,19 @@ export {} from "./inbox-types";export { EXTERNAL_LINKS } from "./links";export type {- CloudMcpServerImport,CloudMcpServerRelayDesignation,LocalMcpServerDescriptor,LocalMcpServerScope,LocalMcpTransport,+ McpServerConnection,} from "./local-mcp-domain";+export {+ MCP_TOOL_PERMISSION_OPTIONS,+ type McpToolApprovalState,+ type McpToolPermissionDecision,+ type McpToolPermissionRequest,+ type McpToolPolicy,+} from "./mcp-tool-policy-domain";export {formatMention,type MentionSegment,@@ -365,6 +372,7 @@ export {parseMcpToolName,posthogToolMeta,readAgentToolName,+ readMcpInstallationId,readMcpToolDescriptor,readMcpToolName,readParentToolCallId,diff --git a/products/desktop/packages/shared/src/local-mcp-domain.ts b/products/desktop/packages/shared/src/local-mcp-domain.tsindex c779a7c95e2f..489fc59afd87 100644--- a/products/desktop/packages/shared/src/local-mcp-domain.ts+++ b/products/desktop/packages/shared/src/local-mcp-domain.ts@@ -33,7 +33,7 @@ export interface LocalMcpServerDescriptor {* Included in the task-run creation payload for servers classified as* importable.*/-export interface CloudMcpServerImport {+export interface McpServerConnection {type: "http" | "sse";name: string;url: string;diff --git a/products/desktop/packages/shared/src/mcp-tool-policy-domain.ts b/products/desktop/packages/shared/src/mcp-tool-policy-domain.tsnew file mode 100644index 000000000000..4d101ef26db1--- /dev/null+++ b/products/desktop/packages/shared/src/mcp-tool-policy-domain.ts@@ -0,0 +1,29 @@+export type McpToolApprovalState = "approved" | "needs_approval" | "do_not_use";++export interface McpToolPolicy {+ serverName: string;+ toolName: string;+ installationId: string;+ approvalState: McpToolApprovalState;+ description?: string;+}++export interface McpToolPermissionRequest {+ requestId: string;+ serverName: string;+ toolName: string;+ installationId: string;+ arguments: Record<string, unknown>;+ description?: string;+}++export type McpToolPermissionDecision = "allow" | "allow_always" | "reject";++export const MCP_TOOL_PERMISSION_OPTIONS = [+ {+ kind: "allow_always",+ name: "Always allow",+ optionId: "allow_always",+ },+ { kind: "reject_once", name: "Reject", optionId: "reject" },+] as const;diff --git a/products/desktop/packages/shared/src/task-creation-domain.ts b/products/desktop/packages/shared/src/task-creation-domain.tsindex a3e9ca4644b8..c6731a64bc38 100644--- a/products/desktop/packages/shared/src/task-creation-domain.ts+++ b/products/desktop/packages/shared/src/task-creation-domain.ts@@ -4,8 +4,8 @@ import type { CloudRunSource, PrAuthorshipMode } from "./cloud";import type { Task } from "./domain-types";import type { ExecutionMode } from "./exec-types";import type {- CloudMcpServerImport,CloudMcpServerRelayDesignation,+ McpServerConnection,} from "./local-mcp-domain";import type { WorkspaceMode } from "./workspace";import type { Workspace } from "./workspace-domain";@@ -88,7 +88,7 @@ export interface TaskCreationInput {* the cloud sandbox in the run-creation payload. Cloud-only; local sessions* already read the user's config directly.*/- importedMcpServers?: CloudMcpServerImport[];+ importedMcpServers?: McpServerConnection[];/*** Desktop-only local MCP servers (stdio / private URL) designated for* relaying into the cloud run via the creating desktopdiff --git a/products/desktop/packages/shared/src/tool-meta.test.ts b/products/desktop/packages/shared/src/tool-meta.test.tsindex 77e0bdd02beb..be5bbf9aef3c 100644--- a/products/desktop/packages/shared/src/tool-meta.test.ts+++ b/products/desktop/packages/shared/src/tool-meta.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {parseMcpToolName,readAgentToolName,+ readMcpInstallationId,readMcpToolDescriptor,readMcpToolName,readParentToolCallId,@@ -93,6 +94,7 @@ describe("readMcpToolDescriptor / readMcpToolName", () => {posthog: {toolName: "ignored",mcp: { server: "posthog", tool: "exec" },+ mcpInstallationId: "installation-1",},};expect(readMcpToolDescriptor(meta)).toEqual({@@ -100,6 +102,7 @@ describe("readMcpToolDescriptor / readMcpToolName", () => {tool: "exec",});expect(readMcpToolName(meta)).toBe("mcp__posthog__exec");+ expect(readMcpInstallationId(meta)).toBe("installation-1");});it("parses the legacy claudeCode mcp__ name when there is no structured channel", () => {diff --git a/products/desktop/packages/shared/src/tool-meta.ts b/products/desktop/packages/shared/src/tool-meta.tsindex afbfde804914..5c339f12054f 100644--- a/products/desktop/packages/shared/src/tool-meta.ts+++ b/products/desktop/packages/shared/src/tool-meta.ts@@ -12,6 +12,7 @@ export interface PosthogToolMeta {toolName: string;/** Set only for MCP tool calls — the originating server + tool. */mcp?: { server: string; tool: string };+ mcpInstallationId?: string;/** Parent subagent tool call for nested activity. */parentToolCallId?: string;}@@ -91,3 +92,7 @@ export function readMcpToolName(meta: unknown): string | undefined {const mcp = readMcpToolDescriptor(meta);return mcp ? mcpToolKey(mcp) : undefined;}++export function readMcpInstallationId(meta: unknown): string | undefined {+ return asToolCallMeta(meta)?.posthog?.mcpInstallationId;+}diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsxindex c801138bd01a..ca45d57db84a 100644--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx@@ -29,10 +29,14 @@ import {EmptyTitle,Skeleton,} from "@posthog/quill";-import type { AgentConversationEvent } from "@posthog/shared";+import {+ type AgentConversationEvent,+ MCP_TOOL_PERMISSION_OPTIONS,+} from "@posthog/shared";import { useUsageLimitStore } from "@posthog/ui/features/billing/usageLimitStore";import { PromptInput } from "@posthog/ui/features/message-editor/components/PromptInput";import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";+import { PermissionSelector } from "@posthog/ui/features/permissions/PermissionSelector";import {CloudConnectionBanner,CloudStreamDisconnectedBanner,@@ -63,6 +67,7 @@ import { PiProjectTrustBanner } from "./PiProjectTrustBanner";import { PiQueuedMessagesDock } from "./PiQueuedMessagesDock";import { PiMessagingModeSelector } from "./PiSessionControls";import { PiSessionModelControls } from "./PiSessionModelControls";+import { buildPiMcpPermissionToolCall } from "./piMcpPermission";import {getPiPendingConfig,usePiPendingConfigStore,@@ -489,6 +494,9 @@ export function PiSessionView({const setMessagingMode = useMessagingModeStore((state) => state.setMode);const { isOnline } = useConnectivity();const promptRecallRef = useRef<PromptRecallHandler | null>(null);+ const mcpPermissionResponsePending = useRef(false);+ const [isMcpPermissionResponding, setIsMcpPermissionResponding] =+ useState(false);const handlePromptRecall = useCallback<PromptRecallHandler>((direction) => promptRecallRef.current?.(direction) ?? null,[],@@ -558,6 +566,30 @@ export function PiSessionView({usePiFailureNotice(session?.error);usePiFailureAcknowledgement(taskId, session?.error);+ const mcpPermission = session?.mcpToolPermissionRequests+ .values()+ .next().value;+ const respondMcpPermission = useCallback(+ (decision: "allow_always" | "reject") => {+ if (!mcpPermission || mcpPermissionResponsePending.current) {+ return;+ }++ mcpPermissionResponsePending.current = true;+ setIsMcpPermissionResponding(true);+ void piSessionController+ .respondMcpToolPermission(taskId, mcpPermission, decision)+ .catch((error) =>+ log.error("Failed to respond to MCP permission", error),+ )+ .finally(() => {+ mcpPermissionResponsePending.current = false;+ setIsMcpPermissionResponding(false);+ });+ },+ [mcpPermission, piSessionController, taskId],+ );+if (!session) {return <TaskDetailSkeleton />;}@@ -700,50 +732,67 @@ export function PiSessionView({)}</>)}- <PromptInput- sessionId={taskId}- toolbarEndSlot={<ContextUsageIndicator usage={contextUsage} />}- taskId={taskId}- repoPath={repoPath}- placeholder="Type a message..."- disabled={isCompacting}- isLoading={controlsPending}- submitDisabledExternal={- !sessionAvailable ||- !status ||- !isOnline ||- hasQueuedMessage ||- isAuthRestoring- }- submitTooltipOverride={- !isOnline- ? "No internet connection"- : isAuthRestoring- ? "Restoring authentication"- : hasQueuedMessage- ? "A message is already queued"- : undefined- }- enableBashMode- enableCommands- modelSelector={- <PiSessionModelControls- taskId={taskId}- taskRunId={taskRunId}- session={session}- controller={piSessionController}- isOnline={isOnline}- onError={handleControllerError}+ {mcpPermission ? (+ isMcpPermissionResponding ? (+ <Skeleton className="h-24 w-full" />+ ) : (+ <PermissionSelector+ toolCall={buildPiMcpPermissionToolCall(mcpPermission)}+ options={[...MCP_TOOL_PERMISSION_OPTIONS]}+ onSelect={(optionId) => {+ respondMcpPermission(+ optionId === "allow_always" ? "allow_always" : "reject",+ );+ }}+ onCancel={() => respondMcpPermission("reject")}/>- }- reasoningSelector={null}- messagingModeToggle={messagingModeToggle}- onToggleMessagingMode={toggleMessagingMode}- onPromptRecall={handlePromptRecall}- onSubmit={sendPrompt}- onBashCommand={runBashCommand}- onCancel={cancelPrompt}- />+ )+ ) : (+ <PromptInput+ sessionId={taskId}+ toolbarEndSlot={<ContextUsageIndicator usage={contextUsage} />}+ taskId={taskId}+ repoPath={repoPath}+ placeholder="Type a message..."+ disabled={isCompacting}+ isLoading={controlsPending}+ submitDisabledExternal={+ !sessionAvailable ||+ !status ||+ !isOnline ||+ hasQueuedMessage ||+ isAuthRestoring+ }+ submitTooltipOverride={+ !isOnline+ ? "No internet connection"+ : isAuthRestoring+ ? "Restoring authentication"+ : hasQueuedMessage+ ? "A message is already queued"+ : undefined+ }+ enableBashMode+ enableCommands+ modelSelector={+ <PiSessionModelControls+ taskId={taskId}+ taskRunId={taskRunId}+ session={session}+ controller={piSessionController}+ isOnline={isOnline}+ onError={handleControllerError}+ />+ }+ reasoningSelector={null}+ messagingModeToggle={messagingModeToggle}+ onToggleMessagingMode={toggleMessagingMode}+ onPromptRecall={handlePromptRecall}+ onSubmit={sendPrompt}+ onBashCommand={runBashCommand}+ onCancel={cancelPrompt}+ />+ )}{!isCloud && (<PiExtensionWidgetswidgets={currentExtensionState.widgets}diff --git a/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.test.ts b/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.test.tsnew file mode 100644index 000000000000..7780c82bd46f--- /dev/null+++ b/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.test.ts@@ -0,0 +1,33 @@+import {+ MCP_TOOL_PERMISSION_OPTIONS,+ readMcpInstallationId,+ readMcpToolDescriptor,+} from "@posthog/shared";+import { describe, expect, it } from "vitest";+import { buildPiMcpPermissionToolCall } from "./piMcpPermission";++describe("Pi MCP permission", () => {+ it("preserves the MCP descriptor and arguments for permission rendering", () => {+ const toolCall = buildPiMcpPermissionToolCall({+ requestId: "request-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ description: "Search Cloudflare resources",+ });++ expect(readMcpToolDescriptor(toolCall._meta)).toEqual({+ server: "Cloudflare",+ tool: "search",+ });+ expect(readMcpInstallationId(toolCall._meta)).toBe("installation-1");+ expect(toolCall.rawInput).toEqual({ query: "workers" });+ });++ it("does not offer one-time approval when approval must persist", () => {+ expect(+ MCP_TOOL_PERMISSION_OPTIONS.map((option) => option.optionId),+ ).toEqual(["allow_always", "reject"]);+ });+});diff --git a/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.ts b/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.tsnew file mode 100644index 000000000000..aa96bf5cd7fb--- /dev/null+++ b/products/desktop/packages/ui/src/features/pi-sessions/piMcpPermission.ts@@ -0,0 +1,29 @@+import type { McpToolPermissionRequest } from "@posthog/shared";+import { mcpToolKey, posthogToolMeta } from "@posthog/shared";+import type { PermissionToolCall } from "@posthog/ui/features/permissions/types";++export function buildPiMcpPermissionToolCall(+ request: McpToolPermissionRequest,+): PermissionToolCall {+ const mcp = { server: request.serverName, tool: request.toolName };++ return {+ toolCallId: request.requestId,+ title: `The agent wants to call ${request.toolName} (${request.serverName})`,+ kind: "other",+ content: request.description+ ? [+ {+ type: "content",+ content: { type: "text", text: request.description },+ },+ ]+ : [],+ rawInput: request.arguments,+ _meta: posthogToolMeta({+ toolName: mcpToolKey(mcp),+ mcp,+ mcpInstallationId: request.installationId,+ }),+ };+}diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.module.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.module.tsindex 5082b73a7e62..94846c157aca 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.module.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.module.ts@@ -1,9 +1,16 @@import { ContainerModule } from "inversify";import { AgentService } from "./agent";import { AgentAuthAdapter } from "./auth-adapter";-import { AGENT_AUTH_ADAPTER, AGENT_SERVICE } from "./identifiers";+import {+ AGENT_AUTH_ADAPTER,+ AGENT_SERVICE,+ MCP_SERVER_CONNECTION_SOURCE,+ MCP_TOOL_POLICY_UPDATER,+} from "./identifiers";export const agentModule = new ContainerModule(({ bind }) => {bind(AGENT_SERVICE).to(AgentService).inSingletonScope();bind(AGENT_AUTH_ADAPTER).to(AgentAuthAdapter).inSingletonScope();+ bind(MCP_SERVER_CONNECTION_SOURCE).toService(AGENT_AUTH_ADAPTER);+ bind(MCP_TOOL_POLICY_UPDATER).toService(AGENT_AUTH_ADAPTER);});diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex d7ae5cfa942b..9f92e5435cca 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -69,6 +69,7 @@ import {type CloudRegion,type ExecutionMode,isAuthError,+ type McpServerConnection,resolveCloudInitialPermissionMode,serializeError,TypedEventEmitter,@@ -1318,13 +1319,10 @@ If a repository IS genuinely required, attach one in this priority order:return `You are resuming a previous conversation after the native session could not be restored. Here is the conversation history from the previous session:\n\n${history}\n\nContinue from where you left off when responding to the user's next message.`;}- private async filterReachableMcpServers<- T extends {- name: string;- url: string;- headers: Array<{ name: string; value: string }>;- },- >(servers: T[], taskRunId: string): Promise<T[]> {+ private async filterReachableMcpServers<T extends McpServerConnection>(+ servers: T[],+ taskRunId: string,+ ): Promise<T[]> {const probed = await Promise.all(servers.map(async (server) => ({server,@@ -1345,10 +1343,9 @@ If a repository IS genuinely required, attach one in this priority order:return reachable;}- private async isMcpServerReachable(server: {- url: string;- headers: Array<{ name: string; value: string }>;- }): Promise<boolean> {+ private async isMcpServerReachable(+ server: Pick<McpServerConnection, "url" | "headers">,+ ): Promise<boolean> {const PROBE_TIMEOUT_MS = 2_000;try {const headers: Record<string, string> = {diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.tsindex 6028511bf52d..c91e27e6cdec 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.test.ts@@ -228,7 +228,52 @@ describe("AgentAuthAdapter", () => {});});- it("returns empty approvals when tool fetch fails", async () => {+ it("includes runtime servers whose tool policies are loaded", async () => {+ mockFetch+ .mockResolvedValueOnce({+ ok: true,+ json: () =>+ Promise.resolve({+ results: [+ {+ id: "inst-ready",+ url: "https://ready.example.com",+ proxy_url: "https://proxy.posthog.com/inst-ready/",+ name: "ready-server",+ display_name: "Ready Server",+ auth_type: "oauth",+ is_enabled: true,+ pending_oauth: false,+ needs_reauth: false,+ },+ ],+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: () =>+ Promise.resolve({+ results: [+ { tool_name: "search", approval_state: "needs_approval" },+ ],+ }),+ });++ const configuration = await adapter.getMcpRuntimeConfiguration();++ expect(configuration.servers.map((server) => server.name)).toEqual([+ "posthog",+ "ready-server",+ ]);+ expect(configuration.policies).toEqual([+ expect.objectContaining({+ installationId: "inst-ready",+ toolName: "search",+ }),+ ]);+ });++ it("omits runtime servers whose tool policies cannot be loaded", async () => {mockFetch.mockResolvedValueOnce({ok: true,@@ -249,11 +294,15 @@ describe("AgentAuthAdapter", () => {],}),})+ .mockResolvedValueOnce({ ok: false, status: 500 }).mockResolvedValueOnce({ ok: false, status: 500 });- const { toolApprovals } = await adapter.buildMcpServers(baseCredentials);+ const configuration = await adapter.getMcpRuntimeConfiguration();- expect(toolApprovals).toEqual({});+ expect(configuration.servers.map((server) => server.name)).toEqual([+ "posthog",+ ]);+ expect(configuration.policies).toEqual([]);});it("configures environment using the gateway proxy and current token", async () => {diff --git a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.tsindex 2a33faf29d3a..3357f202f305 100644--- a/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/auth-adapter.ts@@ -4,6 +4,7 @@ import {sanitizeMcpServerName,} from "@posthog/agent/adapters/claude/mcp/tool-metadata";import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";+import type { McpServerConnection, McpToolPolicy } from "@posthog/shared";import { inject, injectable } from "inversify";import type { AuthProxyService } from "../auth-proxy/auth-proxy";import { AUTH_PROXY_SERVICE } from "../auth-proxy/identifiers";@@ -22,13 +23,6 @@ function isValidApprovalState(value: string): value is McpToolApprovalState {return VALID_APPROVAL_STATES.has(value);}-export interface AcpMcpServer {- name: string;- type: "http";- url: string;- headers: Array<{ name: string; value: string }>;-}-export interface AgentPosthogConfig {apiUrl: string;getApiKey: () => Promise<string>;@@ -90,12 +84,41 @@ export class AgentAuthAdapter {return projectId === null ? null : { apiHost, projectId };}- async buildMcpServers(credentials: Credentials): Promise<{- servers: AcpMcpServer[];+ async getMcpRuntimeConfiguration(): Promise<{+ servers: McpServerConnection[];+ policies: McpToolPolicy[];+ }> {+ const credentials = await this.getCurrentCredentials();+ if (!credentials) {+ return { servers: [], policies: [] };+ }++ const configuration = await this.buildMcpServers(credentials, {+ refreshTools: true,+ });+ const policyInstallationIds = new Set(+ configuration.toolPolicies.map((policy) => policy.installationId),+ );+ const servers = configuration.servers.filter((server) => {+ const installationId = configuration.serverInstallationIds.get(server);+ return !installationId || policyInstallationIds.has(installationId);+ });++ return { servers, policies: configuration.toolPolicies };+ }++ async buildMcpServers(+ credentials: Credentials,+ options: { refreshTools?: boolean } = {},+ ): Promise<{+ servers: McpServerConnection[];toolApprovals: McpToolApprovals;toolInstallations: McpToolInstallations;+ toolPolicies: McpToolPolicy[];+ serverInstallationIds: Map<McpServerConnection, string>;}> {- const servers: AcpMcpServer[] = [];+ const servers: McpServerConnection[] = [];+ const serverInstallationIds = new Map<McpServerConnection, string>();const mcpUrl = this.getPostHogMcpUrl(credentials.apiHost);// Warm the token so authenticatedFetch() has something cached, but do not// bake it into the MCP config — the proxy injects a fresh one on every@@ -131,18 +154,33 @@ export class AgentAuthAdapter {`installation-${installation.id}`,installation.proxy_url,);- servers.push({+ const server: McpServerConnection = {name,type: "http",url: proxiedUrl,headers: [],- });+ };+ servers.push(server);+ serverInstallationIds.set(server, installation.id);}- const { approvals: toolApprovals, toolInstallations } =- await this.fetchMcpToolApprovals(credentials, installations);+ const {+ approvals: toolApprovals,+ toolInstallations,+ policies: toolPolicies,+ } = await this.fetchMcpToolApprovals(+ credentials,+ installations,+ options.refreshTools ?? false,+ );- return { servers, toolApprovals, toolInstallations };+ return {+ servers,+ toolApprovals,+ toolInstallations,+ toolPolicies,+ serverInstallationIds,+ };}async ensureGatewayProxy(apiHost: string): Promise<string> {@@ -222,6 +260,22 @@ export class AgentAuthAdapter {return host.endsWith("/") ? host.slice(0, -1) : host;}+ async approveMcpTool(+ installationId: string,+ toolName: string,+ ): Promise<void> {+ const credentials = await this.getCurrentCredentials();+ if (!credentials) {+ throw new Error("PostHog authentication is required");+ }+ await this.updateMcpToolApproval(+ credentials,+ installationId,+ toolName,+ "approved",+ );+ }+async updateMcpToolApproval(credentials: Credentials,installationId: string,@@ -250,13 +304,16 @@ export class AgentAuthAdapter {name: string;display_name: string;}>,+ refreshTools: boolean,): Promise<{approvals: McpToolApprovals;toolInstallations: McpToolInstallations;+ policies: McpToolPolicy[];}> {const baseUrl = this.getPostHogApiBaseUrl(credentials.apiHost);const approvals: McpToolApprovals = {};const toolInstallations: McpToolInstallations = {};+ const policies: McpToolPolicy[] = [];const results = await Promise.allSettled(installations.map(async (installation) => {@@ -264,18 +321,30 @@ export class AgentAuthAdapter {installation.name || installation.display_name || installation.url,);const toolsUrl = `${baseUrl}/api/environments/${credentials.projectId}/mcp_server_installations/${installation.id}/tools/`;+ const refreshUrl = `${toolsUrl}refresh/`;- const response = await this.authService.authenticatedFetch(+ let response = await this.authService.authenticatedFetch(fetch,- toolsUrl,- { headers: { "Content-Type": "application/json" } },+ refreshTools ? refreshUrl : toolsUrl,+ {+ method: refreshTools ? "POST" : "GET",+ headers: { "Content-Type": "application/json" },+ },);+ if (!response.ok && refreshTools) {+ response = await this.authService.authenticatedFetch(+ fetch,+ toolsUrl,+ { headers: { "Content-Type": "application/json" } },+ );+ }if (!response.ok) return [];const data = (await response.json()) as {results?: Array<{tool_name: string;approval_state?: string;+ description?: string;}>;};return (data.results ?? []).map((tool) => ({@@ -283,6 +352,7 @@ export class AgentAuthAdapter {installationId: installation.id,toolName: tool.tool_name,approvalState: tool.approval_state,+ description: tool.description,}));}),);@@ -306,10 +376,19 @@ export class AgentAuthAdapter {installationId: tool.installationId,toolName: tool.toolName,};+ if (tool.approvalState && isValidApprovalState(tool.approvalState)) {+ policies.push({+ serverName: tool.serverName,+ toolName: tool.toolName,+ installationId: tool.installationId,+ approvalState: tool.approvalState,+ ...(tool.description ? { description: tool.description } : {}),+ });+ }}}- return { approvals, toolInstallations };+ return { approvals, toolInstallations, policies };}private async fetchMcpInstallations(credentials: Credentials): Promise<diff --git a/products/desktop/packages/workspace-server/src/services/agent/identifiers.ts b/products/desktop/packages/workspace-server/src/services/agent/identifiers.tsindex db4b8805affc..bf22ad92eaa7 100644--- a/products/desktop/packages/workspace-server/src/services/agent/identifiers.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/identifiers.ts@@ -3,6 +3,12 @@ export const AGENT_AUTH_ADAPTER = Symbol.for("posthog.workspace.agentAuthAdapter",);export const AGENT_LOGGER = Symbol.for("posthog.workspace.agentLogger");+export const MCP_SERVER_CONNECTION_SOURCE = Symbol.for(+ "posthog.workspace.mcpServerConnectionSource",+);+export const MCP_TOOL_POLICY_UPDATER = Symbol.for(+ "posthog.workspace.mcpToolPolicyUpdater",+);export const AGENT_SLEEP_COORDINATOR = Symbol.for("posthog.workspace.agentSleepCoordinator",);diff --git a/products/desktop/packages/workspace-server/src/services/agent/ports.ts b/products/desktop/packages/workspace-server/src/services/agent/ports.tsindex 9ed476dd35dd..ccdd205e2b30 100644--- a/products/desktop/packages/workspace-server/src/services/agent/ports.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/ports.ts@@ -1,4 +1,8 @@-import type { CloudRegion } from "@posthog/shared";+import type {+ CloudRegion,+ McpServerConnection,+ McpToolPolicy,+} from "@posthog/shared";// Narrow ports inverting AgentService's dependencies on core/host services so it// can live in workspace-server without importing @posthog/core or apps/code.@@ -21,6 +25,17 @@ export interface AgentSleepCoordinator {release(activityId: string): void;}+export interface McpToolPolicyUpdater {+ approveMcpTool(installationId: string, toolName: string): Promise<void>;+}++export interface McpServerConnectionSource {+ getMcpRuntimeConfiguration(): Promise<{+ servers: McpServerConnection[];+ policies: McpToolPolicy[];+ }>;+}+export interface AgentMcpServerConnectionConfig {name: string;url: string;diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts b/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.tsindex fb7c6b39107a..624b1505186c 100644--- a/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts+++ b/products/desktop/packages/workspace-server/src/services/pi-session/identifiers.ts@@ -9,7 +9,9 @@ export interface PiRpcClientFactory {input: Pick<PiRpcClientOptions,"cwd" | "model" | "sessionFile" | "projectTrusted"- >,+ > & {+ taskId: string;+ },): Promise<PiRpcClient>;}diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.tsindex 8d552f6a6455..9d80f5cb823b 100644--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.test.ts@@ -178,6 +178,7 @@ describe("PiSessionService task session config", () => {{} as PiRuntimeFactory,{} as ITaskMetadataRepository,{} as ProcessTrackingService,+ { approveMcpTool: vi.fn() },rootLogger,);@@ -204,6 +205,8 @@ describe("PiSessionService start", () => {}),setThinkingLevel,prompt,+ onMcpToolPermissionRequest: vi.fn(),+ respondMcpToolPermission: vi.fn(),} as unknown as PiRpcClient;const runtimeFactory = {create: vi.fn(async () => ({@@ -220,10 +223,12 @@ describe("PiSessionService start", () => {register: vi.fn(),unregister: vi.fn(),} as unknown as ProcessTrackingService;+ const mcpToolPolicyUpdater = { approveMcpTool: vi.fn() };const service = new PiSessionService(runtimeFactory,taskMetadataRepository,processTracking,+ mcpToolPolicyUpdater,rootLogger,);@@ -238,6 +243,43 @@ describe("PiSessionService start", () => {expect(setThinkingLevel.mock.invocationCallOrder[0]).toBeLessThan(prompt.mock.invocationCallOrder[0],);++ const request = {+ requestId: "call-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ };+ const onRequest = (+ client.onMcpToolPermissionRequest as ReturnType<typeof vi.fn>+ ).mock.calls[0]?.[0];+ onRequest(request);+ expect(service.getPendingMcpToolPermissions("task-1")).toEqual([request]);+ await service.respondMcpToolPermission("task-1", request, "allow");++ expect(mcpToolPolicyUpdater.approveMcpTool).not.toHaveBeenCalled();+ expect(client.respondMcpToolPermission).toHaveBeenCalledWith(+ "call-1",+ "allow",+ );++ const persistentRequest = { ...request, requestId: "call-2" };+ onRequest(persistentRequest);+ await service.respondMcpToolPermission(+ "task-1",+ persistentRequest,+ "allow_always",+ );++ expect(mcpToolPolicyUpdater.approveMcpTool).toHaveBeenCalledWith(+ "installation-1",+ "search",+ );+ expect(client.respondMcpToolPermission).toHaveBeenCalledWith(+ "call-2",+ "allow_always",+ );});});@@ -269,6 +311,7 @@ describe("PiSessionService project trust", () => {sessionId: "session-1",})),setThinkingLevel: vi.fn(async () => {}),+ onMcpToolPermissionRequest: vi.fn(),prompt: vi.fn(async () => {}),}) as unknown as PiRpcClient,);@@ -299,6 +342,7 @@ describe("PiSessionService project trust", () => {runtimeFactory,metadata,processTracking,+ { approveMcpTool: vi.fn() },rootLogger,);@@ -313,6 +357,7 @@ describe("PiSessionService project trust", () => {hasProjectResources: true,});expect(runtimeFactory.create).toHaveBeenLastCalledWith({+ taskId: "task-1",cwd: worktree,model: undefined,projectTrusted: false,@@ -333,6 +378,7 @@ describe("PiSessionService project trust", () => {});expect(clients[0].stop).toHaveBeenCalledTimes(2);expect(runtimeFactory.create).toHaveBeenLastCalledWith({+ taskId: "task-1",cwd: worktree,sessionFile: "/tmp/session.jsonl",projectTrusted: false,@@ -351,6 +397,7 @@ describe("PiSessionService project trust", () => {projectTrustPath: repository,});expect(runtimeFactory.create).toHaveBeenLastCalledWith({+ taskId: "task-1",cwd: worktree,sessionFile: "/tmp/session.jsonl",projectTrusted: true,@@ -371,6 +418,7 @@ describe("PiSessionService project trust", () => {register: vi.fn(),unregister: vi.fn(),} as unknown as ProcessTrackingService,+ { approveMcpTool: vi.fn() },rootLogger,);@@ -399,6 +447,7 @@ describe("PiSessionService extension UI", () => {sessionFile: `/tmp/session-${index}.jsonl`,sessionId: `session-${index}`,}),+ onMcpToolPermissionRequest: vi.fn(),prompt: vi.fn().mockResolvedValue(undefined),respondToExtensionUI: vi.fn().mockResolvedValue(undefined),})) as unknown as PiRpcClient[];@@ -425,6 +474,7 @@ describe("PiSessionService extension UI", () => {register: vi.fn(),unregister: vi.fn(),} as unknown as ProcessTrackingService,+ { approveMcpTool: vi.fn() },rootLogger,);const abortController = new AbortController();@@ -563,6 +613,7 @@ describe("PiSessionService RPC request pinning", () => {requestResolvers.push(resolve);}),),+ onMcpToolPermissionRequest: vi.fn(),getQueue: vi.fn(() =>new Promise<{ steering: string[]; followUp: string[] }>((resolve) => {@@ -578,6 +629,7 @@ describe("PiSessionService RPC request pinning", () => {sessionFile: "/tmp/second.jsonl",}),send: vi.fn(),+ onMcpToolPermissionRequest: vi.fn(),} as unknown as PiRpcClient;const thirdClient = {start: vi.fn().mockResolvedValue(undefined),@@ -587,6 +639,7 @@ describe("PiSessionService RPC request pinning", () => {sessionFile: "/tmp/third.jsonl",}),send: vi.fn(),+ onMcpToolPermissionRequest: vi.fn(),} as unknown as PiRpcClient;const clients = [firstClient, secondClient, thirdClient];const runtimeFactory = {@@ -621,6 +674,7 @@ describe("PiSessionService RPC request pinning", () => {runtimeFactory,taskMetadataRepository,processTracking,+ { approveMcpTool: vi.fn() },rootLogger,);diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.tsindex af29edac35ba..a75b6e45c422 100644--- a/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts+++ b/products/desktop/packages/workspace-server/src/services/pi-session/pi-session.ts@@ -25,12 +25,16 @@ import {} from "@posthog/harness/project-trust";import {type AgentConversationEvent,+ type McpToolPermissionDecision,+ type McpToolPermissionRequest,type PiRuntimeHealth,TypedEventEmitter,} from "@posthog/shared";import { inject, injectable } from "inversify";import { TASK_METADATA_REPOSITORY } from "../../db/identifiers";import type { ITaskMetadataRepository } from "../../db/repositories/task-metadata-repository";+import { MCP_TOOL_POLICY_UPDATER } from "../agent/identifiers";+import type { McpToolPolicyUpdater } from "../agent/ports";import { PROCESS_TRACKING_SERVICE } from "../process-tracking/identifiers";import type { ProcessTrackingService } from "../process-tracking/process-tracking";import { PI_RUNTIME_FACTORY, type PiRuntimeFactory } from "./identifiers";@@ -69,6 +73,10 @@ type PiSessionEvent = Parameters<Parameters<PiRpcClient["onEvent"]>[0]>[0];interface PiSessionEvents {event: { taskId: string; event: AgentConversationEvent };+ mcpPermissionRequest: {+ taskId: string;+ request: McpToolPermissionRequest;+ };}type PiExtensionDialogRequest = Extract<@@ -82,6 +90,7 @@ interface PiSessionExtensionEvents {interface ManagedPiSession {client: PiRpcClient;+ pendingMcpPermissions: Map<string, McpToolPermissionRequest>;runtime: PiRuntime;cwd: string;projectTrustPath: string;@@ -240,6 +249,8 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {private readonly taskMetadataRepository: ITaskMetadataRepository,@inject(PROCESS_TRACKING_SERVICE)private readonly processTracking: ProcessTrackingService,+ @inject(MCP_TOOL_POLICY_UPDATER)+ private readonly mcpToolPolicyUpdater: McpToolPolicyUpdater,@inject(ROOT_LOGGER) rootLogger: RootLogger,) {super();@@ -261,6 +272,7 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {await assertProjectTrustAppliesToCwd(projectTrustPath, input.cwd);const projectTrust = readPiProjectTrust(projectTrustPath, input.cwd);const runtime = await this.runtimeFactory.create({+ taskId: input.taskId,cwd: input.cwd,model: input.model,projectTrusted: projectTrust.trusted,@@ -329,6 +341,7 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {await assertProjectTrustAppliesToCwd(projectTrustPath, input.cwd);const projectTrust = readPiProjectTrust(projectTrustPath, input.cwd);const runtime = await this.runtimeFactory.create({+ taskId: input.taskId,cwd: input.cwd,sessionFile,projectTrusted: projectTrust.trusted,@@ -361,6 +374,30 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {});}+ getPendingMcpToolPermissions(taskId: string): McpToolPermissionRequest[] {+ return [...this.requireSession(taskId).pendingMcpPermissions.values()];+ }++ async respondMcpToolPermission(+ taskId: string,+ request: McpToolPermissionRequest,+ decision: McpToolPermissionDecision,+ ): Promise<void> {+ const session = this.requireSession(taskId);+ const pending = session.pendingMcpPermissions.get(request.requestId);+ if (!pending) {+ throw new Error(`No pending MCP permission ${request.requestId}`);+ }+ if (decision === "allow_always") {+ await this.mcpToolPolicyUpdater.approveMcpTool(+ pending.installationId,+ pending.toolName,+ );+ }+ session.pendingMcpPermissions.delete(request.requestId);+ session.client.respondMcpToolPermission(request.requestId, decision);+ }+getQueue(taskId: string): Promise<PiQueueSnapshot> {return this.withActiveRequest(taskId, (session) =>session.client.getQueue(),@@ -619,8 +656,15 @@ export class PiSessionService extends TypedEventEmitter<PiSessionEvents> {cwd: string,projectTrustPath: string,): ManagedPiSession {+ const pendingMcpPermissions = new Map<string, McpToolPermissionRequest>();+ runtime.client.onMcpToolPermissionRequest((request) => {+ pendingMcpPermissions.set(request.requestId, request);+ this.emit("mcpPermissionRequest", { taskId, request });+ });+const session: ManagedPiSession = {client: runtime.client,+ pendingMcpPermissions,runtime,cwd,projectTrustPath,diff --git a/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts b/products/desktop/packages/workspace-server/src/services/pi-session/schemas.tsindex d9de294781b9..3b8109e07224 100644--- a/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts+++ b/products/desktop/packages/workspace-server/src/services/pi-session/schemas.ts@@ -54,6 +54,21 @@ export const setPiProjectTrustInput = z.object({trusted: z.boolean(),});+export const mcpToolPermissionRequestSchema = z.object({+ requestId: z.string(),+ serverName: z.string(),+ toolName: z.string(),+ installationId: z.string(),+ arguments: z.record(z.string(), z.unknown()),+ description: z.string().optional(),+});++export const respondMcpToolPermissionInput = z.object({+ taskId: z.string(),+ request: mcpToolPermissionRequestSchema,+ decision: z.enum(["allow", "allow_always", "reject"]),+});+export const piSessionConfigInput = z.object({ downloadUrl: z.url() });export const piSessionConfigOutput = z