### MCP Configuration Guide Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/COMPLETION_REPORT.txt Details the environment variables and setup required for the MCP system, including storage backend configurations. ```APIDOC ## MCP Configuration ### Environment Variables - **BOS_AK**: Access Key for Baidu Object Storage. - **BOS_SK**: Secret Access Key for Baidu Object Storage. - **BOS_ENDPOINT**: Endpoint URL for Baidu Object Storage. - **BOS_BUCKET**: Bucket name in Baidu Object Storage. - **BOS_CDN_ENDPOINT**: CDN endpoint for Baidu Object Storage. ### Setup Guide Refer to the `configuration.md` file for detailed setup instructions and examples, including customization for different storage backends like AWS S3. ``` -------------------------------- ### Install Dependencies Source: https://github.com/apache/echarts-mcp/blob/main/README.md Install the necessary Node.js dependencies for the project. ```sh npm install ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Example .env file for production, similar to development but with production-specific credentials and endpoints. ```env SERVER_PORT=8081 BOS_AK=prod_ak BOS_SK=prod_sk BOS_ENDPOINT=https://bj.bcebos.com BOS_CDN_ENDPOINT=https://cdn.example.com BOS_BUCKET=echarts-mcp-prod ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Example .env file for development, specifying server port, Baidu Cloud credentials, and endpoints. ```env SERVER_PORT=8081 BOS_AK=test_ak BOS_SK=test_sk BOS_ENDPOINT=https://bj.bcebos.com BOS_CDN_ENDPOINT=https://dev-cdn.example.com BOS_BUCKET=echarts-mcp-dev ``` -------------------------------- ### EChartsServer Instantiation and Run Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md Demonstrates how to instantiate the EChartsServer and start the HTTP server. The instantiation happens automatically at module load. ```javascript // Instantiation happens automatically at module load const server = new EChartsServer(); server.run().catch(console.error); ``` -------------------------------- ### Example URLs for Generated Charts Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Illustrates the format of public CDN URLs for generated chart images. ```text https://charts-cdn.example.com/upload/echarts/202401151530215a8b3c2d1e.png https://images.example.com/upload/echarts/202401151530221x2y3z4a5b.png ``` -------------------------------- ### Setting Custom Server Port Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Example of how to run the development server on a custom port (e.g., 3000) by setting the SERVER_PORT environment variable. ```bash SERVER_PORT=3000 npm run dev # Server runs on http://localhost:3000 ``` -------------------------------- ### Check for .env file on startup Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Ensures the .env file exists in the project root before the server starts. Throws an error if the file is missing, prompting the user to create it. ```javascript if (!fs.existsSync('.env')) { throw new Error('Missing .env file. Please create a .env file with your configuration. See .env.example for reference.'); } ``` -------------------------------- ### Using MCP Inspector CLI Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Interact with ECharts MCP tools via the command line using the MCP Inspector. This example shows how to start the inspector. ```bash mcp-inspector node ./src/index.js ``` -------------------------------- ### Example Usage of getXData with Empty Data Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/utility-functions.md Demonstrates calling `getXData` with empty data, which should return an empty object. ```javascript import { getXData } from './util.js'; // Empty data const xAxisEmpty = getXData([], 'Fruit'); // Returns: [] ``` -------------------------------- ### Example Usage of isTreelike Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/utility-functions.md Shows how to use the `isTreelike` function to check if various series types are hierarchical. ```javascript import { isTreelike } from './util.js'; isTreelike('tree'); // true isTreelike('treemap'); // true isTreelike('sunburst'); // true isTreelike('bar'); // false isTreelike('pie'); // false isTreelike('scatter'); // false ``` -------------------------------- ### Example Usage of getXData with Numeric Values Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/utility-functions.md Demonstrates extracting X-axis configuration from data with numeric values and an axis name. ```javascript import { getXData } from './util.js'; // Numeric values const xAxisNum = getXData([ [1, 10], [2, 20], [3, 15] ], 'Month'); // Returns: { type: 'value', data: [1, 2, 3], name: 'Month' } ``` -------------------------------- ### Start EChartsServer HTTP Server Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Starts the Express.js HTTP server and establishes SSE transport for MCP protocol communication. The server listens on the port specified by the SERVER_PORT environment variable or defaults to 8081. ```javascript async run() ``` ```javascript // In src/index.js, run() is called automatically const server = new EChartsServer(); await server.run(); // Server now listening on http://localhost:8081 ``` -------------------------------- ### Example .env File Template Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md A template for the .env file located at the project root, including server and Baidu BOS configurations. Ensure sensitive keys are kept secret. ```dotenv # Server Configuration SERVER_PORT=8081 # Baidu Cloud Object Storage (BOS) BOS_AK=your_access_key BOS_SK=your_secret_key BOS_ENDPOINT=https://bj.bcebos.com BOS_CDN_ENDPOINT=https://your-cdn-domain.com BOS_BUCKET=echarts-mcp ``` -------------------------------- ### Example Usage of getXData with String Categories Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/utility-functions.md Demonstrates extracting X-axis configuration from data with string categories and an axis name. ```javascript import { getXData } from './util.js'; // String categories const xAxis = getXData([ ['Apple', 100], ['Banana', 200], ['Cherry', 150] ], 'Fruit'); // Returns: { type: 'category', data: ['Apple', 'Banana', 'Cherry'], name: 'Fruit' } ``` -------------------------------- ### Run MCP Server Source: https://github.com/apache/echarts-mcp/blob/main/README.md Start the MCP server to handle chart generation requests. Ensure the inspector is running in a separate terminal. ```sh # Run the MCP server npm run dev # Run the inspector in another terminal npm run inspect ``` -------------------------------- ### AWS S3 Storage Backend Implementation Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Example JavaScript code for integrating AWS S3 as a storage backend. It includes setting up the S3 client and uploading images. ```javascript // src/storage.js import AWS from 'aws-sdk'; const s3 = new AWS.S3({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, }); export async function saveImage(base64) { const fileName = getFilePrefix() + '.png'; const base64Data = base64.replace(/^data:image\/\w+;base64,/, ''); const params = { Bucket: process.env.AWS_BUCKET, Key: `echarts/${fileName}`, Body: Buffer.from(base64Data, 'base64'), ContentType: 'image/png', ACL: 'public-read', }; const result = await s3.upload(params).promise(); return result.Location; } ``` -------------------------------- ### Custom Theme Registration Example Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/INDEX.md Example of how to register a custom ECharts theme. Uncomment and modify the theme object with your desired theme properties. ```javascript // Register custom theme // echarts.registerTheme('myTheme', { // color: ['#c23531','#2f4554', ...] // }); ``` -------------------------------- ### Example Usage of seriesTypes Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/utility-functions.md Demonstrates how to import and use the `seriesTypes` constant to check the number of supported types or validate a user-provided type. ```javascript import { seriesTypes } from './util.js'; console.log(seriesTypes.length); // 8 if (seriesTypes.includes(userType)) { // Valid type } ``` -------------------------------- ### EChartsServer Class Definition Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md Defines the EChartsServer class, which serves as the main entry point for the MCP server. It handles chart type and data validation, tool handler setup, and starting the HTTP server. ```javascript class EChartsServer { constructor() validateChartType(type) validateChartData(data, type) setupToolHandlers() async run() } ``` -------------------------------- ### Success Response Example Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md A successful response returns a JSON object containing a URL to the generated chart image. ```json { "content": [ { "type": "text", "text": "https://cdn.example.com/upload/echarts/202401151530215a8b3c2d1e.png" } ] } ``` -------------------------------- ### List Available Tools via MCP Protocol Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md This example shows how to request a list of available tools from the ECharts MCP server. It first establishes an SSE connection to obtain a sessionId, then sends a POST request to the /messages endpoint with the 'tools/list' method. ```bash # First establish SSE connection to get sessionId curl -N "http://localhost:8081/sse" \ -H "Accept: text/event-stream" & # Then call /messages (assuming sessionId = "abc123") curl -X POST "http://localhost:8081/messages?sessionId=abc123" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }' ``` -------------------------------- ### GET / Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md A simple health check endpoint to verify if the ECharts MCP server is running. ```APIDOC ## GET / ### Description Health check endpoint to verify the server is running. ### Method GET ### Endpoint / ### Response #### Success Response (200 OK) - **Content-Type**: text/html - **Body**: `Apache ECharts MCP Server is running` ### Request Example ```bash curl http://localhost:8081/ ``` ``` -------------------------------- ### Set Server Port Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Configure the HTTP port for the server. Defaults to 8081 if not set. Example shows setting it to 3000. ```bash SERVER_PORT=3000 npm run dev ``` -------------------------------- ### Custom Font Registration Example Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/INDEX.md Example of how to register custom fonts for ECharts charts. Uncomment and modify the paths to your font files. ```javascript // Register custom font // echarts.registerFont("./font/MyFont.woff2"); // echarts.registerFont("./font/MyFont.ttf"); ``` -------------------------------- ### AWS S3 Environment Variables Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Example .env file configuration for using AWS S3 as the storage backend, including access keys, region, and bucket name. ```env SERVER_PORT=8081 AWS_ACCESS_KEY_ID=your_key AWS_SECRET_ACCESS_KEY=your_secret AWS_REGION=us-east-1 AWS_BUCKET=your-bucket ``` -------------------------------- ### Establish SSE Connection with MCP SDK Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md This Node.js example demonstrates how to establish a Server-Sent Events connection to the ECharts MCP server using the MCP SDK. It sets up a client transport and connects a client instance. ```javascript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; const transport = await SSEClientTransport.connect({ url: 'http://localhost:8081/sse' }); const client = new Client({ name: 'client', version: '1.0.0', }, { capabilities: {} }); await client.connect(transport); ``` -------------------------------- ### EChartsServer.run() Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Starts the Express.js HTTP server and establishes SSE (Server-Sent Events) transport for MCP protocol communication. The server listens on the port specified by the SERVER_PORT environment variable, defaulting to 8081. ```APIDOC ## EChartsServer.run() ### Description Starts the Express.js HTTP server and establishes SSE (Server-Sent Events) transport for MCP protocol communication. The server listens on the port specified by the SERVER_PORT environment variable, defaulting to 8081. ### Method ``` async run() ``` ### Parameters No parameters. ### HTTP Routes #### GET / - **Purpose**: Health check. Returns 'Apache ECharts MCP Server is running'. #### GET /sse - **Purpose**: Establishes SSE connection for MCP protocol messages. #### POST /messages - **Purpose**: Receives MCP tool call requests from client. ### Behavior - Creates an Express application. - Establishes SSE transport on `/sse` endpoint. - Handles bidirectional communication via `/messages` endpoint. - Manages session tracking via `sessionId` query parameter. - Listens on port specified by `SERVER_PORT` environment variable (defaults to 8081). ### Request Example ```javascript const server = new EChartsServer(); await server.run(); // Server now listening on http://localhost:8081 ``` ### Error Handling - `server.onerror` handler logs all MCP protocol errors to console. - Validation errors are wrapped in `McpError` with appropriate `ErrorCode` values. - Storage errors result in `ErrorCode.InternalError` responses. - Validation Errors: `ErrorCode.InvalidParams` for invalid chart type or data format. - Generation Errors: `ErrorCode.InternalError` for chart generation or image upload failures. - Transport Errors: Logged via `server.onerror` handler for protocol-level issues. All errors are returned to the MCP client with appropriate error codes and descriptions. ``` -------------------------------- ### Hierarchical Data Format Example Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/types.md Shows the data structure for hierarchical charts such as tree, treemap, and sunburst. Nodes can contain nested children, forming a tree-like structure. ```javascript [ { name: 'A', value: 100, children: [ { name: 'A1', value: 40 }, { name: 'A2', value: 60 } ] }, { name: 'B', value: 200 } ] ``` -------------------------------- ### Setup EChartsServer Tool Handlers Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Registers MCP tool handlers for the 'get-chart' tool, including validation and chart generation. This is called internally by the constructor. ```javascript // Called internally by constructor const server = new EChartsServer(); // setupToolHandlers() is invoked automatically ``` -------------------------------- ### GET /sse Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Establishes a Server-Sent Events (SSE) connection for MCP protocol communication. A unique sessionId is generated and returned, which is required for subsequent message delivery. ```APIDOC ## GET /sse ### Description Server-Sent Events endpoint for MCP protocol communication setup. Establishes a connection and provides a `sessionId` for subsequent message delivery. ### Method GET ### Endpoint /sse ### Response #### Success Response (101 Upgrade / 200 SSE Stream) - **Content-Type**: `text/event-stream` - **Headers**: - `Cache-Control: no-cache` - `Connection: keep-alive` - **Body**: Stream of MCP protocol messages ### Session Management - A unique `sessionId` is generated and tracked internally. - This `sessionId` must be passed to the `/messages` endpoint. ### MCP Connection Flow 1. Client establishes SSE connection to `/sse`. 2. Server creates `SSEServerTransport` and stores it. 3. Client receives `sessionId` from transport initialization. 4. Subsequent messages are POSTed to `/messages?sessionId={sessionId}`. ### Request Example (Node.js with MCP SDK) ```javascript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; const transport = await SSEClientTransport.connect({ url: 'http://localhost:8081/sse' }); const client = new Client({ name: 'client', version: '1.0.0', }, { capabilities: {} }); await client.connect(transport); ``` ``` -------------------------------- ### Get Chart Tool Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md This tool allows users to generate various types of charts by providing data and configuration. It supports bar, pie, and tree chart types. ```APIDOC ## tools/call get-chart ### Description Generates a chart based on the provided data and chart type. ### Method POST ### Endpoint /tools/call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (integer) - Required - The ID of the request. - **method** (string) - Required - The method to call, should be "get-chart". - **params** (object) - Required - Parameters for the tool call. - **name** (string) - Required - The name of the tool, "get-chart". - **arguments** (object) - Required - Arguments for the get-chart tool. - **type** (string) - Required - The type of chart to generate (e.g., "bar", "pie", "tree"). - **data** (array) - Required - The data to be visualized in the chart. - **title** (string) - Required - The title of the chart. - **seriesName** (string) - Optional - The name of the data series. - **xAxisName** (string) - Optional - The name for the x-axis (for bar charts). - **yAxisName** (string) - Optional - The name for the y-axis (for bar charts). ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "get-chart", "arguments": { "type": "bar", "data": [["Q1", 1000], ["Q2", 1500], ["Q3", 1200], ["Q4", 1800]], "title": "Quarterly Revenue", "seriesName": "Revenue", "xAxisName": "Quarter", "yAxisName": "Revenue (USD)" } } } ``` ### Response #### Success Response (200) - **result** (string) - URL of the generated chart image. #### Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "http://example.com/charts/bar_chart.png" } ``` ``` -------------------------------- ### 2D Array Data Format Example Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/types.md Illustrates the data format for 2D array-based charts like bar, line, pie, scatter, and funnel. Each inner array represents a data point with a label and a value. ```javascript [ ['Apple', 100], ['Banana', 200], ['Cherry', 150] ] ``` -------------------------------- ### EChartsServer Class Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md The EChartsServer class is the main entry point for the MCP server. It handles request routing, validation, and starts the HTTP server. It provides methods to validate chart types and data, and to run the server. ```APIDOC ## Class: EChartsServer ### Description The EChartsServer class is the main entry point for the MCP server. It handles request routing, validation, and starts the HTTP server. It provides methods to validate chart types and data, and to run the server. ### Methods - **constructor()**: Initializes the server, checks for .env file, sets up the MCP Server instance and tool handlers. - **validateChartType(type: string) → void**: Throws McpError if the chart type is invalid. - **validateChartData(data: any, type: string) → void**: Throws McpError if the chart data is invalid for the given type. - **setupToolHandlers() → void**: Initializes tool handlers for the server. - **run() → Promise**: Starts the HTTP server. This is a long-running process and never resolves. ### Usage ```javascript // Instantiation happens automatically at module load const server = new EChartsServer(); server.run().catch(console.error); ``` ``` -------------------------------- ### Server Startup with Configurable Port Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Configure the server's listening port using the SERVER_PORT environment variable. Defaults to 8081. ```javascript const port = process.env.SERVER_PORT || 8081; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); ``` -------------------------------- ### Initialize EChartsServer with Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Initializes an MCP Server with basic configuration including name, version, and capabilities. This sets up the fundamental properties for the server's operation. ```javascript new Server({ name: 'echarts', version: '1.0.0' }, { capabilities: { tools: {} } }) ``` -------------------------------- ### BOS Client Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/storage.md Sets up the Baidu Cloud Object Storage client using environment variables for endpoint, credentials, and bucket name. ```javascript const config = { endpoint: process.env.BOS_ENDPOINT, credentials: { ak: process.env.BOS_AK, sk: process.env.BOS_SK, }, }; const client = new bos.BosClient(config); const bucket = process.env.BOS_BUCKET; const basePath = '/upload/echarts'; ``` -------------------------------- ### setupToolHandlers() Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Registers MCP tool handlers for the `get-chart` tool, configuring request handlers for listing tools and handling chart generation requests. ```APIDOC ## setupToolHandlers() ### Description Registers MCP tool handlers for the `get-chart` tool. Configures request handlers for `ListToolsRequestSchema` and `CallToolRequestSchema` to handle chart generation requests. ### Method ```javascript setupToolHandlers() ``` ### Parameters No parameters. Sets up internal request handlers. ### Behavior - Registers a single `get-chart` tool with full parameter validation. - Validates chart type against supported series types. - Validates chart data structure. - Generates base64 chart image and uploads to cloud storage. - Returns the public CDN URL of the uploaded image. ### Example ```javascript // Called internally by constructor const server = new EChartsServer(); // setupToolHandlers() is invoked automatically ``` ``` -------------------------------- ### Instantiate EChartsServer Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Instantiates the EChartsServer. The server is typically run at module load time. Ensure the .env file is present. ```javascript import { EChartsServer } from './index.js'; // Server is instantiated and run at module load time // const server = new EChartsServer(); // await server.run(); ``` -------------------------------- ### Error Response: Unknown Tool Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Returned when an invalid tool name is provided in the request. ```json { "error": { "code": -32601, "message": "Unknown tool: invalid-tool-name" } } ``` -------------------------------- ### Throwing McpError for Invalid Parameters Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/types.md Example of throwing an McpError with ErrorCode.InvalidParams, typically used when chart type or data format is incorrect. ```javascript throw new McpError( ErrorCode.InvalidParams, `Invalid chart type. Must be one of: ${seriesTypes.join(', ')}` ); ``` -------------------------------- ### EChartsServer Constructor Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/EChartsServer.md Creates a new MCP server instance named 'echarts' version 1.0.0. It requires a `.env` file to be present. ```APIDOC ## Constructor EChartsServer() ### Description Creates a new MCP server with name 'echarts' version 1.0.0. Throws an error if `.env` file is missing. ### Method ```javascript constructor() ``` ### Parameters There are no parameters for this constructor. ### Throws `Error` if `.env` file does not exist. ### Example ```javascript import { EChartsServer } from './index.js'; // Server is instantiated and run at module load time // const server = new EChartsServer(); // await server.run(); ``` ``` -------------------------------- ### Enable Verbose Logging for Debugging Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/errors.md Run the development server with 'npm run dev' to enable verbose logging. This will output detailed error messages and stack traces to the console, aiding in debugging. ```bash npm run dev # Look for [MCP Error] and error stacktraces in output ``` -------------------------------- ### Register Custom Font for Canvas Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md Example of how to register a custom font for use with the Node.js canvas library. This is useful for ensuring consistent font rendering in generated images. ```javascript import { registerFont } from 'canvas'; registerFont('./font/xxx.otf', { family: 'xxx', weight: 'bold' }); ``` -------------------------------- ### Initialize Baidu Object Storage Client Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md Initializes the Baidu Object Storage (BOS) client using environment variables for endpoint, credentials, and bucket name. This client is used for uploading images. ```javascript const config = { endpoint: process.env.BOS_ENDPOINT, credentials: { ak: process.env.BOS_AK, sk: process.env.BOS_SK } }; const client = new bos.BosClient(config); const bucket = process.env.BOS_BUCKET; const basePath = '/upload/echarts'; ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Use this GET request to verify if the ECharts MCP server is running. It expects a 200 OK status and returns a simple running message. ```bash curl http://localhost:8081/ ``` -------------------------------- ### Create Temporary Directory Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/storage.md Ensures the temporary directory for storing images before upload exists. Creates the directory if it does not already exist upon module initialization. ```javascript const tmpDir = path.join(__dirname, '../tmp'); if (!fs.existsSync(tmpDir)) { fs.mkdirSync(tmpDir); } ``` -------------------------------- ### SSE Connection Management in MCP Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Illustrates the server-side structure for managing multiple Server-Sent Events (SSE) transports, keyed by sessionId. ```javascript const transports = {}; // Map of sessionId -> SSEServerTransport // Each GET /sse creates a new entry // Each POST /messages routes to the correct transport ``` -------------------------------- ### Method Not Found Error (-32601) Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/errors.md Triggered when an unknown tool name is called via the MCP. Ensure the tool name is 'get-chart' as it's the only supported tool. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "invalid-tool", // Not "get-chart" "arguments": {...} } } ``` -------------------------------- ### Save Image to AWS S3 Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/storage.md This JavaScript snippet demonstrates how to save a base64 encoded image to an AWS S3 bucket. Ensure AWS SDK is installed and environment variables for access key, secret access key, and bucket name are configured. ```javascript import AWS from 'aws-sdk'; const s3 = new AWS.S3({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }); export async function saveImage(base64) { const fileName = getFilePrefix() + '.png'; const base64Data = base64.replace(/^data:image\/\w+;base64,/, ''); const params = { Bucket: process.env.AWS_BUCKET, Key: `echarts/${fileName}`, Body: Buffer.from(base64Data, 'base64'), ContentType: 'image/png', }; const result = await s3.upload(params).promise(); return result.Location; } ``` -------------------------------- ### Load environment variables from .env file Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Uses the dotenv package to load environment variables from a .env file into process.env. This is typically done at the application's entry point. ```javascript import dotenv from 'dotenv'; dotenv.config(); ``` -------------------------------- ### Baidu BOS Bucket Name Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Specify the Baidu BOS bucket name where chart images will be uploaded. This bucket must be created in the Baidu Cloud Console beforehand. ```dotenv BOS_BUCKET=echarts-mcp ``` -------------------------------- ### MCP HTTP Endpoints Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/COMPLETION_REPORT.txt Documentation for all available HTTP routes, including request/response schemas and error responses. ```APIDOC ## MCP API Endpoints Refer to the `endpoints.md` file for a complete list of documented HTTP routes, including detailed specifications for request and response schemas, and error handling. ``` -------------------------------- ### Error Handling for Image Upload Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/storage.md Demonstrates how to catch and re-throw errors during the image upload process. Upload failures are logged to the console and then re-thrown to the MCP server. ```javascript // Upload failures are logged to console try { const url = await saveImage(base64); } catch (error) { // error.message contains upload details console.error('Upload failed:', error); throw error; // Re-thrown to MCP server } ``` -------------------------------- ### Canvas Configuration Object Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/types.md Specifies canvas dimensions and theme for rendering. The theme must be registered separately. ```javascript { width: 800, height: 600, theme: 'custom' } ``` -------------------------------- ### Missing .env File Error Message Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md The error message displayed when the required .env file is missing at the project root. This indicates a critical configuration issue. ```text Missing .env file. Please create a .env file with your configuration. See .env.example for reference. ``` -------------------------------- ### Registering Custom Themes Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/chart-generation.md Register a custom theme to apply it to all rendered charts. The theme name must match 'custom' to be used by default. ```javascript import * as echarts from 'echarts'; // In src/chart.js, uncomment and modify: echarts.registerTheme('custom', { backgroundColor: '#ccc', // ... additional theme properties }); // Chart initialization in getChartBase64() already uses 'custom' theme: let chart = echarts.init(canvas, 'custom'); ``` -------------------------------- ### Cloud URL Format for Saved Images Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/types.md Represents the format of a cloud URL returned after saving an image. Includes a CDN endpoint, path, timestamp, and random characters. ```string string // Format: 'https://cdn.example.com/upload/echarts/YYYYMMDDHHMMSS{random}.png' ``` ```string https://charts-cdn.example.com/upload/echarts/202401151530215a8b3c2d1e.png ``` -------------------------------- ### Debug logging for BOS configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Adds console logging to output the Baidu Object Storage (BOS) endpoint and bucket configuration. Avoid logging sensitive AK/SK in production environments. ```javascript // Add logging in src/storage.js console.log('BOS Config:', { endpoint: process.env.BOS_ENDPOINT, bucket: process.env.BOS_BUCKET, // Note: Don't log AK/SK in production }); ``` -------------------------------- ### Test BOS CDN Endpoint Access Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Use this command to manually verify if the configured BOS CDN endpoint is accessible and serving files correctly. Ensure the endpoint URL and the test file path are accurate. ```bash curl {BOS_CDN_ENDPOINT}/upload/echarts/test.png ``` -------------------------------- ### MCP SSE Connection Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Establishes a Server-Sent Events (SSE) connection for real-time messaging between the client and the MCP server. ```APIDOC ## GET /sse ### Description Establishes an SSE connection to the MCP server. ### Method GET ### Endpoint /sse ### Parameters None ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - Server returns an SSE stream connection. #### Response Example (SSE stream) ``` -------------------------------- ### Pie Chart JSON-RPC Request Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md This JSON-RPC request is used to generate a pie chart. Provide the chart type, data, and title. ```json { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "get-chart", "arguments": { "type": "pie", "data": [["Product A", 35], ["Product B", 40], ["Product C", 25]], "title": "Market Share", "seriesName": "Percentage" } } } ``` -------------------------------- ### Baidu BOS Access Key Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Provide your Baidu Cloud Access Key (public key) for authentication. Keep this value secret and do not commit it to version control. ```dotenv BOS_AK=your_access_key_here ``` -------------------------------- ### Bar Chart JSON-RPC Request Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/endpoints.md Use this JSON-RPC request to generate a bar chart. Specify chart type, data, and labels. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "get-chart", "arguments": { "type": "bar", "data": [["Q1", 1000], ["Q2", 1500], ["Q3", 1200], ["Q4", 1800]], "title": "Quarterly Revenue", "seriesName": "Revenue", "xAxisName": "Quarter", "yAxisName": "Revenue (USD)" } } } ``` -------------------------------- ### Upload Base64 Image to Baidu Object Storage Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/modules.md Asynchronously uploads a base64 encoded PNG image to Baidu Object Storage (BOS) and returns its public CDN URL. It handles temporary file creation, cleanup, and error logging. ```javascript export async function saveImage(base64) → Promise ``` -------------------------------- ### getChartBase64 Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/chart-generation.md Renders a chart to a PNG image and returns it as a base64-encoded data URL. Creates a canvas, initializes an ECharts instance, renders the chart, and cleans up resources. ```APIDOC ## getChartBase64(type, data, title, seriesName, xAxisName, yAxisName) ### Description Renders a chart to a PNG image and returns it as a base64-encoded data URL. Creates a canvas, initializes an ECharts instance, renders the chart, and cleans up resources. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **type** (string) - Required - Chart series type - **data** (array) - Required - Chart data (pre-validated) - **title** (string) - Required - Chart title - **seriesName** (string) - Required - Series name - **xAxisName** (string) - Optional - X-axis label - **yAxisName** (string) - Optional - Y-axis label ### Request Example ```javascript // Generate a bar chart image const base64 = getChartBase64( 'bar', [['Q1', 1000], ['Q2', 1500], ['Q3', 1200], ['Q4', 1800]], 'Quarterly Revenue', 'Revenue ($)', 'Quarter', 'Revenue (USD)' ); // Returns: "data:image/png;base64,iVBORw0K..." // Use in storage pipeline const url = await saveImage(base64); console.log(url); // https://cdn.example.com/upload/echarts/2024010115302155abcdef.png ``` ### Response #### Success Response (200) - **Return Type:** `string` - Returns a data URL string in base64 format: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA... ``` ### Error Handling - Not specified in source. ``` -------------------------------- ### Generate Unique File Prefix Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/api-reference/storage.md Generates a unique filename prefix using the current timestamp and 10 random alphanumeric characters. Ensures globally unique filenames for uploaded images. ```javascript function getFilePrefix() { // ... implementation details ... } ``` -------------------------------- ### Baidu BOS Secret Key Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Provide your Baidu Cloud Secret Key (private key) for authentication. Treat this as sensitive as a password and keep it secret. ```dotenv BOS_SK=your_secret_key_here ``` -------------------------------- ### Baidu BOS CDN Endpoint Configuration Source: https://github.com/apache/echarts-mcp/blob/main/_autodocs/configuration.md Configure the public CDN endpoint for accessing uploaded chart images. This URL is returned to clients as the image location. Ensure it does not have a trailing slash. ```dotenv BOS_CDN_ENDPOINT=https://charts-cdn.example.com ```