Skip to main content
Glama

export_chart

Create visual charts from Excel data and export them as images. Specify data columns, chart type, and sheet to generate charts for analysis and presentation.

Instructions

Create a chart from Excel data and return as an image.

Args:
    file_path: Path to the Excel file
    x_column: Column to use for x-axis
    y_column: Column to use for y-axis
    chart_type: Type of chart ('line', 'bar', 'scatter', 'hist')
    sheet_name: Name of the sheet to chart (for Excel files)
    
Returns:
    Chart as image

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
x_columnYes
y_columnYes
chart_typeNoline
sheet_nameNo

Implementation Reference

  • Implementation of the 'export_chart' tool handler. Decorated with @mcp.tool(), reads data from various file formats (Excel, CSV, etc.), creates charts using matplotlib/seaborn (line, bar, scatter, hist), and returns a PNG image or error image.
    @mcp.tool()
    def export_chart(file_path: str, x_column: str, y_column: str, 
                   chart_type: str = "line", sheet_name: Optional[str] = None) -> Image:
        """
        Create a chart from Excel data and return as an image.
        
        Args:
            file_path: Path to the Excel file
            x_column: Column to use for x-axis
            y_column: Column to use for y-axis
            chart_type: Type of chart ('line', 'bar', 'scatter', 'hist')
            sheet_name: Name of the sheet to chart (for Excel files)
            
        Returns:
            Chart as image
        """
        import matplotlib.pyplot as plt
        import seaborn as sns
        
        try:
            # Read file
            _, ext = os.path.splitext(file_path)
            ext = ext.lower()
            
            read_params = {}
            if ext in ['.xlsx', '.xls', '.xlsm'] and sheet_name is not None:
                read_params["sheet_name"] = sheet_name
                
            if ext in ['.xlsx', '.xls', '.xlsm']:
                df = pd.read_excel(file_path, **read_params)
            elif ext == '.csv':
                df = pd.read_csv(file_path)
            elif ext == '.tsv':
                df = pd.read_csv(file_path, sep='\t')
            elif ext == '.json':
                df = pd.read_json(file_path)
            else:
                raise ValueError(f"Unsupported file extension: {ext}")
            
            # Create chart
            plt.figure(figsize=(10, 6))
            
            if chart_type == "line":
                sns.lineplot(data=df, x=x_column, y=y_column)
            elif chart_type == "bar":
                sns.barplot(data=df, x=x_column, y=y_column)
            elif chart_type == "scatter":
                sns.scatterplot(data=df, x=x_column, y=y_column)
            elif chart_type == "hist":
                df[y_column].hist()
                plt.xlabel(y_column)
            else:
                raise ValueError(f"Unsupported chart type: {chart_type}")
            
            plt.title(f"{chart_type.capitalize()} Chart: {y_column} by {x_column}")
            plt.tight_layout()
            
            # Save to bytes buffer
            buf = io.BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            
            # Convert to Image
            plt.close()
            return Image(data=buf.getvalue(), format="png")
        except Exception as e:
            # Return error image
            plt.figure(figsize=(8, 2))
            plt.text(0.5, 0.5, f"Error creating chart: {str(e)}", 
                     horizontalalignment='center', fontsize=12, color='red')
            plt.axis('off')
            
            buf = io.BytesIO()
            plt.savefig(buf, format='png')
            buf.seek(0)
            plt.close()
            
            return Image(data=buf.getvalue(), format="png")

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/yzfly/mcp-excel-server'

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