import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import * as Charts from "./charts";
import {
startHTTPStreamableServer,
startSSEMcpServer,
startStdioMcpServer,
} from "./services";
import { callTool } from "./utils/callTool";
/**
* Creates and configures an MCP server for chart generation.
*/
export function createServer(): Server {
const server = new Server(
{
name: "echarts-mcp-server",
version: "0.0.10",
},
{
capabilities: {
tools: {},
},
},
);
setupToolHandlers(server);
server.onerror = (error) => console.error("[MCP Error]", error);
process.on("SIGINT", async () => {
await server.close();
process.exit(0);
});
return server;
}
/**
* Sets up tool handlers for the MCP server.
*/
function setupToolHandlers(server: Server): void {
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: Object.values(Charts).map((chart) => chart.tool),
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
return await callTool(request.params.name, request.params.arguments);
});
}
/**
* Runs the server with stdio transport.
*/
export async function runStdioServer(): Promise<void> {
const server = createServer();
await startStdioMcpServer(server);
}
/**
* Runs the server with SSE transport.
*/
export async function runSSEServer(
endpoint = "/sse",
port = 1122,
): Promise<void> {
const server = createServer();
await startSSEMcpServer(server, endpoint, port);
}
/**
* Runs the server with HTTP streamable transport.
*/
export async function runHTTPStreamableServer(
endpoint = "/mcp",
port = 1122,
): Promise<void> {
await startHTTPStreamableServer(createServer, endpoint, port);
}