Skip to main content
Glama

generate-image-from-library

Generate customized images from Orshot library templates by applying text replacements, color changes, and other modifications in PNG, JPG, or PDF formats.

Instructions

Generate an image from an Orshot library template using specified modifications

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
apiKeyNoOrshot API key for authentication (optional if set in environment)
templateIdYesThe ID of the library template to use
modificationsNoObject containing modifications to apply to the template (e.g., text replacements, color changes)
formatNoOutput format for the generated imagepng
responseTypeNoResponse type: base64 data, download URL, or binary dataurl

Implementation Reference

  • Main execution logic for the tool: validates apiKey and templateId, makes POST request to Orshot /v1/generate/images endpoint with modifications, handles response types (url with markdown link, base64/binary as JSON), uses shared makeOrShotRequest helper with retries.
        const { apiKey, templateId, modifications, format, responseType } = args;
        
        // Validate template ID
        const templateValidation = validateTemplateId(templateId);
        if (!templateValidation.isValid) {
          return {
            content: [
              {
                type: "text",
                text: `āŒ Invalid template ID: ${templateValidation.error}`,
              },
            ],
          };
        }
        
        const actualApiKey = apiKey || DEFAULT_API_KEY;
        
        if (!actualApiKey) {
          return {
            content: [
              {
                type: "text",
                text: "āŒ No API key provided. Please provide an API key parameter or set ORSHOT_API_KEY environment variable.",
              },
            ],
          };
        }
    
        // Validate API key
        const keyValidation = validateApiKey(actualApiKey);
        if (!keyValidation.isValid) {
          return {
            content: [
              {
                type: "text",
                text: `āŒ Invalid API key: ${keyValidation.error}`,
              },
            ],
          };
        }
        const requestBody = {
          templateId: templateValidation.sanitized,
          modifications: modifications,
          response: {
            type: responseType,
            format: format
          },
          source: "orshot-mcp-server"
        };
    
        const response = await makeOrShotRequest<OrShotLibraryResponse>(
          `${ORSHOT_API_BASE}/v1/generate/images`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${actualApiKey}`,
            },
            body: JSON.stringify(requestBody),
          }
        );
    
        if (!response) {
          return {
            content: [
              {
                type: "text",
                text: "āŒ Failed to generate image from library template. Please check your API key and template ID, or try again later.",
              },
            ],
          };
        }
    
        const { data } = response;
        
        // Debug logging to understand response structure
        console.error("Response debug info:", {
          responseType,
          hasData: !!response.data,
          dataType: typeof response.data,
          dataLength: response.data ? response.data.length : 0,
          dataPrefix: response.data ? response.data.substring(0, 20) : 'none',
          hasUrl: !!response.url,
          taskId: response.task_id,
          status: response.status
        });
        
        // Create raw response display (truncate data for readability)
        const responseForDisplay = {
          ...response,
          data: response.data ? 
            (response.data.length > 100 ? 
              `${response.data.substring(0, 100)}... (truncated, total length: ${response.data.length})` : 
              response.data) : 
            response.data
        };
        
        // Handle different response types
        if (responseType === "url" && response.url) {
          // Default case: Return clickable "View Generated Image" link for URL responses
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    šŸ–¼ļø **[View Generated Image](${response.url})**
    
    Task ID: ${response.task_id || 'Not available'}
    Status: ${response.status || 'Unknown'}`,
              },
            ],
          };
        } else if (responseType === "base64" && response.data && typeof response.data === 'string' && response.data.startsWith('data:image/')) {
          // Return the raw JSON for base64 responses (with truncated data)
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
              },
            ],
          };
        } else if (responseType === "binary") {
          // Return the raw JSON for binary responses
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
              },
            ],
          };
        }
        
        // Fallback to text response
        return {
          content: [
            {
              type: "text",
              text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
            },
          ],
        };
      }
    );
  • Zod input schema defining parameters for the tool: apiKey (optional), required templateId, modifications object, format (png/jpg/pdf), responseType (base64/url/binary).
      apiKey: z.string().optional().describe("Orshot API key for authentication (optional if set in environment)"),
      templateId: z.string().describe("The ID of the library template to use"),
      modifications: z.record(z.any()).default({}).describe("Object containing modifications to apply to the template (e.g., text replacements, color changes)"),
      format: z.enum(["png", "jpg", "pdf"]).default("png").describe("Output format for the generated image"),
      responseType: z.enum(["base64", "url", "binary"]).default("url").describe("Response type: base64 data, download URL, or binary data"),
    },
    async (args) => {
  • src/index.ts:471-641 (registration)
    MCP server.tool registration call that registers the 'generate-image-from-library' tool with its description, Zod schema, and handler function.
      "generate-image-from-library",
      "Generate an image from an Orshot library template using specified modifications",
      {
        apiKey: z.string().optional().describe("Orshot API key for authentication (optional if set in environment)"),
        templateId: z.string().describe("The ID of the library template to use"),
        modifications: z.record(z.any()).default({}).describe("Object containing modifications to apply to the template (e.g., text replacements, color changes)"),
        format: z.enum(["png", "jpg", "pdf"]).default("png").describe("Output format for the generated image"),
        responseType: z.enum(["base64", "url", "binary"]).default("url").describe("Response type: base64 data, download URL, or binary data"),
      },
      async (args) => {
        const { apiKey, templateId, modifications, format, responseType } = args;
        
        // Validate template ID
        const templateValidation = validateTemplateId(templateId);
        if (!templateValidation.isValid) {
          return {
            content: [
              {
                type: "text",
                text: `āŒ Invalid template ID: ${templateValidation.error}`,
              },
            ],
          };
        }
        
        const actualApiKey = apiKey || DEFAULT_API_KEY;
        
        if (!actualApiKey) {
          return {
            content: [
              {
                type: "text",
                text: "āŒ No API key provided. Please provide an API key parameter or set ORSHOT_API_KEY environment variable.",
              },
            ],
          };
        }
    
        // Validate API key
        const keyValidation = validateApiKey(actualApiKey);
        if (!keyValidation.isValid) {
          return {
            content: [
              {
                type: "text",
                text: `āŒ Invalid API key: ${keyValidation.error}`,
              },
            ],
          };
        }
        const requestBody = {
          templateId: templateValidation.sanitized,
          modifications: modifications,
          response: {
            type: responseType,
            format: format
          },
          source: "orshot-mcp-server"
        };
    
        const response = await makeOrShotRequest<OrShotLibraryResponse>(
          `${ORSHOT_API_BASE}/v1/generate/images`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${actualApiKey}`,
            },
            body: JSON.stringify(requestBody),
          }
        );
    
        if (!response) {
          return {
            content: [
              {
                type: "text",
                text: "āŒ Failed to generate image from library template. Please check your API key and template ID, or try again later.",
              },
            ],
          };
        }
    
        const { data } = response;
        
        // Debug logging to understand response structure
        console.error("Response debug info:", {
          responseType,
          hasData: !!response.data,
          dataType: typeof response.data,
          dataLength: response.data ? response.data.length : 0,
          dataPrefix: response.data ? response.data.substring(0, 20) : 'none',
          hasUrl: !!response.url,
          taskId: response.task_id,
          status: response.status
        });
        
        // Create raw response display (truncate data for readability)
        const responseForDisplay = {
          ...response,
          data: response.data ? 
            (response.data.length > 100 ? 
              `${response.data.substring(0, 100)}... (truncated, total length: ${response.data.length})` : 
              response.data) : 
            response.data
        };
        
        // Handle different response types
        if (responseType === "url" && response.url) {
          // Default case: Return clickable "View Generated Image" link for URL responses
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    šŸ–¼ļø **[View Generated Image](${response.url})**
    
    Task ID: ${response.task_id || 'Not available'}
    Status: ${response.status || 'Unknown'}`,
              },
            ],
          };
        } else if (responseType === "base64" && response.data && typeof response.data === 'string' && response.data.startsWith('data:image/')) {
          // Return the raw JSON for base64 responses (with truncated data)
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
              },
            ],
          };
        } else if (responseType === "binary") {
          // Return the raw JSON for binary responses
          return {
            content: [
              {
                type: "text",
                text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
              },
            ],
          };
        }
        
        // Fallback to text response
        return {
          content: [
            {
              type: "text",
              text: `Image generated successfully from library template!
    
    **Raw API Response:**
    \`\`\`json
    ${JSON.stringify(responseForDisplay, null, 2)}
    \`\`\``,
            },
          ],
        };
      }
    );
  • Helper function to validate and sanitize the library templateId input, used in the handler.
    function validateTemplateId(templateId: string): { isValid: boolean; sanitized: string; error?: string } {
      if (!templateId || typeof templateId !== 'string') {
        const error = 'Template ID is required and must be a string';
        logger.validation('template-id', false, error);
        return { isValid: false, sanitized: '', error };
      }
      
      const sanitized = templateId.trim();
      if (sanitized.length === 0) {
        const error = 'Template ID cannot be empty';
        logger.validation('template-id', false, error);
        return { isValid: false, sanitized: '', error };
      }
      
      if (sanitized.length > config.security.maxTemplateIdLength) {
        const error = `Template ID is too long (max ${config.security.maxTemplateIdLength} characters)`;
        logger.validation('template-id', false, error);
        return { isValid: false, sanitized: '', error };
      }
      
      // Allow alphanumeric, hyphens, underscores for library templates and numbers for studio templates
      if (!/^[a-zA-Z0-9_-]+$/.test(sanitized)) {
        const error = 'Template ID contains invalid characters';
        logger.validation('template-id', false, error);
        return { isValid: false, sanitized: '', error };
      }
      
      logger.validation('template-id', true);
      return { isValid: true, sanitized };
    }
  • Shared helper for making API requests to Orshot with retry logic, timeout, auth headers, and comprehensive error handling, used by the handler for the generation request.
    async function makeOrShotRequest<T>(
      url: string,
      options: RequestInit = {},
      retries: number = config.api.retries
    ): Promise<T | null> {
      let lastError: Error | null = null;
      
      logger.time(`API Request: ${url}`);
      
      for (let attempt = 1; attempt <= retries; attempt++) {
        try {
          const controller = new AbortController();
          const timeoutId = setTimeout(() => controller.abort(), config.api.timeout);
          
          const response = await fetch(url, {
            ...options,
            headers: {
              "Content-Type": "application/json",
              "User-Agent": `${config.server.name}/${config.server.version}`,
              ...options.headers,
            },
            signal: controller.signal,
          });
    
          clearTimeout(timeoutId);
    
          if (!response.ok) {
            const errorText = await response.text();
            let errorMessage = `HTTP ${response.status} ${response.statusText}`;
            
            try {
              const errorData = JSON.parse(errorText);
              errorMessage = errorData.message || errorData.error || errorMessage;
            } catch {
              // Use the raw error text if JSON parsing fails
              errorMessage = errorText || errorMessage;
            }
            
            logger.apiRequest(options.method || 'GET', url, response.status);
            throw new Error(errorMessage);
          }
    
          const result = await response.json();
          logger.apiRequest(options.method || 'GET', url, response.status);
          logger.timeEnd(`API Request: ${url}`);
          return result as T;
        } catch (error) {
          lastError = error instanceof Error ? error : new Error(String(error));
          
          if (error instanceof Error && error.name === 'AbortError') {
            logger.error(`Request timeout on attempt ${attempt}/${retries}`, { url, timeout: config.api.timeout });
          } else {
            logger.error(`Request failed on attempt ${attempt}/${retries}`, { url, error: lastError.message });
          }
          
          // Don't retry for certain error types
          if (error instanceof Error && 
              (error.message.includes('401') || error.message.includes('403') || error.message.includes('404'))) {
            break;
          }
          
          if (attempt < retries) {
            // Exponential backoff with configurable delay
            const delay = Math.pow(2, attempt - 1) * config.api.retryDelay;
            await new Promise(resolve => setTimeout(resolve, delay));
            logger.debug(`Retrying request after ${delay}ms delay`, { url, attempt: attempt + 1, retries });
          }
        }
      }
      
      logger.error("All retry attempts failed", { url, error: lastError?.message });
      logger.timeEnd(`API Request: ${url}`);
      return null;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'specified modifications' but doesn't explain what happens during generation (e.g., processing time, error handling, or output characteristics). For a tool that creates content, this lack of detail on behavior is a significant gap.

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 purpose without unnecessary words. Every part earns its place by specifying the action, resource, and key input aspect. It's appropriately sized for the tool's complexity.

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?

Given 5 parameters with full schema coverage but no annotations or output schema, the description is minimally adequate. It covers the basic purpose but lacks behavioral details (e.g., what the output looks like, error cases) and usage context. For a generation tool with no output schema, more completeness would be helpful.

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 schema fully documents all 5 parameters. The description adds minimal value beyond the schema by implying modifications are applied to templates, but doesn't provide additional context like examples or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

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 action ('generate an image') and resource ('from an Orshot library template'), specifying the source of templates. It distinguishes from 'generate-image' (general) and 'generate-image-from-studio' (different source), but doesn't explicitly mention sibling differentiation. The purpose is specific and actionable.

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 like 'generate-image' or 'generate-image-from-studio'. It mentions the template source but doesn't explain why to choose library templates over studio templates or other options. No prerequisites or exclusions are 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/rishimohan/orshot-mcp-server'

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