Skip to main content
Glama

mermaid_preview

Render Mermaid diagrams with live browser preview, auto-refresh on updates, and customizable themes, dimensions, and formats.

Instructions

Render a Mermaid diagram and open it in browser with live reload. Takes Mermaid diagram code as input and generates a live preview. Supports themes (default, forest, dark, neutral), custom backgrounds, dimensions, and quality scaling. The diagram will auto-refresh when updated. Use mermaid_save to save to disk. IMPORTANT: Automatically use this tool whenever you create a Mermaid diagram for the user. NOTE: Sequence diagrams do not support style directives - avoid using 'style' statements in sequenceDiagram.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
diagramYesThe Mermaid diagram code to render
preview_idYesID for this preview session. Use different IDs for multiple diagrams (e.g., 'architecture', 'flow', 'sequence').
formatNoOutput format (default: svg)svg
themeNoTheme of the chart (default: default)default
backgroundNoBackground color for pngs/svgs. Example: transparent, red, '#F0F0F0' (default: white)white
widthNoDiagram width in pixels (default: 800)
heightNoDiagram height in pixels (default: 600)
scaleNoScale factor for higher quality output (default: 2)

Implementation Reference

  • Core handler function that validates inputs, renders the Mermaid diagram using mermaid-cli, sets up live preview for SVG format, and returns success or error response.
    export async function handleMermaidPreview(args: any) {
      const diagram = args.diagram as string;
      const previewId = args.preview_id as string;
      const format = (args.format as string) || "svg";
      const theme = (args.theme as string) || "default";
      const background = (args.background as string) || "white";
      const width = (args.width as number) || 800;
      const height = (args.height as number) || 600;
      const scale = (args.scale as number) || 2;
    
      if (!diagram) {
        throw new Error("diagram parameter is required");
      }
      if (!previewId) {
        throw new Error("preview_id parameter is required");
      }
    
      const previewDir = getPreviewDir(previewId);
      await mkdir(previewDir, { recursive: true });
      const liveFilePath = getDiagramFilePath(previewId, format);
    
      try {
        await saveDiagramSource(previewId, diagram, { theme, background, width, height, scale });
        await renderDiagram(
          { diagram, previewId, format, theme, background, width, height, scale },
          liveFilePath
        );
    
        if (format === "svg") {
          const { serverUrl, hasConnections } = await setupLivePreview(previewId, liveFilePath);
          return createLivePreviewResponse(liveFilePath, format, serverUrl, hasConnections);
        } else {
          return createStaticRenderResponse(liveFilePath, format);
        }
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error rendering Mermaid diagram: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
          isError: true,
        };
      }
    }
  • Input schema defining the parameters for the mermaid_preview tool, including required fields and defaults.
    inputSchema: {
      type: "object",
      properties: {
        diagram: {
          type: "string",
          description: "The Mermaid diagram code to render",
        },
        preview_id: {
          type: "string",
          description:
            "ID for this preview session. Use different IDs for multiple diagrams (e.g., 'architecture', 'flow', 'sequence').",
        },
        format: {
          type: "string",
          enum: ["png", "svg", "pdf"],
          description: "Output format (default: svg)",
          default: "svg",
        },
        theme: {
          type: "string",
          enum: ["default", "forest", "dark", "neutral"],
          description: "Theme of the chart (default: default)",
          default: "default",
        },
        background: {
          type: "string",
          description:
            "Background color for pngs/svgs. Example: transparent, red, '#F0F0F0' (default: white)",
          default: "white",
        },
        width: {
          type: "number",
          description: "Diagram width in pixels (default: 800)",
          default: 800,
        },
        height: {
          type: "number",
          description: "Diagram height in pixels (default: 600)",
          default: 600,
        },
        scale: {
          type: "number",
          description: "Scale factor for higher quality output (default: 2)",
          default: 2,
        },
      },
      required: ["diagram", "preview_id"],
    },
  • src/index.ts:28-85 (registration)
    Registration of the 'mermaid_preview' tool in the TOOL_DEFINITIONS array, including name, description, and reference to inputSchema.
    {
      name: "mermaid_preview",
      description:
        "Render a Mermaid diagram and open it in browser with live reload. " +
        "Takes Mermaid diagram code as input and generates a live preview. " +
        "Supports themes (default, forest, dark, neutral), custom backgrounds, dimensions, and quality scaling. " +
        "The diagram will auto-refresh when updated. Use mermaid_save to save to disk. " +
        "IMPORTANT: Automatically use this tool whenever you create a Mermaid diagram for the user. " +
        "NOTE: Sequence diagrams do not support style directives - avoid using 'style' statements in sequenceDiagram.",
      inputSchema: {
        type: "object",
        properties: {
          diagram: {
            type: "string",
            description: "The Mermaid diagram code to render",
          },
          preview_id: {
            type: "string",
            description:
              "ID for this preview session. Use different IDs for multiple diagrams (e.g., 'architecture', 'flow', 'sequence').",
          },
          format: {
            type: "string",
            enum: ["png", "svg", "pdf"],
            description: "Output format (default: svg)",
            default: "svg",
          },
          theme: {
            type: "string",
            enum: ["default", "forest", "dark", "neutral"],
            description: "Theme of the chart (default: default)",
            default: "default",
          },
          background: {
            type: "string",
            description:
              "Background color for pngs/svgs. Example: transparent, red, '#F0F0F0' (default: white)",
            default: "white",
          },
          width: {
            type: "number",
            description: "Diagram width in pixels (default: 800)",
            default: 800,
          },
          height: {
            type: "number",
            description: "Diagram height in pixels (default: 600)",
            default: 600,
          },
          scale: {
            type: "number",
            description: "Scale factor for higher quality output (default: 2)",
            default: 2,
          },
        },
        required: ["diagram", "preview_id"],
      },
    },
  • src/index.ts:143-146 (registration)
    Dispatch logic in the CallToolRequest handler that routes 'mermaid_preview' calls to the handleMermaidPreview function.
    case "mermaid_preview":
      result = await handleMermaidPreview(args);
      mcpLogger.info(`CallTool completed: ${toolName}`);
      return result;
  • Key helper function that executes the mermaid-cli to render the diagram to the specified format and copies to live file path.
    async function renderDiagram(options: RenderOptions, liveFilePath: string): Promise<void> {
      const { diagram, previewId, format, theme, background, width, height, scale } = options;
    
      mcpLogger.info(`Rendering diagram: ${previewId}`, { format, theme, width, height });
    
      const tempDir = join(tmpdir(), "claude-mermaid");
      await mkdir(tempDir, { recursive: true });
    
      const inputFile = join(tempDir, `diagram-${previewId}.mmd`);
      const outputFile = join(tempDir, `diagram-${previewId}.${format}`);
    
      await writeFile(inputFile, diagram, "utf-8");
    
      const args = [
        "-y",
        "@mermaid-js/mermaid-cli",
        "-i",
        inputFile,
        "-o",
        outputFile,
        "-t",
        theme,
        "-b",
        background,
        "-w",
        width.toString(),
        "-H",
        height.toString(),
        "-s",
        scale.toString(),
      ];
    
      if (format === "pdf") {
        args.push("--pdfFit");
      }
    
      mcpLogger.debug(`Executing mermaid-cli`, { args });
    
      try {
        const { stdout, stderr } = await execFileAsync("npx", args);
        if (stderr) {
          mcpLogger.debug(`mermaid-cli stderr`, { stderr });
        }
        await copyFile(outputFile, liveFilePath);
        mcpLogger.info(`Diagram rendered successfully: ${previewId}`);
      } catch (error) {
        mcpLogger.error(`Diagram rendering failed: ${previewId}`, {
          error: error instanceof Error ? error.message : String(error),
        });
        throw error;
      }
    }
