Skip to main content
Glama

generate_pie_chart

Create a pie chart displaying proportional data for categories like market share or budget allocation. Customize dimensions, theme, inner radius for donut charts, and export as PNG, SVG, or ECharts option.

Instructions

Generate a pie chart to show the proportion of parts, such as, market share and budget allocation.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dataYesData for pie chart, such as, [{ category: 'Category A', value: 27 }, { category: 'Category B', value: 25 }].
heightNoSet the height of the chart, default is 600px.
innerRadiusNoSet the innerRadius of pie chart, the value between 0 and 1. Set the pie chart as a donut chart. Set the value to 0.6 or number in [0 ,1] to enable it.
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 'run' function that executes the pie chart generation logic. Transforms data, builds ECharts option, and calls generateChartImage.
      run: async (params: {
        data: Array<{ category: string; value: number }>;
        height: number;
        innerRadius?: number;
        theme?: "default" | "dark";
        title?: string;
        width: number;
        outputType?: "png" | "svg" | "option";
      }) => {
        const {
          data,
          height,
          innerRadius = 0,
          theme,
          title,
          width,
          outputType,
        } = params;
    
        // Transform data for ECharts
        const pieData = data.map((item) => ({
          name: item.category,
          value: item.value,
        }));
    
        const series: Array<SeriesOption> = [
          {
            data: pieData,
            radius: innerRadius > 0 ? [`${innerRadius * 100}%`, "70%"] : "70%",
            type: "pie",
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ];
    
        const echartsOption: EChartsOption = {
          legend: {
            left: "center",
            orient: "horizontal",
            top: "bottom",
          },
          series,
          title: {
            left: "center",
            text: title,
          },
          tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b}: {c} ({d}%)",
          },
        };
    
        return await generateChartImage(
          echartsOption,
          width,
          height,
          theme,
          outputType,
          "generate_pie_chart",
        );
      },
    };
  • Tool definition with name 'generate_pie_chart', description, and inputSchema using Zod for validation (data array, height, innerRadius, theme, title, width, outputType).
    export const generatePieChartTool = {
      name: "generate_pie_chart",
      description:
        "Generate a pie chart to show the proportion of parts, such as, market share and budget allocation.",
      inputSchema: z.object({
        data: z
          .array(data)
          .describe(
            "Data for pie chart, such as, [{ category: 'Category A', value: 27 }, { category: 'Category B', value: 25 }].",
          )
          .nonempty({ message: "Pie chart data cannot be empty." }),
        height: HeightSchema,
        innerRadius: z
          .number()
          .default(0)
          .describe(
            "Set the innerRadius of pie chart, the value between 0 and 1. Set the pie chart as a donut chart. Set the value to 0.6 or number in [0 ,1] to enable it.",
          ),
        theme: ThemeSchema,
        title: TitleSchema,
        width: WidthSchema,
        outputType: OutputTypeSchema,
      }),
  • Registration of generatePieChartTool in the tools array exported from src/tools/index.ts.
    export const tools = [
      generateEChartsTool,
      generateAreaChartTool,
      generateLineChartTool,
      generateBarChartTool,
      generatePieChartTool,
      generateRadarChartTool,
      generateScatterChartTool,
      generateSankeyChartTool,
      generateFunnelChartTool,
      generateGaugeChartTool,
      generateTreemapChartTool,
      generateSunburstChartTool,
      generateHeatmapChartTool,
      generateCandlestickChartTool,
      generateBoxplotChartTool,
      generateGraphChartTool,
      generateParallelChartTool,
      generateTreeChartTool,
    ];
  • The generateChartImage helper function that renders ECharts and returns image (PNG base64/MinIO URL), SVG string, or option object.
    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)
          }`,
        );
      }
    }
  • Shared schema definitions used by generate_pie_chart (HeightSchema, ThemeSchema, OutputTypeSchema, TitleSchema, WidthSchema).
    export const HeightSchema = z
      .number()
      .int()
      .positive()
      .optional()
      .default(600)
      .describe("Set the height of the chart, default is 600px.");
    
    export const ThemeSchema = z
      .enum(["default", "dark"])
      .optional()
      .default("default")
      .describe("Set the theme for the chart, optional, default is 'default'.");
    
    export const OutputTypeSchema = z
      .enum(["png", "svg", "option"])
      .optional()
      .default("png")
      .describe(
        "The 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.",
      );
    
    export const TitleSchema = z
      .string()
      .optional()
      .describe("Set the title of the chart.");
    
    export const WidthSchema = z
      .number()
      .int()
      .positive()
      .optional()
      .default(800)
      .describe("Set the width of the chart, default is 800px.");
Behavior2/5

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

No annotations are provided, and the description does not disclose any behavioral traits (e.g., idempotency, side effects, or performance characteristics). The schema covers output format options, but the description adds no behavioral context.

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, well-structured sentence that efficiently conveys the core purpose. It is appropriately sized, though it could include a bit more detail without becoming verbose.

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 complexity (7 parameters, no output schema) and the large number of sibling chart tools, the description is too minimal. It does not explain return values or provide guidance on how this chart differs from alternatives, leaving the agent to infer from the name alone.

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 baseline is 3. The tool description does not add any additional meaning beyond what the schema already provides for parameters.

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 tool generates a pie chart to show proportions, with concrete examples like market share and budget allocation. It distinctly identifies the specific chart type among many sibling chart generators.

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 when to use (proportional data) through examples but lacks explicit guidance on when not to use or alternatives among the many sibling chart tools.

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