Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 77 additions & 2 deletions apps/code/src/main/services/agent/auth-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ describe("AgentAuthAdapter", () => {
});

it("builds the default PostHog MCP server routed through the local proxy", async () => {
const servers = await adapter.buildMcpServers(baseCredentials);
const { servers } = await adapter.buildMcpServers(baseCredentials);

expect(deps.mcpProxy.register).toHaveBeenCalledWith(
"posthog",
Expand Down Expand Up @@ -126,7 +126,7 @@ describe("AgentAuthAdapter", () => {
}),
});

const servers = await adapter.buildMcpServers(baseCredentials);
const { servers } = await adapter.buildMcpServers(baseCredentials);

expect(deps.mcpProxy.register).toHaveBeenCalledWith(
"installation-inst-2",
Expand All @@ -143,6 +143,81 @@ describe("AgentAuthAdapter", () => {
);
});

it("fetches tool approval states for installations", async () => {
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
results: [
{
id: "inst-3",
url: "https://tools.example.com",
proxy_url: "https://proxy.posthog.com/inst-3/",
name: "tool-server",
display_name: "Tool Server",
auth_type: "oauth",
is_enabled: true,
pending_oauth: false,
needs_reauth: false,
},
],
}),
})
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
results: [
{ tool_name: "read_data", approval_state: "approved" },
{ tool_name: "write_data", approval_state: "do_not_use" },
{ tool_name: "query", approval_state: "needs_approval" },
],
}),
});

const { toolApprovals, toolInstallations } =
await adapter.buildMcpServers(baseCredentials);

expect(toolApprovals).toEqual({
"mcp__tool-server__read_data": "approved",
"mcp__tool-server__write_data": "do_not_use",
"mcp__tool-server__query": "needs_approval",
});
expect(toolInstallations["mcp__tool-server__read_data"]).toEqual({
installationId: "inst-3",
toolName: "read_data",
});
});

it("returns empty approvals when tool fetch fails", async () => {
mockFetch
.mockResolvedValueOnce({
ok: true,
json: () =>
Promise.resolve({
results: [
{
id: "inst-4",
url: "https://broken.example.com",
proxy_url: "https://proxy.posthog.com/inst-4/",
name: "broken-server",
display_name: "Broken Server",
auth_type: "oauth",
is_enabled: true,
pending_oauth: false,
needs_reauth: false,
},
],
}),
})
.mockResolvedValueOnce({ ok: false, status: 500 });

const { toolApprovals } = await adapter.buildMcpServers(baseCredentials);

expect(toolApprovals).toEqual({});
});

