Skip to main content
Glama
hoangdn3

OpenRouter MCP Multimodal Server

by hoangdn3

mcp_openrouter_multi_image_analysis

Analyze multiple images simultaneously with a single prompt to extract detailed insights and information from visual content.

Instructions

Analyze multiple images at once with a single prompt and receive detailed responses

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imagesYesArray of image objects to analyze
promptYesPrompt for analyzing the images
markdown_responseNoWhether to format the response in Markdown (default: true)
modelNoOpenRouter model to use. If not specified, the system will use a free model with vision capabilities or the default model.

Implementation Reference

  • Main handler function: validates input, fetches and processes multiple images into base64 data URLs, constructs multimodal message, calls OpenRouter API (with model fallbacks), formats Markdown response if requested, and returns structured result with metadata.
    export async function handleMultiImageAnalysis(
      request: { params: { arguments: MultiImageAnalysisToolRequest } },
      openai: OpenAI,
      defaultModel?: string
    ) {
      const args = request.params.arguments;
      
      try {
        // Validate inputs
        if (!args.images || !Array.isArray(args.images) || args.images.length === 0) {
          throw new McpError(ErrorCode.InvalidParams, 'At least one image is required');
        }
        
        if (!args.prompt) {
          throw new McpError(ErrorCode.InvalidParams, 'A prompt for analyzing the images is required');
        }
        
        console.error(`Processing ${args.images.length} images`);
        
        // Process each image and convert to base64 if needed
        const processedImages = await Promise.all(
          args.images.map(async (image, index) => {
            try {
              // Skip processing if already a data URL
              if (image.url.startsWith('data:')) {
                console.error(`Image ${index + 1} is already in base64 format`);
                return image;
              }
              
              console.error(`Processing image ${index + 1}: ${image.url.substring(0, 100)}${image.url.length > 100 ? '...' : ''}`);
              
              // Get MIME type
              const mimeType = getMimeType(image.url);
              
              // Fetch and process the image
              const buffer = await fetchImageAsBuffer(image.url);
              const base64 = await processImage(buffer, mimeType);
              
              return {
                url: `data:${mimeType === 'application/octet-stream' ? 'image/jpeg' : mimeType};base64,${base64}`,
                alt: image.alt
              };
            } catch (error: any) {
              console.error(`Error processing image ${index + 1}:`, error);
              throw new Error(`Failed to process image ${index + 1}: ${image.url}. Error: ${error.message}`);
            }
          })
        );
        
        // Select model with priority:
        // 1. User-specified model
        // 2. Default model from environment
        let model = args.model || defaultModel || DEFAULT_FREE_MODEL;
        console.error(`[Multi-Image Tool] Using IMAGE model: ${model}`);
        
        // Build content array for the API call
        const content: Array<{ 
          type: string; 
          text?: string; 
          image_url?: { 
            url: string 
          } 
        }> = [
          {
            type: 'text',
            text: args.prompt
          }
        ];
        
        // Add each processed image to the content array
        processedImages.forEach(image => {
          content.push({
            type: 'image_url',
            image_url: {
              url: image.url
            }
          });
        });
        
        // Try primary model first
        let responseText: string;
        let responseId: string;
        let usedModel: string;
        let usage: any;
        
        try {
          const completion = await openai.chat.completions.create({
            model,
            messages: [{
              role: 'user',
              content
            }] as any
          });
          
          const response = completion as any;
          responseText = completion.choices[0].message.content || '';
          responseId = response.id;
          usedModel = response.model;
          usage = response.usage;
        } catch (primaryError: any) {
          // If primary model fails and backup exists, try backup
          const backupModel = process.env.OPENROUTER_DEFAULT_MODEL_IMG_BACKUP;
          if (backupModel && backupModel !== model) {
            try {
              console.error(`Primary model failed, trying backup: ${backupModel}`);
              const completion = await openai.chat.completions.create({
                model: backupModel,
                messages: [{
                  role: 'user',
                  content
                }] as any
              });
              
              const resp = completion as any;
              responseText = completion.choices[0].message.content || '';
              responseId = resp.id;
              usedModel = resp.model;
              usage = resp.usage;
            } catch (backupError: any) {
              console.error(`Backup model failed, searching for free models...`);
              
              // Try to find a free model
              const freeModel = await findSuitableFreeModel(openai);
              if (freeModel && freeModel !== model && freeModel !== backupModel) {
                console.error(`Trying free model: ${freeModel}`);
                const completion = await openai.chat.completions.create({
                  model: freeModel,
                  messages: [{
                    role: 'user',
                    content
                  }] as any
                });
                
                const resp = completion as any;
                responseText = completion.choices[0].message.content || '';
                responseId = resp.id;
                usedModel = resp.model;
                usage = resp.usage;
              } else {
                throw backupError;
              }
            }
          } else {
            // No backup, try free model directly
            console.error(`Primary model failed, searching for free models...`);
            const freeModel = await findSuitableFreeModel(openai);
            if (freeModel && freeModel !== model) {
              console.error(`Trying free model: ${freeModel}`);
              const completion = await openai.chat.completions.create({
                model: freeModel,
                messages: [{
                  role: 'user',
                  content
                }] as any
              });
              
              const resp = completion as any;
              responseText = completion.choices[0].message.content || '';
              responseId = resp.id;
              usedModel = resp.model;
              usage = resp.usage;
            } else {
              throw primaryError;
            }
          }
        }
        
        // Format as markdown if requested
        if (args.markdown_response) {
          // Simple formatting enhancements
          responseText = responseText
            // Add horizontal rule after sections
            .replace(/^(#{1,3}.*)/gm, '$1\n\n---')
            // Ensure proper spacing for lists
            .replace(/^(\s*[-*•]\s.+)$/gm, '\n$1')
            // Convert plain URLs to markdown links
            .replace(/(https?:\/\/[^\s]+)/g, '[$1]($1)');
        }
        
        // Return the analysis result
        return {
          content: [
            {
              type: 'text',
              text: responseText,
            },
          ],
          metadata: {
            id: responseId,
            model: usedModel,
            usage: usage
          }
        };
      } catch (error: any) {
        console.error('Error in multi-image analysis:', error);
        
        if (error instanceof McpError) {
          throw error;
        }
        
        return {
          content: [
            {
              type: 'text',
              text: `Error analyzing images: ${error.message}`,
            },
          ],
          isError: true,
          metadata: {
            error_type: error.constructor.name,
            error_message: error.message
          }
        };
      }
    }
  • Tool schema definition including input schema for images array, prompt, markdown_response flag, and optional model.
    {
      name: 'mcp_openrouter_multi_image_analysis',
      description: 'Analyze multiple images at once with a single prompt and receive detailed responses',
      inputSchema: {
        type: 'object',
        properties: {
          images: {
            type: 'array',
            description: 'Array of image objects to analyze',
            items: {
              type: 'object',
              properties: {
                url: {
                  type: 'string',
                  description: 'URL or data URL of the image (use http(s):// for web images, absolute file paths for local files, or data:image/xxx;base64,... for base64 encoded images)',
                },
                alt: {
                  type: 'string',
                  description: 'Optional alt text or description of the image',
                },
              },
              required: ['url'],
            },
          },
          prompt: {
            type: 'string',
            description: 'Prompt for analyzing the images',
          },
          markdown_response: {
            type: 'boolean',
            description: 'Whether to format the response in Markdown (default: true)',
            default: true,
          },
          model: {
            type: 'string',
            description: 'OpenRouter model to use. If not specified, the system will use a free model with vision capabilities or the default model.',
          },
        },
        required: ['images', 'prompt'],
      },
    },
  • Registration in the CallToolRequestSchema switch statement that dispatches to the handleMultiImageAnalysis handler function.
    case 'mcp_openrouter_multi_image_analysis':
      return handleMultiImageAnalysis({
        params: {
          arguments: request.params.arguments as unknown as MultiImageAnalysisToolRequest
        }
      }, this.openai, this.defaultModel);
  • TypeScript interface defining the tool request parameters, used for type safety in the handler.
    export interface MultiImageAnalysisToolRequest {
      images: Array<{
        url: string;
        alt?: string;
      }>;
      prompt: string;
      markdown_response?: boolean;
      model?: string;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions receiving 'detailed responses' but doesn't specify format, length, or structure of outputs. It also omits critical details like rate limits, authentication requirements, error handling, or whether the operation is idempotent. For a tool with no annotations and no output schema, this leaves significant gaps in understanding its behavior.

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?

The description is a single, efficient sentence that front-loads the core functionality ('Analyze multiple images at once with a single prompt') and adds value ('receive detailed responses'). There is no wasted text, repetition, or unnecessary elaboration, making it highly concise and well-structured.

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

Completeness2/5

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

Given the complexity of analyzing multiple images with AI, the lack of annotations, and no output schema, the description is incomplete. It doesn't explain what 'detailed responses' entail, potential limitations (e.g., image count, size), or how errors are handled. For a tool with 4 parameters and no structured output documentation, more context is needed to ensure reliable use.

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%, so the input schema fully documents all parameters. The description adds no additional meaning beyond what's in the schema, such as examples of valid prompts or image types. However, it does imply the tool handles multiple images, which aligns with the 'images' array parameter. Given high schema coverage, a baseline score of 3 is appropriate.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Analyze multiple images at once with a single prompt and receive detailed responses.' It specifies the verb ('analyze'), resource ('multiple images'), and scope ('at once'), making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'mcp_openrouter_analyze_image' (single vs. multiple image analysis), which prevents a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'mcp_openrouter_analyze_image' for single-image analysis or 'mcp_openrouter_chat_completion' for non-image tasks, nor does it specify prerequisites, constraints, or exclusions. Usage is implied by the name and description but not explicitly stated.

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/hoangdn3/mcp-ocr-fallback'

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