: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(experiments): attach and view variant screenshots from MCP (#116145)
posthog[bot]68343eef4108
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex c1ad8762ee55..3971854b99ce 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -7115,6 +7115,7 @@ export type UploadedMediaListPurpose = (typeof UploadedMediaListPurpose)[keyof texport const UploadedMediaListPurpose = {Canvas: 'canvas',Email: 'email',+ Experiment: 'experiment',} as const/**@@ -7126,6 +7127,7 @@ export type UploadedMediaCreateBodyPurpose =export const UploadedMediaCreateBodyPurpose = {Email: 'email',Canvas: 'canvas',+ Experiment: 'experiment',} as constexport type UploadedMediaCreateBody = {diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex c56ac30a60c6..8bcba1098eff 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -1269,7 +1269,7 @@ export const TerminalNetplaySignalCreateBody = /* @__PURE__ */ zod.object({export const UploadedMediaCreateBody = /* @__PURE__ */ zod.object({image: zod.instanceof(File).describe('Image file. Must be under 4MB and a real, decodable image.'),purpose: zod- .enum(['email', 'canvas'])+ .enum(['email', 'canvas', 'experiment']).optional().describe('Library to add this image to. Omit to upload without joining a library (as dashboard text cards and notebooks do).'diff --git a/posthog/api/test/test_uploaded_media.py b/posthog/api/test/test_uploaded_media.pyindex 1ac01d2e0acb..c1ab220f0dd6 100644--- a/posthog/api/test/test_uploaded_media.py+++ b/posthog/api/test/test_uploaded_media.py@@ -617,9 +617,10 @@ class TestMediaLibraryAPI(APIBaseTest):assert media_location is not Nonereturn media_id, media_location- def test_complete_upload_verifies_and_activates_the_pending_upload(self) -> None:+ @parameterized.expand([("email",), ("experiment",)])+ def test_complete_upload_verifies_and_activates_the_pending_upload(self, purpose: str) -> None:with self.settings(OBJECT_STORAGE_ENABLED=True, OBJECT_STORAGE_MEDIA_UPLOADS_FOLDER=TEST_BUCKET):- media_id, media_location = self._start_upload()+ media_id, media_location = self._start_upload(purpose=purpose)with open(get_path_to("a-small-but-valid.gif"), "rb") as image:gif_bytes = image.read()object_storage.write(media_location, gif_bytes)@@ -635,7 +636,7 @@ class TestMediaLibraryAPI(APIBaseTest):media = UploadedMedia.objects.get(id=media_id)assert media.pending is False- list_response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose=email")+ list_response = self.client.get(f"/api/projects/{self.team.id}/uploaded_media/?purpose={purpose}")assert [item["id"] for item in list_response.json()["results"]] == [media_id]self.client.logout()diff --git a/posthog/models/uploaded_media.py b/posthog/models/uploaded_media.pyindex a453cfcd19b5..1a00be574de0 100644--- a/posthog/models/uploaded_media.py+++ b/posthog/models/uploaded_media.py@@ -30,7 +30,8 @@ class ObjectStorageUnavailable(Exception):# second library that nothing lists, and give the caller no sign that it had.MEDIA_PURPOSE_EMAIL = "email"MEDIA_PURPOSE_CANVAS = "canvas"-MEDIA_PURPOSES = [MEDIA_PURPOSE_EMAIL, MEDIA_PURPOSE_CANVAS]+MEDIA_PURPOSE_EXPERIMENT = "experiment"+MEDIA_PURPOSES = [MEDIA_PURPOSE_EMAIL, MEDIA_PURPOSE_CANVAS, MEDIA_PURPOSE_EXPERIMENT]# These uploads must never be served through the unauthenticated /uploaded_media route.# Their owning product provides an authenticated download endpoint instead.diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yamlindex 0cbe818ea50c..083ffd486ca7 100644--- a/products/experiments/mcp/tools.yaml+++ b/products/experiments/mcp/tools.yaml@@ -563,7 +563,8 @@ tools:custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure;use it in SQL instead of hardcoding either name. When it is $feature_flag_called, also read$experiment_exposure (event IN ('$feature_flag_called', '$experiment_exposure')), and count persons, not- rows).+ rows). variant_screenshot_urls maps each variant key to the viewable URLs of its screenshots in+ parameters.variant_screenshot_media_ids.param_overrides:id:cast: string-int@@ -571,6 +572,7 @@ tools:- experimentId- experiment_idui_app: experiment+ hooks: experiments/getExperimentHooksresponse:exclude:- saved_metrics.*.effective_querydiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 6aa5327371f1..99a7b9cae5da 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5275,7 +5275,7 @@}},"experiment-get": {- "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, running_time_calculation (minimum detectable effect, recommended running time and sample size), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name. When it is $feature_flag_called, also read $experiment_exposure (event IN ('$feature_flag_called', '$experiment_exposure')), and count persons, not rows).",+ "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, running_time_calculation (minimum detectable effect, recommended running time and sample size), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name. When it is $feature_flag_called, also read $experiment_exposure (event IN ('$feature_flag_called', '$experiment_exposure')), and count persons, not rows). variant_screenshot_urls maps each variant key to the viewable URLs of its screenshots in parameters.variant_screenshot_media_ids.","category": "Experiments","feature": "experiments","summary": "Get experiment details",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 71fe0e924c8f..7df0ed0ce6a9 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5347,7 +5347,7 @@}},"experiment-get": {- "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, running_time_calculation (minimum detectable effect, recommended running time and sample size), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name. When it is $feature_flag_called, also read $experiment_exposure (event IN ('$feature_flag_called', '$experiment_exposure')), and count persons, not rows).",+ "description": "Get a single experiment by ID. If you have the experiment's feature flag key instead of its ID, call experiment-get-by-flag-key. If you have neither, load the finding-experiments skill to resolve the user's reference first.\n\nReturns the full experiment object including: status (draft/running/paused/exposure_frozen/stopped — \"paused\" is a virtual value returned when the experiment is launched but its feature flag has been deactivated, \"exposure_frozen\" when its flag's release groups are narrowed to the already-exposed cohort so enrollment is closed while metrics keep flowing), start_date and end_date, linked feature_flag (with variants, filters, active state), metrics and metrics_secondary arrays, conclusion and conclusion_comment if ended, running_time_calculation (minimum detectable effect, recommended running time and sample size), stats_config, type (web/product), and resolved_exposure_event (the event exposures are counted on when no custom exposure event is configured — resolved server-side to $feature_flag_called or $experiment_exposure; use it in SQL instead of hardcoding either name. When it is $feature_flag_called, also read $experiment_exposure (event IN ('$feature_flag_called', '$experiment_exposure')), and count persons, not rows). variant_screenshot_urls maps each variant key to the viewable URLs of its screenshots in parameters.variant_screenshot_media_ids.","category": "Experiments","feature": "experiments","summary": "Get experiment details",@@ -5361,7 +5361,7 @@}},"experiment-get-by-flag-key": {- "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly.",+ "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly. A found experiment also carries `variant_screenshot_urls`, which maps each variant key to the viewable URLs of its screenshots.","category": "Experiments","feature": "experiments","summary": "Get an experiment by its feature flag key.",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex da07b05035e7..d5d5f60f5229 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -89,7 +89,7 @@}},"experiment-get-by-flag-key": {- "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly.",+ "description": "Get an experiment by its feature flag key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the flag key but not the experiment's numeric ID; use `experiment-get` when you have the ID. Returns the full experiment with `found: true`, or `found: false` with a message when no flag or no linked experiment exists — a miss is data, not an error, so an existence check before `experiment-create` needs no special handling. Archived flags and experiments are included. A miss carries `reason`: `no_flag` or `no_experiment` mean the key is free to create on; `ambiguous` means several experiments share the flag (experiment-duplicate reuses it) and none is the single live one, so `candidates` (id, name, status, archived, dates) lists them to pick from with `experiment-get`. When exactly one is live it is returned directly. A found experiment also carries `variant_screenshot_urls`, which maps each variant key to the viewable URLs of its screenshots.","category": "Experiments","feature": "experiments","summary": "Get an experiment by its feature flag key.",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex eba27961bb69..75d8fecc32ca 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -608,7 +608,7 @@"type": "string"}},- "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant."+ "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. To add a screenshot, upload the image with media-image-upload-start and media-image-upload-complete with purpose \"experiment\", then pass the returned id here. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant."},"ExternalDataJobsAfterSchema": {"type": "string",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex bf97ec7c1478..24de5d4b8b9d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -134298,6 +134298,7 @@ export namespace Schemas {export const UploadedMediaListPurpose = {Canvas: 'canvas',Email: 'email',+ Experiment: 'experiment',} as const;/**@@ -134309,6 +134310,7 @@ export namespace Schemas {export const UploadedMediaCreateBodyPurpose = {Email: 'email',Canvas: 'canvas',+ Experiment: 'experiment',} as const;export type UploadedMediaCreateBody = {diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex 8537f5908142..118c352b1031 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -5837,7 +5837,7 @@ export const UploadedMediaListParams = () => zod.object({export const UploadedMediaListQueryParams = () => zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),- purpose: zod.enum(['canvas', 'email']).describe('The library to list.'),+ purpose: zod.enum(['canvas', 'email', 'experiment']).describe('The library to list.'),search: zod.string().optional().describe('Only list images whose name contains this text, ignoring case.'),})diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex b9218306c61a..86e84fdee296 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -496,7 +496,7 @@ export const ExperimentVariantNotesSchema = zexport const ExperimentVariantScreenshotMediaIdsSchema = z.record(z.string(), z.array(z.string())).describe(- 'Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.'+ 'Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. To add a screenshot, upload the image with media-image-upload-start and media-image-upload-complete with purpose "experiment", then pass the returned id here. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.').optional()diff --git a/services/mcp/src/tools/experiments/getByFlagKey.ts b/services/mcp/src/tools/experiments/getByFlagKey.tsindex e67bef17f26f..10ea40710094 100644--- a/services/mcp/src/tools/experiments/getByFlagKey.ts+++ b/services/mcp/src/tools/experiments/getByFlagKey.ts@@ -7,6 +7,8 @@ import { resolveFlagsByKey } from '@/tools/featureFlags/resolveFlagsByKey'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'+import { withVariantScreenshotUrls } from './variantDetails'+/*** `experiment-get-by-flag-key` fetches an experiment by its feature flag key, the identifier* agents hold when `experiment-get` wants a numeric ID. The experiments list has no key filter,@@ -49,7 +51,9 @@ interface ExperimentLookupMiss {candidates?: ExperimentCandidate[]}-type Result = (WithPostHogUrl<Schemas.Experiment> & { found: true }) | ExperimentLookupMiss+type Result =+ | (WithPostHogUrl<Schemas.Experiment> & { variant_screenshot_urls: Record<string, string[]>; found: true })+ | ExperimentLookupMisstype LinkedPick = { experimentId: number } | { candidates: ExperimentCandidate[] }@@ -157,7 +161,7 @@ const experimentGetByFlagKey = (): ToolBase<typeof schema, Result> => ({path: `/api/projects/${encodeURIComponent(projectId)}/experiments/${encodeURIComponent(String(experimentId))}/`,})const experimentWithUrl = await withPostHogUrl(context, experiment, `/experiments/${experiment.id}`)- return { ...experimentWithUrl, found: true }+ return { ...withVariantScreenshotUrls(experimentWithUrl, context.api.publicBaseUrl), found: true }},})diff --git a/services/mcp/src/tools/experiments/getExperimentHooks.ts b/services/mcp/src/tools/experiments/getExperimentHooks.tsnew file mode 100644index 000000000000..e3d1d28f6463--- /dev/null+++ b/services/mcp/src/tools/experiments/getExperimentHooks.ts@@ -0,0 +1,9 @@+/** Hooks for the generated `experiment-get` tool. They add viewable URLs for the variant screenshots. */+import type { ToolHooks } from '@/tools/tool-hooks'++import { withVariantScreenshotUrls } from './variantDetails'++export default {+ afterResponse: (context, _params, result) =>+ withVariantScreenshotUrls(result as { parameters?: unknown }, context.api.publicBaseUrl),+} satisfies ToolHooks<Record<string, unknown>>diff --git a/services/mcp/src/tools/experiments/variantDetails.ts b/services/mcp/src/tools/experiments/variantDetails.tsindex b4b9f7179eba..af9b7c642ac0 100644--- a/services/mcp/src/tools/experiments/variantDetails.ts+++ b/services/mcp/src/tools/experiments/variantDetails.ts@@ -71,6 +71,23 @@ export function summarizeVariantDetails<T extends { parameters?: unknown }>(}}+/** Adds `variant_screenshot_urls`, the public image URLs of `variant_screenshot_media_ids`, keyed by variant key. */+export function withVariantScreenshotUrls<T extends { parameters?: unknown }>(+ experiment: T,+ publicBaseUrl: string+): T & { variant_screenshot_urls: Record<string, string[]> } {+ const mediaIds = asRecord(asRecord(experiment.parameters).variant_screenshot_media_ids)+ const urls = Object.fromEntries(+ Object.entries(mediaIds).map(([variantKey, ids]) => [+ variantKey,+ (Array.isArray(ids) ? ids : [ids])+ .filter((id): id is string => typeof id === 'string' && id !== '')+ .map((id) => `${publicBaseUrl}/uploaded_media/${encodeURIComponent(id)}`),+ ])+ )+ return { ...experiment, variant_screenshot_urls: urls }+}+function variantKeysWhere(value: unknown, predicate: (entry: unknown) => boolean): string[] {return Object.entries(asRecord(value)).filter(([, entry]) => predicate(entry))diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.tsindex 3a61893cefc4..317569c9ece1 100644--- a/services/mcp/src/tools/generated/experiments.ts+++ b/services/mcp/src/tools/generated/experiments.ts@@ -11,6 +11,7 @@ import {} from '@/schema/tool-inputs'import { castStringToInt, normalizeParamAliases } from '@/tools/cast-helpers'import hooks_experimentCreate from '@/tools/experiments/createExperimentHooks'+import hooks_experimentGet from '@/tools/experiments/getExperimentHooks'import hooks_experimentList from '@/tools/experiments/listExperimentsHooks'import hooks_experimentUpdate from '@/tools/experiments/updateExperimentHooks'import { transformRequestBody, withToolHooks } from '@/tools/tool-hooks'@@ -570,15 +571,21 @@ const experimentGet = (): ToolBase<ReturnType<typeof ExperimentGetSchema>, WithPwithUiApp('experiment', {name: 'experiment-get',schema: ExperimentGetSchema(),- handler: async (context: Context, params: z.infer<ReturnType<typeof ExperimentGetSchema>>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<Schemas.Experiment>({- method: 'GET',- path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/`,- })- const filtered = omitResponseFields(result, ['saved_metrics.*.effective_query', 'health']) as typeof result- return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)- },+ handler: withToolHooks(+ hooks_experimentGet,+ async (context: Context, params: z.infer<ReturnType<typeof ExperimentGetSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.Experiment>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/`,+ })+ const filtered = omitResponseFields(result, [+ 'saved_metrics.*.effective_query',+ 'health',+ ]) as typeof result+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)+ }+ ),})const ExperimentHoldoutsCreateSchema = () => {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.jsonindex 3798f3601df9..224076d29490 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-create.json@@ -6017,7 +6017,7 @@},"type": "array"},- "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.",+ "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. To add a screenshot, upload the image with media-image-upload-start and media-image-upload-complete with purpose \"experiment\", then pass the returned id here. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.","propertyNames": {"type": "string"},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.jsonindex 180b96607900..7b1add3015b9 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json@@ -9757,7 +9757,7 @@},"type": "array"},- "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.",+ "description": "Screenshot media IDs per variant, keyed by variant key, shown under each variant in the experiment view. Each value is the complete list of uploaded media IDs for that variant. To add a screenshot, upload the image with media-image-upload-start and media-image-upload-complete with purpose \"experiment\", then pass the returned id here. On update, only the variants you pass change and the screenshots of other variants stay. Pass an empty list to remove all screenshots of a variant.","propertyNames": {"type": "string"},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.jsonindex 2ee1e2fd3f17..e14d3fb38d3f 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/media-images-list.json@@ -11,7 +11,7 @@},"purpose": {"description": "The library to list, e.g. \"email\". Required.",- "enum": ["canvas", "email"],+ "enum": ["canvas", "email", "experiment"],"type": "string"},"search": {diff --git a/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts b/services/mcp/tests/unit/experiment-get-by-flag-key.test.tsindex cd9bcfa1f894..388c5fffb2e9 100644--- a/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts+++ b/services/mcp/tests/unit/experiment-get-by-flag-key.test.ts@@ -8,6 +8,7 @@ function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {return {api: {request: requestMock,+ publicBaseUrl: 'https://us.posthog.com',getProjectBaseUrl: (projectId: string) => `https://us.posthog.com/project/${projectId}`,} as any,stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,@@ -68,7 +69,11 @@ describe('experiment-get-by-flag-key', () => {const request = vi.fn().mockResolvedValueOnce({ results: [flag(7, 'new-checkout', [11])] })- .mockResolvedValueOnce({ ...experiment(11, 'new-checkout'), metrics: [] })+ .mockResolvedValueOnce({+ ...experiment(11, 'new-checkout'),+ metrics: [],+ parameters: { variant_screenshot_media_ids: { test: ['media-1'] } },+ })const result = await tool.handler(createMockContext(request), { feature_flag_key: 'new-checkout' })@@ -76,7 +81,13 @@ describe('experiment-get-by-flag-key', () => {expect(request).toHaveBeenCalledTimes(2)expect(request).toHaveBeenNthCalledWith(1, FLAG_LIST)expect(request).toHaveBeenNthCalledWith(2, EXPERIMENT_GET(11))- expect(result).toMatchObject({ id: 11, feature_flag_key: 'new-checkout', metrics: [], found: true })+ expect(result).toMatchObject({+ id: 11,+ feature_flag_key: 'new-checkout',+ metrics: [],+ variant_screenshot_urls: { test: ['https://us.posthog.com/uploaded_media/media-1'] },+ found: true,+ })expect((result as { _posthogUrl?: string })._posthogUrl).toContain('/experiments/11')})diff --git a/services/mcp/tests/unit/experiment-variant-details.test.ts b/services/mcp/tests/unit/experiment-variant-details.test.tsindex 62e641f9922b..fd4d188ef755 100644--- a/services/mcp/tests/unit/experiment-variant-details.test.ts+++ b/services/mcp/tests/unit/experiment-variant-details.test.ts@@ -17,7 +17,11 @@ function contextWith(responses: Record<string, unknown>): { context: Context; reconst request = vi.fn(async ({ method }: { method: string }) => responses[method])const context = {stateManager: { getProjectId: async () => '7' },- api: { request, getProjectBaseUrl: () => 'https://app.example.com/project/7' },+ api: {+ request,+ publicBaseUrl: 'https://app.example.com',+ getProjectBaseUrl: () => 'https://app.example.com/project/7',+ },} as unknown as Contextreturn { context, request }}@@ -116,6 +120,25 @@ describe('experiment variant notes and screenshots', () => {expect(sentBody(request, 'PATCH')).toEqual({ name: 'Renamed' })})+ it('experiment-get maps each variant screenshot media ID to its viewable URL', async () => {+ const { context } = contextWith({+ GET: {+ id: 1,+ parameters: { variant_screenshot_media_ids: { control: ['media-1', 'media-2'], test: 'media-3' } },+ },+ })++ const result = (await run('experiment-get', context, { id: 1 })) as Record<string, unknown>++ expect(result.variant_screenshot_urls).toEqual({+ control: [+ 'https://app.example.com/uploaded_media/media-1',+ 'https://app.example.com/uploaded_media/media-2',+ ],+ test: ['https://app.example.com/uploaded_media/media-3'],+ })+ })+it('experiment-list reports which variants have notes or screenshots', async () => {const { context } = contextWith({GET: {