Skip to main content
Glama
GongRzhe

Quickchart-MCP-Server

download_chart

Save customizable data visualizations as image files to your local system using Chart.js configurations.

Instructions

Download a chart image to a local file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
configYesChart configuration object
outputPathNoPath where the chart image should be saved. If not provided, the chart will be saved to Desktop or home directory.

Implementation Reference

  • Main execution logic for the download_chart tool: validates and normalizes config, determines output path (defaulting to Desktop/chart_timestamp.png), generates chart URL, downloads image with axios, saves to file, returns success message.
    case 'download_chart': {
      try {
        const { config, outputPath: userProvidedPath } = request.params.arguments as { 
          config: Record<string, unknown>;
          outputPath?: string;
        };
        
        // Validate and normalize config first
        if (!config || typeof config !== 'object') {
          throw new McpError(
            ErrorCode.InvalidParams,
            'Config must be a valid chart configuration object'
          );
        }
        
        // Handle both direct properties and nested properties in 'data'
        let normalizedConfig: any = { ...config };
        
        // If config has data property with datasets, extract them
        if (config.data && typeof config.data === 'object' && 
            (config.data as any).datasets && !normalizedConfig.datasets) {
          normalizedConfig.datasets = (config.data as any).datasets;
        }
        
        // If config has data property with labels, extract them
        if (config.data && typeof config.data === 'object' && 
            (config.data as any).labels && !normalizedConfig.labels) {
          normalizedConfig.labels = (config.data as any).labels;
        }
        
        // If type is inside data object but not at root, extract it
        if (config.data && typeof config.data === 'object' && 
            (config.data as any).type && !normalizedConfig.type) {
          normalizedConfig.type = (config.data as any).type;
        }
        
        // Final validation after normalization
        if (!normalizedConfig.type || !normalizedConfig.datasets) {
          throw new McpError(
            ErrorCode.InvalidParams,
            'Config must include type and datasets properties (either at root level or inside data object)'
          );
        }
        
        // Generate default outputPath if not provided
        const fs = await import('fs');
        const path = await import('path');
        const os = await import('os');
        
        let outputPath = userProvidedPath;
        if (!outputPath) {
          // Get home directory
          const homeDir = os.homedir();
          const desktopDir = path.join(homeDir, 'Desktop');
          
          // Check if Desktop directory exists and is writable
          let baseDir = homeDir;
          try {
            await fs.promises.access(desktopDir, fs.constants.W_OK);
            baseDir = desktopDir; // Desktop exists and is writable
          } catch (error) {
            // Desktop doesn't exist or is not writable, use home directory
            console.error('Desktop not accessible, using home directory instead');
          }
          
          // Generate a filename based on chart type and timestamp
          const timestamp = new Date().toISOString()
            .replace(/:/g, '-')
            .replace(/\..+/, '')
            .replace('T', '_');
          const chartType = normalizedConfig.type || 'chart';
          outputPath = path.join(baseDir, `${chartType}_${timestamp}.png`);
          
          console.error(`No output path provided, using: ${outputPath}`);
        }
        
        // Check if the output directory exists and is writable
        const outputDir = path.dirname(outputPath);
        
        try {
          await fs.promises.access(outputDir, fs.constants.W_OK);
        } catch (error) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Output directory does not exist or is not writable: ${outputDir}`
          );
        }
        
        const chartConfig = this.generateChartConfig(normalizedConfig);
        const url = await this.generateChartUrl(chartConfig);
        
        try {
          const response = await axios.get(url, { responseType: 'arraybuffer' });
          await fs.promises.writeFile(outputPath, response.data);
        } catch (error: any) {
          if (error.code === 'EACCES' || error.code === 'EROFS') {
            throw new McpError(
              ErrorCode.InvalidParams,
              `Cannot write to ${outputPath}: Permission denied`
            );
          }
          if (error.code === 'ENOENT') {
            throw new McpError(
              ErrorCode.InvalidParams,
              `Cannot write to ${outputPath}: Directory does not exist`
            );
          }
          throw error;
        }
        
        return {
          content: [
            {
              type: 'text',
              text: `Chart saved to ${outputPath}`
            }
          ]
        };
      } catch (error: any) {
        if (error instanceof McpError) {
          throw error;
        }
        throw new McpError(
          ErrorCode.InternalError,
          `Failed to download chart: ${error?.message || 'Unknown error'}`
        );
      }
    }
  • src/index.ts:228-245 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining name, description, and input schema for download_chart.
    {
      name: 'download_chart',
      description: 'Download a chart image to a local file',
      inputSchema: {
        type: 'object',
        properties: {
          config: {
            type: 'object',
            description: 'Chart configuration object'
          },
          outputPath: {
            type: 'string',
            description: 'Path where the chart image should be saved. If not provided, the chart will be saved to Desktop or home directory.'
          }
        },
        required: ['config']
      }
    }
  • Input schema definition for the download_chart tool, specifying config (required) and optional outputPath.
    inputSchema: {
      type: 'object',
      properties: {
        config: {
          type: 'object',
          description: 'Chart configuration object'
        },
        outputPath: {
          type: 'string',
          description: 'Path where the chart image should be saved. If not provided, the chart will be saved to Desktop or home directory.'
        }
      },
      required: ['config']
  • Helper function generateChartConfig: validates input, normalizes chart configuration, handles special cases for chart types, returns ChartConfig object. Called by download_chart handler.
    private generateChartConfig(args: any): ChartConfig {
      // Add defensive checks to handle possibly malformed input
      if (!args) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'No arguments provided to generateChartConfig'
        );
      }
      
      if (!args.type) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Chart type is required'
        );
      }
      
      if (!args.datasets || !Array.isArray(args.datasets)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Datasets must be a non-empty array'
        );
      }
      
      const { type, labels, datasets, title, options = {} } = args;
      
      this.validateChartType(type);
    
      const config: ChartConfig = {
        type,
        data: {
          labels: labels || [],
          datasets: datasets.map((dataset: any) => {
            if (!dataset || !dataset.data) {
              throw new McpError(
                ErrorCode.InvalidParams,
                'Each dataset must have a data property'
              );
            }
            return {
              label: dataset.label || '',
              data: dataset.data,
              backgroundColor: dataset.backgroundColor,
              borderColor: dataset.borderColor,
              ...(dataset.additionalConfig || {})
            };
          })
        },
        options: {
          ...options,
          ...(title && {
            title: {
              display: true,
              text: title
            }
          })
        }
      };
    
      // Special handling for specific chart types
      switch (type) {
        case 'radialGauge':
        case 'speedometer':
          if (!datasets?.[0]?.data?.[0]) {
            throw new McpError(
              ErrorCode.InvalidParams,
              `${type} requires a single numeric value`
            );
          }
          config.options = {
            ...config.options,
            plugins: {
              datalabels: {
                display: true,
                formatter: (value: number) => value
              }
            }
          };
          break;
    
        case 'scatter':
        case 'bubble':
          datasets.forEach((dataset: any) => {
            if (!Array.isArray(dataset.data[0])) {
              throw new McpError(
                ErrorCode.InvalidParams,
                `${type} requires data points in [x, y${type === 'bubble' ? ', r' : ''}] format`
              );
            }
          });
          break;
      }
    
      return config;
  • Helper function to generate QuickChart URL from ChartConfig. Used in download_chart to fetch the image.
    private async generateChartUrl(config: ChartConfig): Promise<string> {
      const encodedConfig = encodeURIComponent(JSON.stringify(config));
      return `${QUICKCHART_BASE_URL}?c=${encodedConfig}`;
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 'Download' implies file system write operations, it doesn't specify permissions needed, whether existing files are overwritten, what image formats are supported, or error conditions. The description mentions default save locations but lacks other critical behavioral details for a file-writing tool.

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

Conciseness5/5

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

The description is a single, efficient sentence that communicates the core functionality without unnecessary words. It's appropriately sized for a simple tool and front-loads the essential information. Every word earns its place.

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?

For a tool that writes files to the local system with no annotations and no output schema, the description is insufficient. It doesn't address important contextual aspects like supported image formats, error handling, file naming conventions, or what happens when the outputPath directory doesn't exist. The agent lacks critical information for reliable 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?

With 100% schema description coverage, the baseline is 3. The description doesn't add meaningful parameter semantics beyond what's in the schema - it mentions the outputPath default behavior which is already documented in the schema description. No additional context about the 'config' object structure or validation is provided.

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 action ('Download') and resource ('a chart image to a local file'), making the purpose immediately understandable. However, it doesn't distinguish this tool from its sibling 'generate_chart' - while 'download' implies saving to a file versus 'generate' which might create in memory, this distinction isn't explicitly stated in the description.

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 its sibling 'generate_chart'. There's no mention of prerequisites, alternative approaches, or specific scenarios where this tool is preferred. The agent must infer usage from the tool name alone.

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/GongRzhe/Quickchart-MCP-Server'

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