Skip to main content
Glama

compare_screenshots

Detect visual changes on Android screens by comparing current and previous screenshots to verify UI modifications, calculate pixel change percentage, and determine significant differences.

Instructions

Compare the current screen with the previously captured screenshot to detect changes. Returns the percentage of pixels that changed and whether the screen has significantly changed. Useful for verifying that an action had an effect.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
thresholdNoMinimum change percentage to be considered "changed" (default: 5)
device_idNoDevice serial number

Implementation Reference

  • The MCP tool 'compare_screenshots' is registered here. It handles input validation, retrieves the previous screenshot from memory, captures the current one, and invokes the comparison logic.
    server.registerTool(
      'compare_screenshots',
      {
        description: 'Compare the current screen with the previously captured screenshot to detect changes. Returns the percentage of pixels that changed and whether the screen has significantly changed. Useful for verifying that an action had an effect.',
        inputSchema: {
          threshold: z.number().optional().default(5).describe('Minimum change percentage to be considered "changed" (default: 5)'),
          device_id: z.string().optional().describe('Device serial number'),
        },
      },
      async ({ threshold, device_id }) => {
        return await metrics.measure('compare_screenshots', device_id || 'default', async () => {
          const deviceKey = device_id || 'default';
          const previousBuffer = lastScreenshots.get(deviceKey);
    
          if (!previousBuffer) {
            return {
              content: [{
                type: 'text' as const,
                text: JSON.stringify({
                  success: false,
                  error: 'No previous screenshot to compare with. Call capture_screenshot first.',
                }, null, 2),
              }],
            };
          }
    
          const currentBuffer = await captureScreenshotBuffer(device_id);
          const diff = await compareScreenshots(previousBuffer, currentBuffer, threshold);
    
          // Update stored screenshot
          lastScreenshots.set(deviceKey, currentBuffer);
    
          return {
            content: [{
              type: 'text' as const,
              text: JSON.stringify({
                success: true,
                diff: {
                  changePercentage: diff.changePercentage,
                  hasChanged: diff.hasChanged,
                  totalPixels: diff.totalPixels,
                  changedPixels: diff.changedPixels,
                },
              }, null, 2),
            }],
          };
        });
      }
    );
  • The core logic for comparing two screenshot buffers. It resizes images to a standard size, compares pixels raw, and calculates the change percentage.
    export async function compareScreenshots(
      buffer1: Buffer,
      buffer2: Buffer,
      threshold: number = 5 // minimum change % to be considered "changed"
    ): Promise<DiffResult> {
      // Normalize both images to same size and raw format
      const size = { width: 360, height: 640 }; // Downscale for fast comparison
    
      const [raw1, raw2] = await Promise.all([
        sharp(buffer1)
          .resize(size.width, size.height, { fit: 'fill' })
          .raw()
          .toBuffer(),
        sharp(buffer2)
          .resize(size.width, size.height, { fit: 'fill' })
          .raw()
          .toBuffer(),
      ]);
    
      const totalPixels = size.width * size.height;
      let changedPixels = 0;
    
      // Compare pixel by pixel (each pixel = 3 bytes for RGB)
      const bytesPerPixel = 3;
      const pixelThreshold = 30; // Per-channel difference threshold
    
      for (let i = 0; i < totalPixels; i++) {
        const offset = i * bytesPerPixel;
        const dr = Math.abs(raw1[offset] - raw2[offset]);
        const dg = Math.abs(raw1[offset + 1] - raw2[offset + 1]);
        const db = Math.abs(raw1[offset + 2] - raw2[offset + 2]);
    
        if (dr > pixelThreshold || dg > pixelThreshold || db > pixelThreshold) {
          changedPixels++;
        }
      }
    
      const changePercentage = (changedPixels / totalPixels) * 100;
      const screenHash = computeScreenHash(buffer2);
    
      const result: DiffResult = {
        changePercentage: Math.round(changePercentage * 100) / 100,
        hasChanged: changePercentage >= threshold,
        screenHash,
        totalPixels,
        changedPixels,
      };
    
      log.debug('Screen diff computed', result);
      return result;
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses return values ('percentage of pixels that changed and whether the screen has significantly changed'), but omits critical behavioral details: error handling when no previous screenshot exists, whether the comparison updates the reference screenshot, and any side effects like saving diff images.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three sentences efficiently structured: first defines the action, second specifies return values, third states the use case. No redundancy or filler. Front-loaded with the core comparison concept.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 2-parameter tool without output schema, the description adequately compensates by describing return values. However, it fails to mention the critical state dependency—that this tool requires a previously captured screenshot to exist—and what happens if called without one, which is essential for correct invocation sequencing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, establishing a baseline of 3. The description mentions 'significantly changed' which loosely maps to the threshold parameter's purpose, but adds no syntax details, valid ranges, or semantic context beyond what the schema already provides for device_id or threshold.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action (compare current screen with previously captured screenshot) and the resource (screenshots). It effectively distinguishes from sibling capture_screenshot by emphasizing the comparison with a previously captured state rather than capturing new.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides implicit usage context ('Useful for verifying that an action had an effect'), indicating when to use it. However, it lacks explicit prerequisites (requires a prior screenshot to exist), does not mention error conditions if none exists, and does not contrast with alternatives like analyze_screen.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/divineDev-dotcom/android_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server