Skip to main content
Glama

generate_mermaid_diagram

Create diagrams and charts from Mermaid syntax to visualize concepts, processes, or data structures for documentation and communication.

Instructions

Generate mermaid diagram and chart with mermaid syntax dynamically. Mermaid is a JavaScript based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams. The main purpose of Mermaid is to help documentation catch up with development.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
mermaidYesThe mermaid diagram syntax used to be generated, such as, graph TD; A-->B; A-->C; B-->D; C-->D;.
themeNoTheme for the diagram (optional). Default is 'default'.default
backgroundColorNoBackground color for the diagram (optional). Default is 'white'.white
outputTypeNoThe output type of the diagram. Can be 'base64', 'svg', 'mermaid', 'file', 'svg_url', or 'png_url'. Default is 'base64'. 'base64' returns PNG image as base64 encoded string. 'file' saves the PNG image to disk. The *_url options return public mermaid.ink links for remote-friendly sharing.base64

Implementation Reference

  • Handler function for CallToolRequestSchema that checks if the tool name matches 'generate_mermaid_diagram', validates arguments using the schema, renders the Mermaid diagram with custom theme and background, and returns content based on outputType (base64 image, SVG, URL, file, or raw mermaid).
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name === tool.name) {
        try {
          const args = request.params.arguments || {};
          // Use safeParse instead of parse and try-catch.
          const result = schema.safeParse(args);
          if (!result.success) {
            throw new McpError(
              ErrorCode.InvalidParams,
              `Invalid parameters: ${result.error.message}`,
            );
          }
    
          const { mermaid, theme, backgroundColor, outputType = "base64" } = args;
          const { id, svg, screenshot } = await renderMermaid(
            mermaid as string,
            theme as string,
            backgroundColor as string,
          );
    
          if (outputType === "mermaid") {
            return {
              content: [
                {
                  type: "text",
                  text: mermaid,
                },
              ],
            };
          }
          if (outputType === "svg") {
            return {
              content: [
                {
                  type: "text",
                  text: svg,
                },
              ],
            };
          }
          if (outputType === "svg_url" || outputType === "png_url") {
            const variant = outputType === "svg_url" ? "svg" : "img";
            const url = createMermaidInkUrl(mermaid as string, variant);
            return {
              content: [
                {
                  type: "text",
                  text: url,
                },
              ],
            };
          }
          if (outputType === "file") {
            if (!screenshot) {
              throw new McpError(
                ErrorCode.InternalError,
                "Failed to generate screenshot for file output.",
              );
            }
    
            // Create a unique filename with timestamp and random suffix
            const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
            const randomSuffix = Math.random().toString(36).substring(2, 8);
            const filename = `mermaid-${timestamp}-${randomSuffix}.png`;
    
            // Use current working directory to save the file
            const filePath = path.resolve(process.cwd(), filename);
    
            try {
              fs.writeFileSync(filePath, screenshot);
              return {
                content: [
                  {
                    type: "text",
                    text: `Mermaid diagram saved to file: ${filePath}`,
                  },
                ],
              };
            } catch (fileError) {
              throw new McpError(
                ErrorCode.InternalError,
                `Failed to save file: ${fileError instanceof Error ? fileError.message : "Unknown file error"}`,
              );
            }
          }
          return {
            content: [
              {
                type: "image",
                data: screenshot?.toString("base64"),
                mimeType: "image/png",
              },
            ],
          };
          // biome-ignore lint/suspicious/noExplicitAny: <explanation>
        } catch (error: any) {
          if (error instanceof McpError) throw error;
          throw new McpError(
            ErrorCode.InternalError,
            `Failed to generate mermaid: ${error?.message || "Unknown error."}`,
          );
        }
      } else {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}.`,
        );
      }
    });
  • Zod schema defining the input parameters for the generate_mermaid_diagram tool: mermaid syntax (required), theme, backgroundColor, and outputType.
    export const schema = z.object({
      mermaid: z
        .string()
        .describe(`The mermaid diagram syntax used to be generated, such as, graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;.`)
        .nonempty({ message: "The mermaid string cannot be empty." }),
      theme: z
        .enum(["default", "base", "forest", "dark", "neutral"])
        .describe("Theme for the diagram (optional). Default is 'default'.")
        .optional()
        .default("default"),
      backgroundColor: z
        .string()
        .describe(
          "Background color for the diagram (optional). Default is 'white'.",
        )
        .optional()
        .default("white"),
      outputType: z
        .enum(["base64", "svg", "mermaid", "file", "svg_url", "png_url"])
        .describe(
          "The output type of the diagram. Can be 'base64', 'svg', 'mermaid', 'file', 'svg_url', or 'png_url'. Default is 'base64'. 'base64' returns PNG image as base64 encoded string. 'file' saves the PNG image to disk. The *_url options return public mermaid.ink links for remote-friendly sharing.",
        )
        .optional()
        .default("base64"),
    });
  • src/server.ts:47-49 (registration)
    Registration of the tool in the MCP server's ListToolsRequest handler, exposing the tool metadata.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [tool],
    }));
  • Tool metadata object with name, description, and input schema (converted to JSON schema).
    export const tool = {
      name: "generate_mermaid_diagram",
      description:
        "Generate mermaid diagram and chart with mermaid syntax dynamically. Mermaid is a JavaScript based diagramming and charting tool that uses Markdown-inspired text definitions and a renderer to create and modify complex diagrams. The main purpose of Mermaid is to help documentation catch up with development.",
      inputSchema: zodToJsonSchema(schema),
    };
  • Core helper function that renders Mermaid diagram to SVG and PNG screenshot using mermaid-isomorphic, applies theme and custom background CSS.
    export async function renderMermaid(
      mermaid: string,
      theme = "default",
      backgroundColor = "white",
    ): Promise<RenderResult> {
      if (!renderer) renderer = createMermaidRenderer();
      const cssContent = `svg { background: ${backgroundColor}; }`;
      const cssTmpPath = path.join(os.tmpdir(), "mermaid-tmp-css.css");
      fs.writeFileSync(cssTmpPath, cssContent);
    
      const r = await renderer([mermaid], {
        // Image is needed.
        screenshot: true,
        css: cssTmpPath,
        mermaidConfig: {
          // biome-ignore lint/suspicious/noExplicitAny: <explanation>
          theme: theme as any,
        },
      });
      const r0 = r[0] as PromiseSettledResult<RenderResult>;
      return r0.status === "fulfilled" ? r0.value : Promise.reject(r0.reason);
    }
  • Helper to generate public mermaid.ink URLs for SVG or PNG by deflate-compressing and base64url-encoding the mermaid syntax.
    export function createMermaidInkUrl(
      mermaid: string,
      variant: "svg" | "img",
    ): string {
      const encoded = encodeMermaidToBase64Url(mermaid);
      return `https://mermaid.ink/${variant}/pako:${encoded}`;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it mentions the tool generates diagrams 'dynamically,' it fails to describe critical behaviors: whether this is a read-only or mutation operation, what permissions are needed, how errors are handled, rate limits, or what the output looks like. The description focuses on Mermaid's general purpose rather than this specific tool's behavior.

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

Conciseness3/5

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

The description is reasonably concise but not optimally structured. The first sentence clearly states the tool's purpose, but the following sentences explain Mermaid's general capabilities rather than focusing on this specific tool's functionality. While not excessively verbose, some content doesn't directly help an agent understand how to use this tool.

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 tool's complexity (4 parameters, no output schema, no annotations), the description is insufficiently complete. It doesn't explain what the tool returns, how to interpret results, error conditions, or practical usage scenarios. While the schema covers parameters well, the description fails to provide the contextual understanding needed for effective tool invocation.

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%, providing comprehensive parameter documentation. The description adds no parameter-specific information beyond what's already in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline score is 3 even with no parameter details in the description.

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: 'Generate mermaid diagram and chart with mermaid syntax dynamically.' It specifies the verb ('generate'), resource ('mermaid diagram and chart'), and technology context ('mermaid syntax'). However, without sibling tools to distinguish from, it cannot achieve the highest score of 5 which requires explicit 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 alternatives. It explains what Mermaid is ('a JavaScript based diagramming and charting tool') and its broader purpose ('help documentation catch up with development'), but offers no practical usage context, prerequisites, or comparison to other diagramming methods.

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/hustcc/mcp-mermaid'

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