Skip to main content
Glama

Generate QR Code as Data URL

generate-qrcode-dataurl

Convert text or URLs into QR codes as base64 data URLs for easy embedding in web applications, with customizable options for error correction, size, colors, and image format.

Instructions

Generate a QR code from text or URL and return it as a base64 data URL

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
optionsNoQR code generation options
textYesThe text or URL to encode in the QR code

Implementation Reference

  • The core handler function that implements the tool logic: destructures input, builds QR options, generates data URL with qrcode library, returns image content or error response.
    async ({ text, options = {} }) => {
      try {
        const qrOptions = {
          errorCorrectionLevel: options.errorCorrectionLevel || 'M',
          width: options.width,
          margin: options.margin || defaultMargin,
          color: {
            dark: options.color?.dark || getDefaultDarkColor(),
            light: options.color?.light || getDefaultLightColor()
          }
        };
    
        const dataUrl = await QRCode.toDataURL(text, qrOptions);
        
        return {
          content: [
            {
              type: "text",
              text: `QR code generated successfully for: "${text}"`
            },
            {
              type: "image",
              data: dataUrl,
              mimeType: options.type || "image/png"
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error generating QR code: ${error instanceof Error ? error.message : 'Unknown error'}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod schema defining customizable options for QR code generation (error level, size, margin, colors, output type), used in the tool's inputSchema.
    const QRCodeOptionsSchema = z.object({
      errorCorrectionLevel: z.enum(['L', 'M', 'Q', 'H']).optional().default('M'),
      width: z.number().min(50).max(2000).optional(),
      margin: z.number().min(0).max(10).optional().default(defaultMargin),
      color: z.object({
        dark: z.string().optional().default(getDefaultDarkColor()),
        light: z.string().optional().default(getDefaultLightColor())
      }).optional(),
      type: z.enum(['image/png', 'image/jpeg', 'image/webp']).optional().default('image/png')
    });
  • src/index.ts:29-78 (registration)
    MCP tool registration via server.registerTool, specifying name, metadata (title/description), input schema, and handler function.
    server.registerTool(
      "generate-qrcode-dataurl",
      {
        title: "Generate QR Code as Data URL",
        description: "Generate a QR code from text or URL and return it as a base64 data URL",
        inputSchema: {
          text: z.string().min(1).describe("The text or URL to encode in the QR code"),
          options: QRCodeOptionsSchema.optional().describe("QR code generation options")
        }
      },
      async ({ text, options = {} }) => {
        try {
          const qrOptions = {
            errorCorrectionLevel: options.errorCorrectionLevel || 'M',
            width: options.width,
            margin: options.margin || defaultMargin,
            color: {
              dark: options.color?.dark || getDefaultDarkColor(),
              light: options.color?.light || getDefaultLightColor()
            }
          };
    
          const dataUrl = await QRCode.toDataURL(text, qrOptions);
          
          return {
            content: [
              {
                type: "text",
                text: `QR code generated successfully for: "${text}"`
              },
              {
                type: "image",
                data: dataUrl,
                mimeType: options.type || "image/png"
              }
            ]
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error generating QR code: ${error instanceof Error ? error.message : 'Unknown error'}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • Utility functions providing default hex color values for QR code foreground (dark) and background (light), used in options merging.
    function getDefaultLightColor(): string {
      return '#FFFFFF';
    }
    
    function getDefaultDarkColor(): string {
      return '#000000';
    }
  • Default margin value for QR code generation, used as fallback in options.
    const defaultMargin = 4;
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 states the tool generates and returns a QR code, implying a read-only operation, but doesn't cover aspects like performance (e.g., size limits on input text), error handling, or whether it's idempotent. This leaves gaps for a tool with configurable options.

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 ('generate a QR code') and specifies the input ('from text or URL') and output ('as a base64 data URL') without any wasted words. Every part earns its place.

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 the tool's moderate complexity (2 parameters with nested objects, no output schema, no annotations), the description is adequate but incomplete. It covers the basic purpose and output format, but lacks usage guidelines, behavioral details, and doesn't compensate for the missing output schema (e.g., what the data URL structure looks like).

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 both parameters (text and options with nested properties). The description adds minimal value by mentioning 'text or URL' and 'base64 data URL', but doesn't explain parameter interactions or provide examples. Baseline 3 is appropriate as 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 verb ('generate'), resource ('QR code'), and output format ('base64 data URL'), which distinguishes it from siblings that produce different formats (SVG, terminal, batch). However, it doesn't explicitly mention that it generates a single QR code versus batch processing, which is a minor gap in sibling differentiation.

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 its siblings (generate-qrcode-batch, generate-qrcode-svg, generate-qrcode-terminal). It doesn't mention use cases like needing a data URL for web embedding versus SVG for vector graphics or batch processing for multiple codes.

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/antoBrugnot/qrcode-mcp'

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