UNPKG

aibiao-excel-mcp-server

Version:

专为aibiao.cn定制的AI Excel操作MCP服务器 - 让AI智能分析和处理Excel数据

810 lines 31.7 kB
#!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { z } from 'zod'; import { zodToJsonSchema } from 'zod-to-json-schema'; import { // 系统管理 QueryApiKeyStatusSchema, // 聊天管理 CreateChatSchema, AppendChatSchema, ListChatsSchema, GetChatSchema, UpdateChatTitleSchema, DeleteChatSchema, // 图表管理 CreateChartSchema, ListChartsSchema, DeleteChartSchema, // 工作流管理 SaveWorkflowSchema, ListWorkflowsSchema, ExecuteWorkflowSchema, UpdateWorkflowNameSchema, DeleteWorkflowSchema, } from './schemas.js'; // 环境变量配置 const AIBIAO_API_KEY = process.env.AIBIAO_API_KEY || ""; const AIBIAO_BASE_URL = process.env.AIBIAO_BASE_URL || `https://aibiao.cn`; const AIBIAO_DEBUG = process.env.AIBIAO_DEBUG || false; // ======================== // AiBiao.cn API Mock 服务器 // 专为AI操作Excel设计的智能数据管理系统 // ======================== class AibiaoAPI { mockApiKey; baseUrl; constructor(apiKey, baseUrl) { this.mockApiKey = apiKey; this.baseUrl = baseUrl; } // ============ 系统管理 API ============ async queryApiKeyStatus() { try { const response = await fetch(`${AIBIAO_BASE_URL}/api/enterprise/external/api-key-status`, { method: 'GET', headers: { 'Authorization': `Bearer ${AIBIAO_API_KEY}`, 'Content-Type': 'application/json' } }); if (!response.ok) { // 如果API调用失败,返回错误信息 const errorText = await response.text(); // throw new Error(`API调用失败: ${response.status} - ${errorText}`); throw new Error(`API调用失败: ${response.status} - ${errorText} - ${AIBIAO_BASE_URL}`); } const data = await response.json(); return data; } catch (error) { // 如果网络错误或其他异常,返回默认状态 console.error('查询API Key状态失败:', error); return { apiKey: this.mockApiKey, totalQuota: 0, usedQuota: 0, isActive: false, error: error instanceof Error ? error.message : '未知错误' }; } } // ============ 聊天管理 API ============ async createChat(fileUrls, title) { try { const requestBody = JSON.stringify({ fileUrls, title, sse: 0 }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/new-chat`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "聊天会话创建成功", data: responseData, }; } catch (error) { console.error('创建聊天会话失败:', error); return { success: false, message: `创建聊天会话失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async appendChat(chatId, message) { try { const requestBody = JSON.stringify({ chatId, message, sse: 0 }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/append-chat`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "消息追加成功", data: responseData, }; } catch (error) { console.error('追加聊天消息失败:', error); return { success: false, message: `追加聊天消息失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async listChats(params) { try { const requestBody = JSON.stringify(params || {}); const response = await fetch(`${this.baseUrl}/api/enterprise/external/list-chats`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "获取聊天列表成功", data: responseData, }; } catch (error) { console.error('获取聊天列表失败:', error); return { success: false, message: `获取聊天列表失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async getChat(chatId, includeMessages = true) { try { const requestBody = JSON.stringify({ chatId, includeMessages, messageLimit: 100 // 默认限制100条消息 }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/get-chat`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "获取聊天记录成功", data: responseData, }; } catch (error) { console.error('获取聊天记录失败:', error); return { success: false, message: `获取聊天记录失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async updateChatTitle(chatId, title) { try { const requestBody = JSON.stringify({ chatId, title }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/update-chat-title`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "聊天标题修改成功", data: responseData, }; } catch (error) { console.error('修改聊天标题失败:', error); return { success: false, message: `修改聊天标题失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async deleteChat(chatId) { try { const requestBody = JSON.stringify({ chatId }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/delete-chat`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "聊天会话删除成功", data: responseData, }; } catch (error) { console.error('删除聊天会话失败:', error); return { success: false, message: `删除聊天会话失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } // ============ 图表管理 API ============ async createChart(fileUrl, prompt) { try { const requestBody = JSON.stringify({ fileUrl, prompt }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/new-chart`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "图表创建成功", data: responseData.data || responseData, }; } catch (error) { console.error('创建图表失败:', error); return { success: false, message: `创建图表失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async listCharts(params) { try { const requestBody = JSON.stringify(params || {}); const response = await fetch(`${this.baseUrl}/api/enterprise/external/list-charts`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "获取图表列表成功", data: responseData.data || responseData, }; } catch (error) { console.error('获取图表列表失败:', error); return { success: false, message: `获取图表列表失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async deleteChart(chartId) { try { const requestBody = JSON.stringify({ chartId }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/delete-chart`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "图表删除成功", data: responseData.data || responseData, }; } catch (error) { console.error('删除图表失败:', error); return { success: false, message: `删除图表失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } // ============ 工作流管理 API ============ async saveWorkflow(chatId, workflowName, description) { try { const requestBody = JSON.stringify({ chatId, workflowName, description }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/save-workflow`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "工作流保存成功", data: responseData.data || responseData, }; } catch (error) { console.error('保存工作流失败:', error); return { success: false, message: `保存工作流失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async listWorkflows(params) { try { const requestBody = JSON.stringify(params || {}); const response = await fetch(`${this.baseUrl}/api/enterprise/external/list-workflows`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "获取工作流列表成功", data: responseData.data || responseData, }; } catch (error) { console.error('获取工作流列表失败:', error); return { success: false, message: `获取工作流列表失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async executeWorkflow(workflowId, fileUrls, title) { try { const requestBody = JSON.stringify({ workflowId, fileUrls, title, sse: 0 }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/execute-workflow`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "工作流执行成功", data: responseData.data || responseData, }; } catch (error) { console.error('执行工作流失败:', error); return { success: false, message: `执行工作流失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async updateWorkflowName(workflowId, name, description) { try { const requestBody = JSON.stringify({ workflowId, name, description }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/update-workflow-name`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "工作流名称修改成功", data: responseData.data || responseData, }; } catch (error) { console.error('修改工作流名称失败:', error); return { success: false, message: `修改工作流名称失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } async deleteWorkflow(workflowId) { try { const requestBody = JSON.stringify({ workflowId }); const response = await fetch(`${this.baseUrl}/api/enterprise/external/delete-workflow`, { method: 'POST', headers: { 'Authorization': `Bearer ${this.mockApiKey}`, 'Content-Type': 'application/json' }, body: requestBody }); if (!response.ok) { const errorText = await response.text(); throw new Error(`API调用失败: ${response.status} - ${errorText}`); } if (AIBIAO_DEBUG) { return { success: true, message: await response.text() }; } const responseData = await response.json(); return { success: responseData.success, message: responseData.message || "工作流删除成功", data: responseData.data || responseData, }; } catch (error) { console.error('删除工作流失败:', error); return { success: false, message: `删除工作流失败: ${error instanceof Error ? error.message : '未知错误'}`, }; } } } // 初始化服务器和API客户端 const aibiao = new AibiaoAPI(AIBIAO_API_KEY, AIBIAO_BASE_URL); const server = new Server({ name: "aibiao-excel-mcp", version: "1.0.0", }, { capabilities: { tools: {} } }); // 注册可用工具 server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ // 系统管理 { name: "query_api_key_status", description: "查询API Key状态和使用额度 - 了解当前API配额使用情况", inputSchema: zodToJsonSchema(QueryApiKeyStatusSchema) }, // 聊天管理 { name: "create_chat", description: "创建新的AI Excel分析聊天会话 - 开始智能数据分析", inputSchema: zodToJsonSchema(CreateChatSchema) }, { name: "append_chat", description: "向聊天会话追加新问题 - 继续深入分析Excel数据", inputSchema: zodToJsonSchema(AppendChatSchema) }, { name: "list_chats", description: "查询所有聊天会话列表 - 管理你的Excel分析历史", inputSchema: zodToJsonSchema(ListChatsSchema) }, { name: "get_chat", description: "获取单个聊天会话详情 - 查看完整的分析过程", inputSchema: zodToJsonSchema(GetChatSchema) }, { name: "update_chat_title", description: "修改聊天会话标题 - 更好地组织你的分析项目", inputSchema: zodToJsonSchema(UpdateChatTitleSchema) }, { name: "delete_chat", description: "删除聊天会话 - 清理不需要的分析记录", inputSchema: zodToJsonSchema(DeleteChatSchema) }, // 图表管理 { name: "create_chart", description: "基于Excel文件创建智能图表 - AI自动生成数据可视化", inputSchema: zodToJsonSchema(CreateChartSchema) }, { name: "list_charts", description: "查询所有图表列表 - 管理你的数据可视化作品", inputSchema: zodToJsonSchema(ListChartsSchema) }, { name: "delete_chart", description: "删除指定图表 - 清理不需要的可视化图表", inputSchema: zodToJsonSchema(DeleteChartSchema) }, // 工作流管理 { name: "save_workflow", description: "将聊天记录保存为可重用工作流 - 创建数据处理自动化模板", inputSchema: zodToJsonSchema(SaveWorkflowSchema) }, { name: "list_workflows", description: "查询所有工作流模板 - 管理你的自动化数据处理流程", inputSchema: zodToJsonSchema(ListWorkflowsSchema) }, { name: "execute_workflow", description: "执行工作流模板 - 自动化处理新的Excel数据", inputSchema: zodToJsonSchema(ExecuteWorkflowSchema) }, { name: "update_workflow_name", description: "修改工作流名称和描述 - 更好地管理自动化模板", inputSchema: zodToJsonSchema(UpdateWorkflowNameSchema) }, { name: "delete_workflow", description: "删除工作流模板 - 清理不需要的自动化流程", inputSchema: zodToJsonSchema(DeleteWorkflowSchema) } ] }; }); // 处理工具调用 server.setRequestHandler(CallToolRequestSchema, async (request) => { try { if (!request.params.arguments) { throw new Error("Arguments are required"); } switch (request.params.name) { // 系统管理 case "query_api_key_status": { QueryApiKeyStatusSchema.parse(request.params.arguments); const result = await aibiao.queryApiKeyStatus(); return { toolResult: result }; } // 聊天管理 case "create_chat": { const args = CreateChatSchema.parse(request.params.arguments); const result = await aibiao.createChat(args.fileUrls, args.title); return { toolResult: result }; } case "append_chat": { const args = AppendChatSchema.parse(request.params.arguments); const result = await aibiao.appendChat(args.chatId, args.message); return { toolResult: result }; } case "list_chats": { const args = ListChatsSchema.parse(request.params.arguments); const result = await aibiao.listChats(args); return { toolResult: result }; } case "get_chat": { const args = GetChatSchema.parse(request.params.arguments); const result = await aibiao.getChat(args.chatId, args.includeMessages); return { toolResult: result }; } case "update_chat_title": { const args = UpdateChatTitleSchema.parse(request.params.arguments); const result = await aibiao.updateChatTitle(args.chatId, args.title); return { toolResult: result }; } case "delete_chat": { const args = DeleteChatSchema.parse(request.params.arguments); const result = await aibiao.deleteChat(args.chatId); return { toolResult: result }; } // 图表管理 case "create_chart": { const args = CreateChartSchema.parse(request.params.arguments); const result = await aibiao.createChart(args.fileUrl, args.prompt); return { toolResult: result }; } case "list_charts": { const args = ListChartsSchema.parse(request.params.arguments); const result = await aibiao.listCharts(args); return { toolResult: result }; } case "delete_chart": { const args = DeleteChartSchema.parse(request.params.arguments); const result = await aibiao.deleteChart(args.chartId); return { toolResult: result }; } // 工作流管理 case "save_workflow": { const args = SaveWorkflowSchema.parse(request.params.arguments); const result = await aibiao.saveWorkflow(args.chatId, args.workflowName, args.description); return { toolResult: result }; } case "list_workflows": { const args = ListWorkflowsSchema.parse(request.params.arguments); const result = await aibiao.listWorkflows(args); return { toolResult: result }; } case "execute_workflow": { const args = ExecuteWorkflowSchema.parse(request.params.arguments); const result = await aibiao.executeWorkflow(args.workflowId, args.fileUrls, args.title); return { toolResult: result }; } case "update_workflow_name": { const args = UpdateWorkflowNameSchema.parse(request.params.arguments); const result = await aibiao.updateWorkflowName(args.workflowId, args.name, args.description); return { toolResult: result }; } case "delete_workflow": { const args = DeleteWorkflowSchema.parse(request.params.arguments); const result = await aibiao.deleteWorkflow(args.workflowId); return { toolResult: result }; } default: throw new Error(`Unknown tool: ${request.params.name}`); } } catch (error) { if (error instanceof z.ZodError) { throw new Error(`Invalid arguments: ${error.message}`); } throw error; } }); // 启动服务器 async function runServer() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("🚀 AiBiao.cn Excel AI MCP Server 已启动 - 智能Excel数据分析就绪! 💪"); } runServer().catch((error) => { console.error("Fatal error in main():", error); process.exit(1); }); //# sourceMappingURL=index.js.map