Skip to main content
Glama

generate_treemap_chart

Generate a treemap chart to display hierarchical data and compare items at the same level, such as disk space usage. Provide nested data with names and values; output as PNG, SVG, or ECharts option.

Instructions

Generate a treemap chart to display hierarchical data and can intuitively show comparisons between items at the same level, such as, show disk space usage with treemap.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dataYesData for treemap chart, such as, [{ name: 'Design', value: 70, children: [{ name: 'Tech', value: 20 }] }].
heightNoSet the height of the chart, default is 600px.
themeNoSet the theme for the chart, optional, default is 'default'.default
titleNoSet the title of the chart.
widthNoSet the width of the chart, default is 800px.
outputTypeNoThe output type of the diagram. Can be 'png', 'svg' or 'option'. Default is 'png', 'png' will return the rendered PNG image, 'svg' will return the rendered SVG string, and 'option' will return the valid ECharts option.png

Implementation Reference

  • The main tool definition for generate_treemap_chart, including the 'run' async handler function that creates the treemap ECharts option and calls generateChartImage.
    export const generateTreemapChartTool = {
      name: "generate_treemap_chart",
      description:
        "Generate a treemap chart to display hierarchical data and can intuitively show comparisons between items at the same level, such as, show disk space usage with treemap.",
      inputSchema: z.object({
        data: z
          .array(TreeNodeSchema)
          .describe(
            "Data for treemap chart, such as, [{ name: 'Design', value: 70, children: [{ name: 'Tech', value: 20 }] }].",
          )
          .nonempty({ message: "Treemap chart data cannot be empty." }),
        height: HeightSchema,
        theme: ThemeSchema,
        title: TitleSchema,
        width: WidthSchema,
        outputType: OutputTypeSchema,
      }),
      run: async (params: {
        data: Array<TreemapDataType>;
        height: number;
        theme?: "default" | "dark";
        title?: string;
        width: number;
        outputType?: "png" | "svg" | "option";
      }) => {
        const { data, height, theme, title, width, outputType } = params;
    
        const series: Array<SeriesOption> = [
          {
            type: "treemap",
            data: data,
            left: "3%",
            right: "3%",
            bottom: "3%",
            label: {
              show: true,
              formatter: "{b}",
              fontSize: 12,
              color: "#fff",
            },
            emphasis: {
              focus: "descendant",
              itemStyle: {
                borderWidth: 3,
              },
              label: {
                fontSize: 16,
              },
            },
            breadcrumb: {
              show: false,
            },
            roam: false,
            nodeClick: "zoomToNode",
          },
        ];
    
        const echartsOption: EChartsOption = {
          series,
          title: {
            left: "center",
            text: title,
          },
          tooltip: {
            trigger: "item",
          },
        };
    
        return await generateChartImage(
          echartsOption,
          width,
          height,
          theme,
          outputType,
          "generate_treemap_chart",
        );
      },
    };
  • Input schema for the generate_treemap_chart tool using Zod, defining data (array of TreeNodeSchema), height, theme, title, width, and outputType.
    inputSchema: z.object({
      data: z
        .array(TreeNodeSchema)
        .describe(
          "Data for treemap chart, such as, [{ name: 'Design', value: 70, children: [{ name: 'Tech', value: 20 }] }].",
        )
        .nonempty({ message: "Treemap chart data cannot be empty." }),
      height: HeightSchema,
      theme: ThemeSchema,
      title: TitleSchema,
      width: WidthSchema,
      outputType: OutputTypeSchema,
    }),
  • createHierarchicalSchema helper function used to build the recursive TreeNodeSchema for hierarchical treemap data (up to depth 5).
    /**
     * Creates a hierarchical schema with explicit nesting to avoid unresolvable $ref.
     * This helper generates nested schemas up to the specified depth to ensure compatibility
     * with strict JSON Schema clients like PydanticAI that don't support relative $ref paths.
     *
     * @param nameDesc - Description for the name field
     * @param valueDesc - Description for the value field
     * @param valueOptional - Whether the value field is optional
     * @param depth - Maximum nesting depth (default: 5)
     * @returns A Zod schema with explicit nesting
     */
    export function createHierarchicalSchema(
      nameDesc: string,
      valueDesc: string,
      valueOptional: boolean,
      depth = 5,
      // biome-ignore lint/suspicious/noExplicitAny: This helper needs to return flexible types for different use cases
    ): any {
      // Build from deepest level up
      let currentLevel = z.object({
        name: z.string().describe(nameDesc),
        value: valueOptional
          ? z.number().optional().describe(valueDesc)
          : z.number().describe(valueDesc),
      });
    
      // Build each level from depth to 1
      for (let i = depth - 1; i >= 1; i--) {
        const childLevel = currentLevel;
        currentLevel = z.object({
          name: z.string().describe(nameDesc),
          value: valueOptional
            ? z.number().optional().describe(valueDesc)
            : z.number().describe(valueDesc),
          children: z
            .array(childLevel)
            .optional()
            .describe("Child nodes for hierarchical structure."),
        }) as typeof currentLevel;
      }
    
      return currentLevel;
    }
  • Import and registration of generateTreemapChartTool in the tools array (line 31) and re-export (line 53).
    import { generateTreemapChartTool } from "./treemap";
    
    export const tools = [
      generateEChartsTool,
      generateAreaChartTool,
      generateLineChartTool,
      generateBarChartTool,
      generatePieChartTool,
      generateRadarChartTool,
      generateScatterChartTool,
      generateSankeyChartTool,
      generateFunnelChartTool,
      generateGaugeChartTool,
      generateTreemapChartTool,
      generateSunburstChartTool,
      generateHeatmapChartTool,
      generateCandlestickChartTool,
      generateBoxplotChartTool,
      generateGraphChartTool,
      generateParallelChartTool,
      generateTreeChartTool,
    ];
    
    // Re-export individual tools for convenient use in tests and other places
    export {
      generateEChartsTool,
      generateAreaChartTool,
      generateLineChartTool,
      generateBarChartTool,
      generatePieChartTool,
      generateRadarChartTool,
      generateScatterChartTool,
      generateSankeyChartTool,
      generateFunnelChartTool,
      generateGaugeChartTool,
      generateTreemapChartTool,
      generateSunburstChartTool,
      generateHeatmapChartTool,
      generateCandlestickChartTool,
      generateBoxplotChartTool,
      generateGraphChartTool,
      generateParallelChartTool,
      generateTreeChartTool,
    };
  • generateChartImage helper function that renders the ECharts option and returns the image (Base64, MinIO URL, SVG, or option JSON) based on configuration.
    export async function generateChartImage(
      echartsOption: EChartsOption,
      width = 800,
      height = 600,
      theme: "default" | "dark" = "default",
      outputType: ImageOutputFormat = "png",
      toolName = "unknown",
    ): Promise<ImageHandlerResult> {
      // Debug logging
      if (process.env.DEBUG_MCP_ECHARTS) {
        console.error(`[DEBUG] ${toolName} generating chart:`, {
          width,
          height,
          theme,
          outputType,
          optionKeys: Object.keys(echartsOption),
        });
      }
    
      try {
        // Render chart
        const result = await renderECharts(
          echartsOption,
          width,
          height,
          theme,
          outputType,
        );
    
        // Determine output type
        const isImage = outputType !== "svg" && outputType !== "option";
    
        if (!isImage) {
          // SVG or configuration options, return text directly
          const response = {
            content: [
              {
                type: "text" as const,
                text: result as string,
              },
            ],
          };
    
          if (process.env.DEBUG_MCP_ECHARTS) {
            console.error(`[DEBUG] ${toolName} chart generated successfully:`, {
              contentType: "text",
              textLength: (result as string).length,
            });
          }
    
          return response;
        }
    
        // PNG image type
        const buffer = result as Buffer;
    
        if (isMinIOConfigured()) {
          try {
            // Use MinIO storage, return URL
            const url = await storeBufferToMinIO(buffer, "png", "image/png");
    
            const response = {
              content: [
                {
                  type: "text" as const,
                  text: url,
                },
              ],
            };
    
            if (process.env.DEBUG_MCP_ECHARTS) {
              console.error(`[DEBUG] ${toolName} chart generated successfully:`, {
                contentType: "text",
                url: url,
              });
            }
    
            return response;
          } catch (minioError) {
            // MinIO failed, log warning and fallback to Base64
            if (process.env.DEBUG_MCP_ECHARTS) {
              console.error(
                `[DEBUG] ${toolName} MinIO storage failed, falling back to Base64:`,
                {
                  error:
                    minioError instanceof Error
                      ? minioError.message
                      : String(minioError),
                },
              );
            }
            // Continue to Base64 fallback below
          }
        }
    
        // Fallback to Base64
        const base64Data = buffer.toString("base64");
    
        const response = {
          content: [
            {
              type: "image" as const,
              data: base64Data,
              mimeType: "image/png",
            },
          ],
        };
    
        if (process.env.DEBUG_MCP_ECHARTS) {
          console.error(`[DEBUG] ${toolName} chart generated successfully:`, {
            contentType: "image",
            dataLength: base64Data.length,
          });
        }
    
        return response;
      } catch (error) {
        // Error logging
        if (process.env.DEBUG_MCP_ECHARTS) {
          console.error(`[DEBUG] ${toolName} chart generation failed:`, {
            error: error instanceof Error ? error.message : String(error),
            stack: error instanceof Error ? error.stack : undefined,
          });
        }
    
        throw new Error(
          `Chart rendering failed: ${
            error instanceof Error ? error.message : String(error)
          }`,
        );
      }
    }
Behavior2/5

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

No annotations are provided, so the description must disclose behaviors. It does not mention side effects, permissions, output format details, or any limitations. The outputType parameter is in the schema but not highlighted in the description.

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 a single sentence with an example, which is concise and front-loaded with the main purpose. It efficiently communicates the tool's function without unnecessary words.

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?

The schema provides detailed parameter information, but the description lacks mention of output options (e.g., png, svg, option) and does not explain what the tool returns. Given the complexity of treemap data, more guidance would be helpful.

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 description is not required to add parameter details. However, it adds no extra context beyond the schema, such as explaining how data should be structured for a treemap or usage tips.

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 verb 'generate' and the resource 'treemap chart', explains its use for hierarchical data and comparisons at the same level, and provides a concrete example (disk space usage). This distinguishes it from sibling chart tools.

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

Usage Guidelines3/5

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

The description implies usage for hierarchical data but does not explicitly state when to use this tool over alternatives or when not to use it. No guidance on exclusions or prerequisites.

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-echarts'

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