Skip to main content
Glama

generate_mermaid_diagram

Create dynamic Mermaid diagrams and charts using Mermaid syntax. Input text definitions to generate diagrams in PNG, SVG, or Mermaid format with customizable themes and background colors. Ideal for enhancing documentation and visualizing complex processes.

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

NameRequiredDescriptionDefault
backgroundColorNoBackground color for the diagram (optional). Default is 'white'.white
mermaidYesThe mermaid diagram syntax used to be generated, such as, graph TD; A-->B; A-->C; B-->D; C-->D;.
outputTypeNoThe output type of the diagram. Can be 'png', 'svg' or 'mermaid'. Default is 'png'.png
themeNoTheme for the diagram (optional). Default is 'default'.default

Input Schema (JSON Schema)

{ "$schema": "http://json-schema.org/draft-07/schema#", "properties": { "backgroundColor": { "default": "white", "description": "Background color for the diagram (optional). Default is 'white'.", "type": "string" }, "mermaid": { "description": "The mermaid diagram syntax used to be generated, such as, graph TD;\nA-->B;\nA-->C;\nB-->D;\nC-->D;.", "minLength": 1, "type": "string" }, "outputType": { "default": "png", "description": "The output type of the diagram. Can be 'png', 'svg' or 'mermaid'. Default is 'png'.", "enum": [ "png", "svg", "mermaid" ], "type": "string" }, "theme": { "default": "default", "description": "Theme for the diagram (optional). Default is 'default'.", "enum": [ "default", "base", "forest", "dark", "neutral" ], "type": "string" } }, "required": [ "mermaid" ], "type": "object" }

Implementation Reference

  • MCP CallToolRequestSchema handler implementing the generate_mermaid_diagram tool: input validation with schema, rendering via renderMermaid, output handling for base64/png image, svg text, urls, file save, and mermaid text.
    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 input schema for the tool defining parameters: mermaid syntax string, optional 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"), });
  • Tool registration metadata: 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), };
  • Helper function to render mermaid diagram to SVG and PNG screenshot using mermaid-isomorphic renderer, 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 shareable mermaid.ink URLs (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}`; }

Other Tools

Related 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