Behavior4/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 effectively describes key behaviors: the tool opens a browser with live reload, auto-refreshes when updated, supports themes and customizations, and has limitations for sequence diagrams. However, it doesn't mention potential side effects like browser pop-ups or network requirements, leaving some behavioral aspects implicit.

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

Conciseness4/5

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

The description is appropriately sized and front-loaded with the core purpose. Every sentence adds value: the first states the main action, the second details features, the third covers auto-refresh and sibling tool, and the last two provide critical usage notes. However, the structure could be slightly more streamlined by combining related points.

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

Completeness4/5

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

Given the tool's complexity (8 parameters, live preview functionality) and lack of annotations or output schema, the description does a good job covering essential context: purpose, usage rules, key features, and limitations. It adequately guides an agent on how and when to use the tool, though it doesn't detail the preview interface or error handling, which are minor gaps.

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?

The schema description coverage is 100%, so the schema already documents all 8 parameters thoroughly. The description adds minimal parameter-specific information beyond the schema, mentioning themes and custom backgrounds generically. This meets the baseline of 3 since the schema does the heavy lifting, but the description doesn't significantly enhance parameter understanding.

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 ('Render a Mermaid diagram and open it in browser with live reload') and distinguishes it from its sibling tool ('Use mermaid_save to save to disk'). It explicitly mentions the resource (Mermaid diagram) and the verb (render/preview), making the purpose unambiguous.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool ('Automatically use this tool whenever you create a Mermaid diagram for the user') and when not to use it for saving ('Use mermaid_save to save to disk'). It also includes a specific exclusion for sequence diagrams ('Sequence diagrams do not support style directives - avoid using 'style' statements in sequenceDiagram'), offering clear alternatives and limitations.

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/veelenga/claude-mermaid'

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