Skip to content

MCP visual previews: list_visual_previews and get_visual_preview returning bounded, downscaled image content #2604

Closed

Description

@propr-dev

Context

Tasks can publish visual previews (screenshots, and video where enabled) that appear as thumbnails in the Inbox and on pull requests. MCP clients cannot fetch them, so an agent cannot check the visual result of a UI change. With the service extracted in the previous issue (packages/api/services/previewMediaFetch.ts), we can expose them safely.

Requirements

  1. list_visual_previews (scope read): exactly one of { repository, taskId } or { repository, pullRequest }.
    • For a task: resolve the association with the existing taskPreviewSource logic (packages/api/services/previewMediaProjection.ts): initial implementation tasks → the PR description; follow-up tasks → their own completion comment (commentId from the latest githubComment history metadata). Other users' private goal tasks stay invisible (use the tool target + applyTaskVisibility rules as get_task).
    • Output: { association: { kind, repository, number }, previews: [{ previewId, type: 'image'|'video', title, description, fetchable: boolean }], previewsEnabled } where previewId = "<kind>:<number>:<assetId>". fetchable is true for images, false for videos (metadata only).
    • Repositories with previews disabled return { previews: [], previewsEnabled: false } (not an error).
  2. get_visual_preview (scope read): { repository, previewId, maxDimension = 1024 (256..1568), format = 'webp' | 'jpeg' | 'png' (default 'webp') }.
    • Parses previewId, re-authorizes the repository, loads the image through loadPublishedPreview with the caller's GitHub credential (never the installation token), maxBytes = 10 MiB.
    • Downscales so the longest edge ≤ maxDimension (never upscales) and re-encodes; if the encoded result exceeds 750 KiB, re-encode with lower quality (webp/jpeg: 80 → 60 → 45) and finally reduce dimension by 25% steps until it fits; if it still cannot fit, fail with PREVIEW_TOO_LARGE.
    • SVG is rasterised (sharp handles it); animated GIF/WebP use the first frame.
    • Returns real MCP image content: content: [{ type: 'image', data: <base64>, mimeType }, { type: 'text', text: JSON metadata }] with metadata { previewId, title, description, width, height, originalBytes, bytes, mimeType }.
    • Videos fail with PREVIEW_NOT_RENDERABLE (stage validation, not retryable) and a message pointing at the PR URL.
  3. Add the image-processing dependency sharp to packages/api/package.json (the app image is linux/amd64 glibc; sharp ships prebuilt binaries). Verify the app image builds and scripts/smoke-test-images.sh loads sharp.
  4. Tool results currently are JSON wrapped by server.ts. Add a narrowly-scoped escape hatch: an OperationResult may carry content (an array of SDK content blocks); server.ts passes it through verbatim for read-only tools instead of JSON-wrapping data. The access log records result_bytes as today (base64 length).
  5. Errors use the envelope: PreviewMediaError codes map to McpError with stage github (source) or validation (not found / not renderable).
  6. Resource propr://instances/{id}/repositories/{owner}/{repo}/previews/{previewId} returning a blob resource with the same bounds.

Implementation Specification

  • New packages/api/mcp/toolsPreviews.ts; register in createToolCatalog.
  • Edit packages/api/mcp/operations.ts/tools.ts types: OperationResult gains optional content.
  • Edit packages/api/mcp/server.ts to honour content.
  • packages/api/package.json: add sharp.
  • Tests packages/api/test/mcpVisualPreviews.test.ts generating a PNG in-test with sharp (no binary fixtures).

