Skip to main content
Glama

generate_diagram_from_json

Convert JSON data into visual diagrams to illustrate API responses, database schemas, dependency trees, or configuration files. Generate flowcharts, ERDs, system architectures, and other diagram types from structured JSON input.

Instructions

Generate a diagram from a JSON structure. Use this tool when the user wants to visualise JSON data such as API responses, database schemas, dependency trees, configuration files, or any structured data. Pass the raw JSON string as content. Returns a link to view and edit the generated diagram in the browser.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYesA JSON string representing the structure to visualise. This can be API response data, a database schema, a config file, dependency tree, or any other structured JSON. Example: '{"users": [{"id": 1, "orders": [{"id": 101}]}]}'
promptNoInstruction for how to interpret or render the JSON. Example: "Show as an entity relationship diagram with cardinality labels"
diagramTypeNoPreferred diagram type. Defaults to 'erd' for schemas and 'flowchart' for other JSON.
isIconEnabledNoSet to true when the user asks to include icons in the diagram.

Implementation Reference

  • Registration of the 'generate_diagram_from_json' tool using 'registerAppTool'.
    export function registerGenerateJsonTool(server: McpServer): void {
      registerAppTool(
        server,
        "generate_diagram_from_json",
        {
          description:
            "Generate a diagram from a JSON structure. Use this tool when the user wants " +
            "to visualise JSON data such as API responses, database schemas, dependency trees, " +
            "configuration files, or any structured data. " +
            "Pass the raw JSON string as `content`. " +
            "Returns a link to view and edit the generated diagram in the browser.",
          inputSchema,
          _meta: { ui: { resourceUri: DIAGRAM_APP_RESOURCE_URI } },
        },
        async (args) => generateDiagram("json", args)
      );
    }
  • Input schema definition for the 'generate_diagram_from_json' tool.
    const inputSchema = {
      content: z
        .string()
        .min(1)
        .describe(
          "A JSON string representing the structure to visualise. " +
            "This can be API response data, a database schema, a config file, " +
            "dependency tree, or any other structured JSON. " +
            'Example: \'{"users": [{"id": 1, "orders": [{"id": 101}]}]}\''
        ),
      prompt: z
        .string()
        .optional()
        .describe(
          'Instruction for how to interpret or render the JSON. ' +
            'Example: "Show as an entity relationship diagram with cardinality labels"'
        ),
      diagramType: z
        .enum(DIAGRAM_TYPES)
        .optional()
        .describe(
          "Preferred diagram type. Defaults to 'erd' for schemas and 'flowchart' for other JSON."
        ),
      isIconEnabled: z
        .boolean()
        .optional()
        .describe(
          "Set to true when the user asks to include icons in the diagram."
        ),
    };
  • The handler 'generateDiagram' which is invoked by the 'generate_diagram_from_json' tool.
    export async function generateDiagram(
      inputType: GenerateDiagramV2Request["inputType"],
      params: DiagramParams
    ): Promise<CallToolResult> {
      debugLog("Tool called:", { inputType, params: paramsForLog(params) });
    
      const apiKey = getApiKey();
      if (!apiKey) {
        const hint =
          process.env.PORT != null
            ? "Send your API key in the Authorization header (Bearer <key>) or X-ADM-API-Key header."
            : "Set the ADM_API_KEY environment variable.";
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `AI Diagram Maker API key is required. ${hint}`,
            },
          ],
        };
      }
    
      const requestBody: GenerateDiagramV2Request = {
        inputType,
        content: params.content,
        // Request SVG, then rasterize to PNG in this MCP server so icons render in chat.
        format: "svg",
        ...(params.prompt !== undefined && { prompt: params.prompt }),
        ...(params.diagramType !== undefined && {
          diagramType: params.diagramType,
        }),
        options: {
          saveDiagramEnabled: true,
          colorTheme: "pastel-layers",
          ...(isMock() && { useMock: true }),
          ...(isDebug() && { debug: true }),
          ...(params.isIconEnabled && { isIconEnabled: true }),
        },
      };
    
      debugLog("Request payload to AI Diagram Maker API:", payloadForLog(requestBody));
    
      const response = await postApiV2DiagramsGenerate(requestBody);
    
      const responseForLog = {
        status: response.status,
        data: {
          ...response.data,
          ...(typeof (response.data as { svg?: string })?.svg === "string" && {
            svg: truncateForLog((response.data as { svg: string }).svg),
          }),
        },
      };
      debugLog("Generate diagram API response:", responseForLog);
    
      if (response.status === 200) {
        const { svg, text, diagramUrl } = response.data;
    
        const content: CallToolResult["content"] = [];
    
        let textContent = text ?? "";
        if (diagramUrl) {
          const baseUrl = (process.env.ADM_BASE_URL ?? "https://app.aidiagrammaker.com").replace(
            /\/$/,
            ""
          );
          const fullDiagramUrl = diagramUrl.startsWith("/")
            ? `${baseUrl}${diagramUrl}`
            : diagramUrl;
          textContent += `\n\nEdit diagram: ${fullDiagramUrl} (open in browser to view and edit)`;
    
          if (svg) {
            try {
              const diagramId = new URL(fullDiagramUrl).pathname.split("/").filter(Boolean).pop();
              if (diagramId) {
                const inlined = await inlineSvgImages(svg, baseUrl);
                storeSvg(diagramId, inlined);
              }
            } catch {
              // URL parsing failed; image unavailable in App
            }
          }
        }
        if (textContent) {
          content.push({ type: "text", text: textContent });
        }
    
        return { content };
      }
    
      // Handle error responses
      const errorData = response.data as {
        error?: string;
        details?: string;
        rateLimitError?: { retryAfter?: number };
      };
    
      let errorMessage = `API request failed with status ${response.status}`;
    
      if (errorData?.error) {
        errorMessage = errorData.error;
        if (errorData.details) {
          errorMessage += `: ${errorData.details}`;
        }
      }
    
      if (response.status === 429 && errorData?.rateLimitError?.retryAfter) {
        errorMessage += ` (retry after ${errorData.rateLimitError.retryAfter} seconds)`;
      }
    
      return {
        isError: true,
        content: [{ type: "text", text: errorMessage }],
      };
    }

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/erajasekar/ai-diagram-maker-mcp'

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