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): stop refreshing the PostHog token on a connected server's auth error (#80616)

Peter Kirkham83ae03eaecba
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.ts
index c91e27e6cdec..2286fcc66971 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
@@ -169,6 +169,8 @@ describe("AgentAuthAdapter", () => {
expect(deps.mcpProxy.register).toHaveBeenCalledWith(
"installation-inst-2",
"https://proxy.posthog.com/inst-2/",
+ // An auth failure here is about the vendor's credential, not the user's PostHog token.
+ { credentialOwner: "installation" },
);
expect(servers).toEqual(
expect.arrayContaining([
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.ts
index b3f7e190c69e..62188b09bd3d 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
@@ -154,6 +154,7 @@ export class AgentAuthAdapter {
const proxiedUrl = this.mcpProxy.register(
`installation-${installation.id}`,
installation.proxy_url,
+ { credentialOwner: "installation" },
);
const server: McpServerConnection = {
name,
diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
index ce365751ce7a..6ca0d6afc47c 100644
--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.test.ts
@@ -256,6 +256,31 @@ describe("McpProxyService", () => {
expect(authServiceMock.authenticatedFetch).toHaveBeenCalledTimes(2);
});
+ it("passes an installation credential failure through without refreshing", async () => {
+ // The failing credential belongs to the connected vendor, not to PostHog, so a
+ // PostHog token refresh cannot fix it and the retry only hides the real error.
+ authServiceMock.authenticatedFetch.mockResolvedValue(
+ new Response(JSON.stringify({ error: "Authentication failed" }), {
+ status: 401,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+
+ await service.start();
+ const proxyUrl = service.register(
+ "installation-abc",
+ "https://app.posthog.com/api/environments/1/mcp_server_installations/abc/proxy/",
+ { credentialOwner: "installation" },
+ );
+
+ const res = await fetch(proxyUrl, { method: "POST", body: "payload" });
+
+ expect(res.status).toBe(401);
+ expect(await res.text()).toBe('{"error":"Authentication failed"}');
+ expect(authServiceMock.refreshAccessToken).not.toHaveBeenCalled();
+ expect(authServiceMock.authenticatedFetch).toHaveBeenCalledTimes(1);
+ });
+
it("does not retry when the body looks healthy", async () => {
authServiceMock.authenticatedFetch.mockResolvedValue(
new Response('{"ok":true}', {
diff --git a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
index b2a6fd45880d..bee677d32ad5 100644
--- a/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
+++ b/products/desktop/packages/workspace-server/src/services/mcp-proxy/mcp-proxy.ts
@@ -30,12 +30,27 @@ function truncateRequestBody(body: RequestInit["body"]): string | undefined {
* before forwarding, but any local process can still use it to issue requests
* on the user's behalf — acceptable for a single-user desktop app.
*/
+/**
+ * Whose credential an auth failure from a target is about.
+ *
+ * `posthog` targets answer for the user's PostHog token, so a stale one is worth
+ * refreshing and retrying. An `installation` target proxies a connected third-party
+ * server, and its auth failures are about that vendor's token — refreshing the PostHog
+ * token cannot fix one, and retrying buries the real reason.
+ */
+export type McpProxyCredentialOwner = "posthog" | "installation";
+
+interface McpProxyTarget {
+ url: string;
+ credentialOwner: McpProxyCredentialOwner;
+}
+
@injectable()
export class McpProxyService {
private server: http.Server | null = null;
private port: number | null = null;
private startPromise: Promise<void> | null = null;
- private targets = new Map<string, string>();
+ private targets = new Map<string, McpProxyTarget>();
private readonly log: ScopedLogger;
@@ -88,11 +103,18 @@ export class McpProxyService {
* should be passed to the MCP transport. Subsequent registrations with the
* same ID overwrite the target.
*/
- register(id: string, targetUrl: string): string {
+ register(
+ id: string,
+ targetUrl: string,
+ options: { credentialOwner?: McpProxyCredentialOwner } = {},
+ ): string {
if (!this.port) {
throw new Error("MCP proxy not started");
}
- this.targets.set(id, targetUrl);
+ this.targets.set(id, {
+ url: targetUrl,
+ credentialOwner: options.credentialOwner ?? "posthog",
+ });
return `http://127.0.0.1:${this.port}/${encodeURIComponent(id)}`;
}
@@ -136,7 +158,7 @@ export class McpProxyService {
}
const suffix = rest.join("/");
- const targetBase = target.replace(/\/+$/, "");
+ const targetBase = target.url.replace(/\/+$/, "");
const targetUrl =
(suffix ? `${targetBase}/${suffix}` : targetBase) + incoming.search;
@@ -181,10 +203,10 @@ export class McpProxyService {
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
fetchOptions.body = Buffer.concat(chunks);
- this.forwardRequest(id, targetUrl, fetchOptions, res);
+ this.forwardRequest(id, targetUrl, fetchOptions, res, target);
});
} else {
- this.forwardRequest(id, targetUrl, fetchOptions, res);
+ this.forwardRequest(id, targetUrl, fetchOptions, res, target);
}
}
@@ -193,6 +215,7 @@ export class McpProxyService {
url: string,
options: RequestInit,
res: http.ServerResponse,
+ target: McpProxyTarget,
): Promise<void> {
this.log.debug("MCP proxy forwarding request", {
id,
@@ -214,6 +237,19 @@ export class McpProxyService {
const bodyText = buf.toString("utf8");
if (this.isAuthErrorBody(bodyText, response.status)) {
+ if (target.credentialOwner === "installation") {
+ this.log.warn(
+ "Connected MCP server rejected the request; its stored credential needs reconnecting in PostHog",
+ {
+ id,
+ url,
+ status: response.status,
+ body: bodyText.slice(0, 2000),
+ },
+ );
+ this.writeBufferedResponse(response, buf, res);
+ return;
+ }
this.log.warn("MCP auth failure — refreshing token and retrying", {
id,
url,