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(mcp): deliver UI app CSP so hosts stop rendering blank frames (#76899)

Adam Bowker00ae2815689e
diff --git a/products/desktop/packages/core/src/mcp-apps/mcp-apps.test.ts b/products/desktop/packages/core/src/mcp-apps/mcp-apps.test.ts
index 70f3a6a44ad3..5add0de42eff 100644
--- a/products/desktop/packages/core/src/mcp-apps/mcp-apps.test.ts
+++ b/products/desktop/packages/core/src/mcp-apps/mcp-apps.test.ts
@@ -1,6 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { McpAppsService } from "./mcp-apps";
-import { McpAppsServiceEvent, type McpServerConnectionConfig } from "./schemas";
+import {
+ McpAppsServiceEvent,
+ type McpResourceUiMeta,
+ type McpServerConnectionConfig,
+} from "./schemas";
function makeLogger() {
const scopedLog = {
@@ -120,8 +124,13 @@ describe("McpAppsService config resolver", () => {
const UI_MIME_TYPE = "text/html;profile=mcp-app";
const REVIEW_URI = "ui://posthog/loops-review.html";
const REVIEW_CSP = { connectDomains: ["https://us.posthog.com"] };
+const REVIEW_PERMISSIONS = { clipboardWrite: {} };
-function makeClient() {
+const UI_META = { ui: { csp: REVIEW_CSP, permissions: REVIEW_PERMISSIONS } };
+
+// metaOn picks whether this client advertises `_meta.ui` on resources/list or
+// on the read response.
+function makeClient(metaOn: "list" | "read" = "list") {
return {
close: vi.fn(async () => {}),
listTools: vi.fn(async () => ({
@@ -134,10 +143,27 @@ function makeClient() {
],
})),
listResources: vi.fn(async () => ({
- resources: [{ uri: REVIEW_URI, _meta: { ui: { csp: REVIEW_CSP } } }],
+ resources: [
+ {
+ uri: REVIEW_URI,
+ ...(metaOn === "list" ? { _meta: UI_META } : {}),
+ } as { uri: string; _meta?: McpResourceUiMeta["_meta"] },
+ ],
})),
readResource: vi.fn(async ({ uri }: { uri: string }) => ({
- contents: [{ uri, mimeType: UI_MIME_TYPE, text: "<html></html>" }],
+ contents: [
+ {
+ uri,
+ mimeType: UI_MIME_TYPE,
+ text: "<html></html>",
+ ...(metaOn === "read" ? { _meta: UI_META } : {}),
+ } as {
+ uri: string;
+ mimeType: string;
+ text: string;
+ _meta?: McpResourceUiMeta["_meta"];
+ },
+ ],
})),
};
}
@@ -149,6 +175,15 @@ function connectClient(service: McpAppsService, client = makeClient()) {
return client;
}
+function connectClients(
+ service: McpAppsService,
+ clients: Record<string, ReturnType<typeof makeClient>>,
+) {
+ vi.spyOn(internals(service), "createConnection").mockImplementation(
+ async (c) => ({ name: c.name, client: clients[c.name], transport: {} }),
+ );
+}
+
describe("McpAppsService lazy discovery", () => {
let service: McpAppsService;
@@ -318,14 +353,41 @@ describe("McpAppsService lazy discovery", () => {
expect(resource?.html).toBe("<html></html>");
});
- it("attaches discovered CSP metadata on direct URI fetches", async () => {
- service.setConfigResolver(async (name) => {
- service.addServerConfigs([config(name)]);
- });
- connectClient(service);
+ it.each([
+ ["the resource listing", "list"],
+ ["the read response", "read"],
+ ] as const)(
+ "attaches UI metadata advertised on %s to direct URI fetches",
+ async (_label, metaOn) => {
+ service.setConfigResolver(async (name) => {
+ service.addServerConfigs([config(name)]);
+ });
+ connectClient(service, makeClient(metaOn));
+
+ const resource = await service.getUiResourceByUri("posthog", REVIEW_URI);
+ expect(resource?.csp).toEqual(REVIEW_CSP);
+ expect(resource?.permissions).toEqual(REVIEW_PERMISSIONS);
+ },
+ );
+
+ it("prefers read-response CSP over the listing CSP", async () => {
+ service.setServerConfigs([config("posthog")]);
+ const readCsp = { connectDomains: ["https://eu.posthog.com"] };
+ const client = makeClient("list");
+ client.readResource.mockImplementation(async ({ uri }) => ({
+ contents: [
+ {
+ uri,
+ mimeType: UI_MIME_TYPE,
+ text: "<html></html>",
+ _meta: { ui: { csp: readCsp } },
+ },
+ ],
+ }));
+ connectClient(service, client);
const resource = await service.getUiResourceByUri("posthog", REVIEW_URI);
- expect(resource?.csp).toEqual(REVIEW_CSP);
+ expect(resource?.csp).toEqual(readCsp);
});
it("returns an uncached resource when the metadata warm-up fails", async () => {
@@ -342,4 +404,53 @@ describe("McpAppsService lazy discovery", () => {
expect(second?.html).toBe("<html></html>");
expect(client.readResource).toHaveBeenCalledTimes(2);
});
+
+ it("caches a read-advertised resource despite a failed warm-up", async () => {
+ service.setServerConfigs([config("posthog")]);
+ const client = makeClient("read");
+ client.listTools.mockRejectedValue(new Error("listTools broken"));
+ connectClient(service, client);
+
+ const first = await service.getUiResourceByUri("posthog", REVIEW_URI);
+ expect(first?.csp).toEqual(REVIEW_CSP);
+ await service.getUiResourceByUri("posthog", REVIEW_URI);
+ expect(client.readResource).toHaveBeenCalledTimes(1);
+ });
+
+ it("caches same-URI resources separately per server", async () => {
+ service.setServerConfigs([config("posthog"), config("staging")]);
+ const stagingClient = makeClient();
+ stagingClient.readResource.mockImplementation(async ({ uri }) => ({
+ contents: [{ uri, mimeType: UI_MIME_TYPE, text: "<html>staging</html>" }],
+ }));
+ connectClients(service, { posthog: makeClient(), staging: stagingClient });
+
+ const posthogResource = await service.getUiResourceByUri(
+ "posthog",
+ REVIEW_URI,
+ );
+ const stagingResource = await service.getUiResourceByUri(
+ "staging",
+ REVIEW_URI,
+ );
+
+ expect(posthogResource?.html).toBe("<html></html>");
+ expect(stagingResource?.html).toBe("<html>staging</html>");
+ });
+
+ it("evicts only the disconnected server's cached resources", async () => {
+ service.setServerConfigs([config("posthog"), config("staging")]);
+ const posthogClient = makeClient();
+ const stagingClient = makeClient();
+ connectClients(service, { posthog: posthogClient, staging: stagingClient });
+
+ await service.getUiResourceByUri("posthog", REVIEW_URI);
+ await service.getUiResourceByUri("staging", REVIEW_URI);
+ await service.disconnectServer("posthog");
+
+ await service.getUiResourceByUri("staging", REVIEW_URI);
+ expect(stagingClient.readResource).toHaveBeenCalledTimes(1);
+ await service.getUiResourceByUri("posthog", REVIEW_URI);
+ expect(posthogClient.readResource).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/products/desktop/packages/core/src/mcp-apps/mcp-apps.ts b/products/desktop/packages/core/src/mcp-apps/mcp-apps.ts
index 0169efab120e..de4a48c407be 100644
--- a/products/desktop/packages/core/src/mcp-apps/mcp-apps.ts
+++ b/products/desktop/packages/core/src/mcp-apps/mcp-apps.ts
@@ -87,6 +87,21 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
this.log = rootLogger.scope("mcp-apps-service");
}
+ // Two servers can serve different content at the same ui:// URI, so every
+ // per-resource cache (resource, meta, pending fetch) keys on server + URI.
+ private resourceKey(serverName: string, resourceUri: string): string {
+ return `${serverName}\n${resourceUri}`;
+ }
+
+ private evictServerEntries<T>(map: Map<string, T>, serverName: string): void {
+ const keyPrefix = this.resourceKey(serverName, "");
+ for (const key of map.keys()) {
+ if (key.startsWith(keyPrefix)) {
+ map.delete(key);
+ }
+ }
+ }
+
/**
* Store server configs for lazy connections later.
* No connections are created at this point.
@@ -212,7 +227,10 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
for (const resource of resourcesList.resources) {
const meta = resource as McpResourceUiMeta;
if (meta._meta?.ui) {
- this.resourceMetaCache.set(resource.uri, meta);
+ this.resourceMetaCache.set(
+ this.resourceKey(serverName, resource.uri),
+ meta,
+ );
}
}
}
@@ -412,7 +430,8 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
serverName: string,
resourceUri: string,
): Promise<McpUiResource | null> {
- const cached = this.resourceCache.get(resourceUri);
+ const key = this.resourceKey(serverName, resourceUri);
+ const cached = this.resourceCache.get(key);
if (cached) {
this.log.debug("fetchUiResourceByUri: cache hit", {
serverName,
@@ -421,7 +440,7 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
return cached;
}
- const pendingFetch = this.pendingFetches.get(resourceUri);
+ const pendingFetch = this.pendingFetches.get(key);
if (pendingFetch) {
this.log.debug("fetchUiResourceByUri: joining pending fetch", {
serverName,
@@ -435,11 +454,11 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
resourceUri,
});
const fetchPromise = this.doFetchUiResource(serverName, resourceUri);
- this.pendingFetches.set(resourceUri, fetchPromise);
+ this.pendingFetches.set(key, fetchPromise);
try {
return await fetchPromise;
} finally {
- this.pendingFetches.delete(resourceUri);
+ this.pendingFetches.delete(key);
}
}
@@ -501,23 +520,39 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
return null;
}
- const resourceMeta = this.resourceMetaCache.get(resourceUri);
+ const resourceMeta = this.resourceMetaCache.get(
+ this.resourceKey(serverName, resourceUri),
+ );
+ // Read-response ui.csp/ui.permissions win; the listing-derived cache is a
+ // fallback for servers that only advertise them at registration.
+ const readUi = (textContent as { _meta?: McpResourceUiMeta["_meta"] })._meta
+ ?.ui;
+ const listUi = resourceMeta?._meta?.ui;
+ const csp = readUi?.csp ?? listUi?.csp;
+ const permissions = readUi?.permissions ?? listUi?.permissions;
const resource: McpUiResource = {
uri: resourceUri,
name: resourceMeta?.name,
mimeType: UI_MIME_TYPE,
- csp: resourceMeta?._meta?.ui?.csp,
- permissions: resourceMeta?._meta?.ui?.permissions,
+ csp,
+ permissions,
html: textContent.text,
serverName,
};
// A failed warm-up with no known metadata may have produced a CSP-less
// copy; leave it uncached so a later fetch can attach the real CSP.
- const cacheable = warmed || resourceMeta !== undefined;
+ const cacheable =
+ warmed ||
+ resourceMeta !== undefined ||
+ csp !== undefined ||
+ permissions !== undefined;
if (cacheable) {
- this.resourceCache.set(resourceUri, resource);
+ this.resourceCache.set(
+ this.resourceKey(serverName, resourceUri),
+ resource,
+ );
}
this.log.info("Lazily fetched UI resource", {
serverName,
@@ -680,24 +715,14 @@ export class McpAppsService extends TypedEventEmitter<McpAppsServiceEvents> {
}
this.connections.delete(serverName);
- // Clean up associations and cached resources for this server
- const urisToEvict = new Set<string>();
for (const [key, assoc] of this.toolAssociations) {
if (assoc.serverName === serverName) {
- urisToEvict.add(assoc.resourceUri);
this.toolAssociations.delete(key);
}
}
- // Only evict cached resources not referenced by remaining associations
- const stillReferenced = new Set(
- [...this.toolAssociations.values()].map((a) => a.resourceUri),
- );
- for (const uri of urisToEvict) {
- if (!stillReferenced.has(uri)) {
- this.resourceCache.delete(uri);
- }
- }
+ this.evictServerEntries(this.resourceCache, serverName);
+ this.evictServerEntries(this.resourceMetaCache, serverName);
}
async cleanup(): Promise<void> {
diff --git a/services/mcp/src/resources/ui-apps.ts b/services/mcp/src/resources/ui-apps.ts
index f48e0eb2e294..32b23abecc42 100644
--- a/services/mcp/src/resources/ui-apps.ts
+++ b/services/mcp/src/resources/ui-apps.ts
@@ -106,7 +106,9 @@ function registerApp(
const meta = buildUiAppResourceMeta(baseUrl, context.env.POSTHOG_MCP_APPS_ANALYTICS_BASE_URL)
const html = buildAppStubHtml(appDir, baseUrl)
- server.registerResource(name, uri, { mimeType: RESOURCE_MIME_TYPE, description }, async (uri) => {
+ // `_meta` goes on the registration too, so a host that builds the iframe CSP from
+ // `resources/list` alone still allows the stub's script and stylesheet from `baseUrl`.
+ server.registerResource(name, uri, { mimeType: RESOURCE_MIME_TYPE, description, _meta: meta }, async (uri) => {
return {
contents: [
{
diff --git a/services/mcp/tests/tools/projects.integration.test.ts b/services/mcp/tests/tools/projects.integration.test.ts
index 88dd29e3193a..1a85c8058c16 100644
--- a/services/mcp/tests/tools/projects.integration.test.ts
+++ b/services/mcp/tests/tools/projects.integration.test.ts
@@ -20,6 +20,7 @@ import type { Context } from '@/tools/types'
describe('Projects', { concurrent: false }, () => {
let context: Context
+ let testPropertyName: string
const createdResources: CreatedResources = {
featureFlags: [],
insights: [],
@@ -148,35 +149,32 @@ describe('Projects', { concurrent: false }, () => {
const updateTool = updatePropertyDefinitionTool()
beforeAll(async () => {
- // Ensure the $browser property definition exists before running update tests.
- // In a fresh test environment no events have been ingested, so property
- // definitions don't exist yet. We create one via the API if missing.
const searchResult = await context.api.request<{ results: { name: string }[] }>({
method: 'GET',
path: `/api/projects/${TEST_PROJECT_ID}/property_definitions/`,
- query: { properties: '$browser', type: 'event' },
+ query: { type: 'event', limit: 100 },
})
- const exists = searchResult.results.some((def) => def.name === '$browser')
- if (!exists) {
- await context.api.request({
- method: 'POST',
- path: `/api/projects/${TEST_PROJECT_ID}/property_definitions/`,
- body: { name: '$browser', type: 1, is_numerical: false },
- })
+
+ const propertyDefinition =
+ searchResult.results.find((def) => def.name === '$browser') ?? searchResult.results[0]
+ if (!propertyDefinition) {
+ throw new Error('Expected the test project to have at least one event property definition')
}
+
+ testPropertyName = propertyDefinition.name
})
it('should update property definition description', async () => {
const testDescription = `Test description ${uuidv4()}`
const result = await updateTool.handler(context, {
- propertyName: '$browser',
+ propertyName: testPropertyName,
type: 'event',
data: { description: testDescription },
})
const propertyDef = parseToolResponse(result)
expect(propertyDef.description).toBe(testDescription)
- expect(propertyDef.name).toBe('$browser')
+ expect(propertyDef.name).toBe(testPropertyName)
// The definition-detail route is keyed by id, not name, so the link must carry the id
expect(propertyDef.url).toContain(`/data-management/properties/${propertyDef.id}`)
})
@@ -184,7 +182,7 @@ describe('Projects', { concurrent: false }, () => {
it('should update property definition tags', async () => {
const testTag = `test-tag-${uuidv4().slice(0, 8)}`
const result = await updateTool.handler(context, {
- propertyName: '$browser',
+ propertyName: testPropertyName,
type: 'event',
data: { tags: [testTag] },
})
@@ -195,7 +193,7 @@ describe('Projects', { concurrent: false }, () => {
it('should update verified status', async () => {
const result = await updateTool.handler(context, {
- propertyName: '$browser',
+ propertyName: testPropertyName,
type: 'event',
data: { verified: true },
})
@@ -208,7 +206,7 @@ describe('Projects', { concurrent: false }, () => {
const testDescription = `Multi-field test ${uuidv4()}`
const testTag = `multi-tag-${uuidv4().slice(0, 8)}`
const result = await updateTool.handler(context, {
- propertyName: '$browser',
+ propertyName: testPropertyName,
type: 'event',
data: {
description: testDescription,
diff --git a/services/mcp/tests/unit/ui-apps.test.ts b/services/mcp/tests/unit/ui-apps.test.ts
index 6860de0c6600..849a528f65a5 100644
--- a/services/mcp/tests/unit/ui-apps.test.ts
+++ b/services/mcp/tests/unit/ui-apps.test.ts
@@ -144,6 +144,18 @@ describe('ui-apps', () => {
expect(result.contents[0]._meta['openai/widgetCSP'].resource_domains).toContain('https://mcp.posthog.com')
})
+ it('advertises the CSP on the registration so resources/list carries it', async () => {
+ const { registerUiAppResources } = await import('@/resources/ui-apps')
+ const server = createMockServer()
+ const context = createMockContext({ MCP_APPS_BASE_URL: 'https://mcp.posthog.com' })
+
+ await registerUiAppResources(server as any, context as any)
+
+ const registration = server.registerResource.mock.calls[0]![2]
+ expect(registration._meta.ui.csp.resourceDomains).toContain('https://mcp.posthog.com')
+ expect(registration._meta['openai/widgetCSP'].resource_domains).toContain('https://mcp.posthog.com')
+ })
+
it('includes analytics URL in CSP when set', async () => {
const { registerUiAppResources } = await import('@/resources/ui-apps')
const server = createMockServer()