it("configures environment using the gateway proxy and current token", async () => {
await adapter.configureProcessEnv({
credentials: baseCredentials,
Expand Down
124 changes: 122 additions & 2 deletions apps/code/src/main/services/agent/auth-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { delimiter } from "node:path";
import {
type McpToolApprovalState,
type McpToolApprovals,
sanitizeMcpServerName,
} from "@posthog/agent/adapters/claude/mcp/tool-metadata";
import { getLlmGatewayUrl } from "@posthog/agent/posthog-api";
import { inject, injectable } from "inversify";
import { MAIN_TOKENS } from "../../di/tokens";
Expand All @@ -10,6 +15,15 @@ import type { Credentials } from "./schemas";

const log = logger.scope("agent-auth-adapter");

const VALID_APPROVAL_STATES = new Set([
"approved",
"needs_approval",
"do_not_use",
]);
function isValidApprovalState(value: string): value is McpToolApprovalState {
return VALID_APPROVAL_STATES.has(value);
}

export interface AcpMcpServer {
name: string;
type: "http";
Expand All @@ -24,6 +38,15 @@ export interface AgentPosthogConfig {
projectId: number;
}

/** Reference linking an MCP tool key back to its server installation for backend updates. */
export interface McpToolInstallationRef {
installationId: string;
toolName: string;
}

/** Maps MCP tool keys (e.g. `mcp__server__tool`) to their installation reference. */
export type McpToolInstallations = Record<string, McpToolInstallationRef>;

interface ConfigureProcessEnvInput {
credentials: Credentials;
mockNodeDir: string;
Expand Down Expand Up @@ -51,7 +74,11 @@ export class AgentAuthAdapter {
};
}

async buildMcpServers(credentials: Credentials): Promise<AcpMcpServer[]> {
async buildMcpServers(credentials: Credentials): Promise<{
servers: AcpMcpServer[];
toolApprovals: McpToolApprovals;
toolInstallations: McpToolInstallations;
}> {
const servers: AcpMcpServer[] = [];
const mcpUrl = this.getPostHogMcpUrl(credentials.apiHost);
// Warm the token so authenticatedFetch() has something cached, but do not
Expand Down Expand Up @@ -95,7 +122,10 @@ export class AgentAuthAdapter {
});
}

return servers;
const { approvals: toolApprovals, toolInstallations } =
await this.fetchMcpToolApprovals(credentials, installations);

return { servers, toolApprovals, toolInstallations };
}

async ensureGatewayProxy(apiHost: string): Promise<string> {
Expand Down Expand Up @@ -154,6 +184,96 @@ export class AgentAuthAdapter {
return host.endsWith("/") ? host.slice(0, -1) : host;
}

async updateMcpToolApproval(
credentials: Credentials,
installationId: string,
toolName: string,
approvalState: McpToolApprovalState,
): Promise<void> {
const baseUrl = this.getPostHogApiBaseUrl(credentials.apiHost);
const url = `${baseUrl}/api/environments/${credentials.projectId}/mcp_server_installations/${installationId}/tools/${encodeURIComponent(toolName)}/`;
const response = await this.authService.authenticatedFetch(fetch, url, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ approval_state: approvalState }),
});
if (!response.ok) {
throw new Error(
`Failed to update MCP tool approval (${response.status}) for ${toolName} on installation ${installationId}`,
);
}
}

private async fetchMcpToolApprovals(
credentials: Credentials,
installations: Array<{
id: string;
url: string;
name: string;
display_name: string;
}>,
): Promise<{
approvals: McpToolApprovals;
toolInstallations: McpToolInstallations;
}> {
const baseUrl = this.getPostHogApiBaseUrl(credentials.apiHost);
const approvals: McpToolApprovals = {};
const toolInstallations: McpToolInstallations = {};

const results = await Promise.allSettled(
installations.map(async (installation) => {
const serverName = sanitizeMcpServerName(
installation.name || installation.display_name || installation.url,
);
const toolsUrl = `${baseUrl}/api/environments/${credentials.projectId}/mcp_server_installations/${installation.id}/tools/`;

const 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;
}>;
};
return (data.results ?? []).map((tool) => ({
serverName,
installationId: installation.id,
toolName: tool.tool_name,
approvalState: tool.approval_state,
}));
}),
);

for (const result of results) {
if (result.status !== "fulfilled") {
log.warn("Failed to fetch tool approvals for an installation", {
error:
result.reason instanceof Error
? result.reason.message
: String(result.reason),
});
continue;
}
for (const tool of result.value) {
const key = `mcp__${tool.serverName}__${tool.toolName}`;
if (tool.approvalState && isValidApprovalState(tool.approvalState)) {
approvals[key] = tool.approvalState;
}
toolInstallations[key] = {
installationId: tool.installationId,
toolName: tool.toolName,
};
}
}

return { approvals, toolInstallations };
}

private async fetchMcpInstallations(credentials: Credentials): Promise<
Array<{
id: string;
Expand Down
22 changes: 14 additions & 8 deletions apps/code/src/main/services/agent/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,18 @@ function createMockDependencies() {
refreshApiKey: vi.fn().mockResolvedValue("fresh-access-token"),
projectId: credentials.projectId,
})),
buildMcpServers: vi.fn().mockResolvedValue([
{
name: "posthog",
type: "http",
url: "https://mcp.posthog.com/mcp",
headers: [],
},
]),
buildMcpServers: vi.fn().mockResolvedValue({
servers: [
{
name: "posthog",
type: "http",
url: "https://mcp.posthog.com/mcp",
headers: [],
},
],
toolApprovals: {},
toolInstallations: {},
}),
},
mcpAppsService: {
setServerConfigs: vi.fn(),
Expand Down Expand Up @@ -301,6 +305,8 @@ describe("AgentService", () => {
config: {},
promptPending: false,
inFlightMcpToolCalls: new Map(),
mcpToolApprovals: {},
toolInstallations: {},
...overrides,
});
}
Expand Down
Loading
Loading