Acceptance Criteria

  • list_visual_previews({ repository, pullRequest }) returns the published previews with titles/types; video entries have fetchable: false.
  • list_visual_previews({ repository, taskId }) for a follow-up task returns only that run's completion-comment previews.
  • get_visual_preview on a 4000×3000 PNG returns an image content block ≤ 750 KiB with longest edge 1024, plus metadata with the original byte count.
  • A video preview returns PREVIEW_NOT_RENDERABLE; a disabled repository returns PREVIEW_NOT_FOUND-style 404 without contacting GitHub.
  • The installation token is never used for media fetches (assert the fake receives the user token).
  • Legacy SDK clients receive the same image block (both eras tested).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We return MCP image content blocks — the only form a vision-capable client can actually look at — rather than a URL (would require the client to authenticate to GitHub/ProPR) or a raw path. Images are downscaled server-side with sharp: MCP clients budget context by bytes/tokens, and a full-resolution 4K screenshot would dominate it. 1024 px default / 1568 px max matches common vision model input sizes, and 750 KiB keeps base64 under ~1 MB.

    Access control is inherited from the extracted service: the caller's GitHub credential must be able to read the PR/comment, the repository must have previews enabled, and only ProPR-published assets are served. Videos are metadata-only per the request (frame extraction would need ffmpeg in the API image).

    File: packages/api/mcp/toolsPreviews.ts (new file)

    Why this file: MCP wrappers for listing and fetching previews, including downscaling.

    import { Octokit } from '@octokit/core';
    import sharp from 'sharp';
    import { z } from 'zod';
    import { McpError } from './config.js';
    import { applyTaskVisibility, type McpTool, type ToolDeps, idSchema, ok, repositorySchema } from './tools.js';
    import { latestCommentMetadata, previewMediaReader, taskPreviewSource } from '../services/previewMediaProjection.js';
    import { listPublishedPreviews, loadPublishedPreview, PreviewMediaError, type PreviewAssociation } from '../services/previewMediaFetch.js';
    import type { McpPrincipal } from './policy.js';
    
    const MAX_ENCODED_BYTES = 750 * 1024;
    const PREVIEW_ID = /^(pull|comment):([1-9][0-9]{0,15}):([A-Za-z0-9_-]{1,128})$/;
    
    function toMcpError(error: unknown): never {
      if (error instanceof PreviewMediaError) {
        throw new McpError(error.code === 'PREVIEWS_DISABLED' ? 'PREVIEW_NOT_FOUND' : error.code, error.message, error.status,
          { stage: error.status === 404 ? 'validation' : 'github', retryable: error.code === 'PREVIEW_UNAVAILABLE' });
      }
      throw error;
    }
    
    /** The media fetch must use the caller's own GitHub credential: it is the access proof. */
    function userGitHub(principal: McpPrincipal): { token: string; octokit: Octokit } {
      const token = principal.user.accessToken;
      if (!token) throw new McpError('GITHUB_CREDENTIAL_REQUIRED', 'Sign in to ProPR in the browser so previews can be read with your GitHub access.', 403, { stage: 'authorization' });
      return { token, octokit: new Octokit({ auth: token, request: { timeout: 10_000 } }) };
    }
    
    async function taskAssociation(deps: ToolDeps, principal: McpPrincipal, repository: string, taskId: string): Promise<PreviewAssociation | null> {
      const query = deps.db('tasks').where({ 'tasks.task_id': taskId, 'tasks.repository': repository });
      applyTaskVisibility(deps.db, query, principal.user.id); // private goal tasks stay invisible
      const task = await query.first('task_id', 'repository', 'task_type', 'pr_number', 'initial_job_data', 'final_result');
      if (!task) throw new McpError('NOT_FOUND', 'Task not found in your authorized repository.', 404, { stage: 'validation' });
      const history = await deps.db('task_history').where({ task_id: taskId }).where('metadata', 'like', '%githubComment%')
        .orderBy('history_id', 'asc').select('metadata');
      const source = taskPreviewSource({ ...task, latest_metadata: latestCommentMetadata(history) });
      if (source.commentId) return { kind: 'comment', repository, number: source.commentId };
      if (source.isFollowUp) return null; // follow-up without a published comment has no previews
      return source.prNumbers[0] ? { kind: 'pull', repository, number: source.prNumbers[0] } : null;
    }
    
    /** Downscale then shrink quality/dimension until the encoded image fits the byte budget. */
    export async function renderForClient(input: Buffer, options: { maxDimension: number; format: 'webp' | 'jpeg' | 'png' }) {
      let dimension = options.maxDimension;
      for (let attempt = 0; attempt < 6; attempt++) {
        for (const quality of options.format === 'png' ? [100] : [80, 60, 45]) {
          const pipeline = sharp(input, { animated: false, limitInputPixels: 64_000_000 })
            .rotate() // respect EXIF orientation
            .resize({ width: dimension, height: dimension, fit: 'inside', withoutEnlargement: true });
          const encoded = options.format === 'png' ? pipeline.png({ compressionLevel: 9 })
            : options.format === 'jpeg' ? pipeline.jpeg({ quality, mozjpeg: true }) : pipeline.webp({ quality });
          const { data, info } = await encoded.toBuffer({ resolveWithObject: true });
          if (data.byteLength <= MAX_ENCODED_BYTES) return { data, width: info.width, height: info.height, mimeType: `image/${options.format}` };
        }
        dimension = Math.floor(dimension * 0.75);
        if (dimension < 128) break;
      }
      throw new McpError('PREVIEW_TOO_LARGE', 'The preview could not be reduced below the 750 KiB response limit.', 413, { stage: 'validation' });
    }
    
    export function addPreviewTools(tools: McpTool[], deps: ToolDeps): void {
      tools.push({ name: 'list_visual_previews', description: 'List the visual previews (screenshots, videos) a task or pull request published, with titles and types. Images can be fetched with get_visual_preview; videos are metadata only.', scope: 'read', readOnly: true,
        schema: z.object({ repository: repositorySchema, taskId: idSchema.optional(), pullRequest: z.number().int().positive().optional() }).strict()
          .refine(args => Number(!!args.taskId) + Number(!!args.pullRequest) === 1, { message: 'Provide exactly one of taskId or pullRequest.' }) as unknown as z.ZodObject,
        run: async ({ principal, args }) => {
          await deps.policy.repository(principal, args.repository);
          const association = args.taskId ? await taskAssociation(deps, principal, args.repository, args.taskId)
            : { kind: 'pull' as const, repository: args.repository.toLowerCase(), number: args.pullRequest };
          if (!association) return ok({ association: null, previews: [], previewsEnabled: true });
          const enabled = (await previewMediaReader.enabledRepositories([association.repository])).has(association.repository.toLowerCase());
          if (!enabled) return ok({ association, previews: [], previewsEnabled: false });
          const { octokit } = userGitHub(principal);
          try {
            const listed = await listPublishedPreviews({ association: { ...association, repository: association.repository.toLowerCase() }, octokit, reader: previewMediaReader });
            return ok({ association, previewsEnabled: true, previews: listed.map(preview => ({
              previewId: `${association.kind}:${association.number}:${preview.assetId}`, type: preview.type, title: preview.title,
              description: preview.description ?? null, fetchable: preview.type === 'image' })) });
          } catch (error) { return toMcpError(error); }
        } });
      tools.push({ name: 'get_visual_preview', description: 'Fetch one published image preview as image content, downscaled so its longest edge is at most maxDimension and the payload stays under 750 KiB. Videos cannot be fetched.', scope: 'read', readOnly: true,
        schema: z.object({ repository: repositorySchema, previewId: z.string().regex(PREVIEW_ID),
          maxDimension: z.number().int().min(256).max(1568).default(1024), format: z.enum(['webp', 'jpeg', 'png']).default('webp') }).strict(),
        run: async ({ principal, args }) => {
          await deps.policy.repository(principal, args.repository);
          const [, kind, number, assetId] = PREVIEW_ID.exec(args.previewId)!;
          const association = { kind: kind as 'pull' | 'comment', repository: args.repository.toLowerCase(), number: Number(number) };
          const { token, octokit } = userGitHub(principal);
          let loaded;
          try { loaded = await loadPublishedPreview({ association, assetId, token, octokit, fetch, reader: previewMediaReader, maxBytes: 10 * 1024 * 1024 }); }
          catch (error) { return toMcpError(error); }
          if (loaded.preview.type !== 'image') {
            throw new McpError('PREVIEW_NOT_RENDERABLE', `"${loaded.preview.title}" is a video; open it on GitHub: https://github.com/${args.repository}/${kind === 'pull' ? `pull/${number}` : 'pulls'}`, 400, { stage: 'validation' });
          }
          const image = await renderForClient(loaded.body, { maxDimension: args.maxDimension, format: args.format });
          const metadata = { previewId: args.previewId, title: loaded.preview.title, description: loaded.preview.description ?? null,
            width: image.width, height: image.height, mimeType: image.mimeType, originalBytes: loaded.body.byteLength, bytes: image.data.byteLength };
          // `content` bypasses JSON wrapping in server.ts so clients receive a real image block.
          return { status: 200, data: metadata, content: [
            { type: 'image', data: image.data.toString('base64'), mimeType: image.mimeType },
            { type: 'text', text: JSON.stringify(metadata) },
          ] };
        } });
    }

    If .refine() on the schema breaks the schema: z.ZodObject contract used by tools/list (see the comment in toolsPullRequests.ts), drop the refine and perform the "exactly one" check at the start of run, throwing INVALID_INPUT — as get_agent_activity does for goal/task.

    Register in tools.ts: import { addPreviewTools } from './toolsPreviews.js'; and addPreviewTools(tools, deps);.

    File: packages/api/mcp/operations.ts (type) and packages/api/mcp/server.ts

    Why these files: The tool contract returns JSON data; image blocks need a narrow pass-through.

    --- a/packages/api/mcp/operations.ts
    +++ b/packages/api/mcp/operations.ts
    -export interface OperationResult { status: number; data: unknown }
    +/**
    + * `content`, when present, is returned to the SDK verbatim instead of JSON-wrapping
    + * `data`. Only read-only tools may use it (e.g. image previews); mutation
    + * receipts always persist `data`.
    + */
    +export interface OperationResult { status: number; data: unknown; content?: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> }

    In server.ts, where a successful tool result is converted into CallToolResult:

    // Read-only tools may supply ready-made content blocks (images).
    if (tool.readOnly && result.content) return { content: result.content, structuredContent: result.data as Record<string, unknown> };
    return { content: [{ type: 'text', text: JSON.stringify(result.data) }], structuredContent: ... }; // existing path

    Ensure the bounded-response guard (256 KiB) does not apply to image blocks (they have their own 750 KiB bound) but still applies to the text block.

    File: packages/api/package.json

       "dependencies": {
    +    "sharp": "^0.34.0",

    File: packages/api/test/mcpVisualPreviews.test.ts (new file)

    Why this file: Exercises downscaling bounds and the list/get contract with a real generated PNG.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import sharp from 'sharp';
    import { renderForClient } from '../mcp/toolsPreviews.js';
    
    test('large screenshots are downscaled under the byte budget', async () => {
      // Random noise compresses badly: a worst case for the byte budget.
      const raw = Buffer.alloc(4000 * 3000 * 3);
      for (let i = 0; i < raw.length; i++) raw[i] = (i * 2654435761) >>> 24;
      const png = await sharp(raw, { raw: { width: 4000, height: 3000, channels: 3 } }).png().toBuffer();
      const image = await renderForClient(png, { maxDimension: 1024, format: 'webp' });
      assert.ok(image.data.byteLength <= 750 * 1024);
      assert.ok(Math.max(image.width, image.height) <= 1024);
      const small = await sharp({ create: { width: 200, height: 100, channels: 3, background: '#fff' } }).png().toBuffer();
      const kept = await renderForClient(small, { maxDimension: 1024, format: 'png' });
      assert.deepEqual([kept.width, kept.height], [200, 100]); // never upscaled
    });
    // Plus executeTool-level cases using a GitHub fake (pattern from previewMediaRoutes.test.ts):
    // list for a PR, list for a follow-up task (comment association), video -> PREVIEW_NOT_RENDERABLE,
    // disabled repository -> previewsEnabled false with zero GitHub calls, and the media fetch receiving the user token.
  2. propr-dev commented on Sep 29, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 2604/gpt-5.6-sol-mcp-visual-previews-list_-20260929-2142-29r
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2604-20260929-2142-gpt-5.6-sol-29r

    🔍 Track Task Execution

  3. added a commit that references this issue on Sep 29, 2026
  4. added a commit that references this issue on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions