Skip to content

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

fix(desktop): handle refresh_session in the codex adapter (#83199)

Alessandro Pogliaghieb98f8c24adf
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
index 71136b5d8370..616ff19efc49 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts
@@ -4391,4 +4391,82 @@ describe("CodexAppServerAgent", () => {
1,
);
});
+
+ it("refresh_session rebinds mcp_servers on the live thread, keeping local tools", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "t" } },
+ "thread/resume": { thread: { id: "t" } },
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+ await agent.newSession({
+ cwd: "/r",
+ mcpServers: [
+ {
+ name: "posthog",
+ url: "https://mcp.posthog.com/mcp",
+ headers: [{ name: "Authorization", value: "Bearer stale" }],
+ },
+ ],
+ } as unknown as NewSessionRequest);
+
+ await expect(
+ agent.extMethod("_posthog/refresh_session", {
+ mcpServers: [
+ {
+ name: "posthog",
+ url: "https://mcp.posthog.com/mcp",
+ headers: [{ name: "Authorization", value: "Bearer fresh" }],
+ },
+ ],
+ }),
+ ).resolves.toEqual({ refreshed: true });
+
+ const mcpServersFor = (method: string) =>
+ (
+ stub.requests.find((r) => r.method === method)?.params as
+ | { config?: { mcp_servers?: Record<string, unknown> } }
+ | undefined
+ )?.config?.mcp_servers ?? {};
+ const resume = stub.requests.find((r) => r.method === "thread/resume");
+ expect(resume?.params).toMatchObject({ threadId: "t" });
+ expect(mcpServersFor("thread/resume").posthog).toMatchObject({
+ http_headers: { Authorization: "Bearer fresh" },
+ });
+ expect(Object.keys(mcpServersFor("thread/resume"))).toEqual(
+ Object.keys(mcpServersFor("thread/start")),
+ );
+ });
+
+ it("refresh_session is refused while a turn is in flight", async () => {
+ const stub = makeStubRpc({
+ "thread/start": { thread: { id: "thr_1" } },
+ "turn/start": { turn: { id: "turn_1" } },
+ });
+ const { client } = makeFakeClient();
+ const agent = new CodexAppServerAgent(client, {
+ processOptions: { binaryPath: "/x/codex" },
+ rpcFactory: stub.factory,
+ });
+ await agent.newSession({ cwd: "/r" } as unknown as NewSessionRequest);
+
+ const promptDone = agent.prompt({
+ sessionId: "thr_1",
+ prompt: [{ type: "text", text: "hello" }],
+ } as unknown as PromptRequest);
+ await waitUntil(() => stub.requests.some((r) => r.method === "turn/start"));
+
+ await expect(
+ agent.extMethod("_posthog/refresh_session", { mcpServers: [] }),
+ ).rejects.toMatchObject({ code: -32002 });
+ expect(stub.requests.some((r) => r.method === "thread/resume")).toBe(false);
+
+ stub.emit("turn/completed", {
+ turn: { id: "turn_1", status: "completed" },
+ });
+ await promptDone;
+ });
});
diff --git a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
index f60a0b580659..6255dd9b9e7d 100644
--- a/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
+++ b/products/desktop/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts
@@ -8,6 +8,7 @@ import type {
ListSessionsResponse,
LoadSessionRequest,
LoadSessionResponse,
+ McpServer,
NewSessionRequest,
NewSessionResponse,
PromptRequest,
@@ -28,7 +29,9 @@ import {
serializeError,
} from "@posthog/shared";
import {
+ isMethod,
type NativeGoalState,
+ POSTHOG_METHODS,
POSTHOG_NOTIFICATIONS,
} from "../../acp-extensions";
import type { ModelInfo } from "../../gateway-models";
@@ -246,6 +249,10 @@ export class CodexAppServerAgent extends BaseAcpAgent {
private additionalDirectories?: string[];
/** The session workspace stays writable when extra roots are applied per turn. */
private workspaceDirectory?: string;
+ private threadSetup?: {
+ meta?: AppServerSessionMeta;
+ developerInstructions?: string;
+ };
/** The in-flight turn's <proposed_plan>, streamed or completed (drives the implement handoff). */
private planProposal?: { itemId: string; text: string };
/** Structured plan tool call already emitted while the proposal streams. */
@@ -418,6 +425,78 @@ export class CodexAppServerAgent extends BaseAcpAgent {
return { sessionId: threadId, configOptions: this.config.options };
}
+ async extMethod(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<Record<string, unknown>> {
+ if (!isMethod(method, POSTHOG_METHODS.REFRESH_SESSION)) {
+ throw RequestError.methodNotFound(method);
+ }
+ if (params.mcpServers === undefined) {
+ throw new RequestError(
+ -32602,
+ "refresh_session requires at least one refreshable field (e.g. mcpServers)",
+ );
+ }
+ if (!Array.isArray(params.mcpServers)) {
+ throw new RequestError(
+ -32602,
+ "refresh_session: mcpServers must be an array",
+ );
+ }
+ if (!this.threadId) {
+ throw new RequestError(
+ -32002,
+ "Cannot refresh session before a thread is started",
+ );
+ }
+ if (this.turns.isPending || this.nativeGoalTurnId) {
+ throw new RequestError(
+ -32002,
+ "Cannot refresh session while a prompt turn is in flight",
+ );
+ }
+
+ await this.refreshThreadMcpServers(params.mcpServers as McpServer[]);
+ return { refreshed: true };
+ }
+
+ private async refreshThreadMcpServers(servers: McpServer[]): Promise<void> {
+ const cwd = this.workspaceDirectory;
+ let localTools: ReturnType<typeof buildLocalToolsServer> = null;
+ try {
+ localTools = buildLocalToolsServer(
+ { cwd },
+ this.localToolsMeta(this.threadSetup?.meta),
+ );
+ } catch (err) {
+ this.logger.warn(
+ "local-tools server unavailable on refresh; continuing without it",
+ { error: String(err) },
+ );
+ }
+ const mcpServers = toCodexMcpServers(
+ [...servers, ...(localTools ? [localTools] : [])],
+ { gatePosthogExec: true },
+ );
+ const config = buildThreadConfig(mcpServers, this.additionalDirectories);
+ const developerInstructions = this.threadSetup?.developerInstructions;
+
+ await this.rpc.request(APP_SERVER_METHODS.THREAD_RESUME, {
+ model: this.config.model,
+ cwd,
+ threadId: this.threadId,
+ ...(developerInstructions ? { developerInstructions } : {}),
+ ...(config ? { config } : {}),
+ });
+
+ this.logger.info("Refreshed codex thread MCP servers", {
+ threadId: this.threadId,
+ mcpServers: mcpServers ? Object.keys(mcpServers) : [],
+ hasLocalTools: !!localTools,
+ });
+ }
+
/** Replay a resumed thread's persisted turns (from the thread/resume response) as session updates. */
private replayHistory(thread: AppServerThread | undefined): void {
if (!this.sessionId || !thread?.turns?.length) return;
@@ -513,6 +592,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {
].filter((s): s is string => !!s),
),
].join("\n\n");
+ this.threadSetup = { meta: params.meta, developerInstructions };
// Degrade gracefully: an unresolvable bundled local-tools script skips it with a
// warning rather than killing thread setup.
let localTools: ReturnType<typeof buildLocalToolsServer> = null;