后端API集成指南
AI 导读
后端API集成指南 概述 本文档说明如何使用已实现的后端API端点,这些端点为MCP和Skill系统提供真实的执行能力。 已集成的LLM提供商 1. Anthropic Claude ✅ 模型:claude-3-5-sonnet-20241022, claude-3-opus, claude-3-haiku 用途:高质量推理、代码生成、长文本处理 API Key: 已配置 2. OpenAI...
后端API集成指南
概述
本文档说明如何使用已实现的后端API端点,这些端点为MCP和Skill系统提供真实的执行能力。
已集成的LLM提供商
1. Anthropic Claude ✅
- 模型:claude-3-5-sonnet-20241022, claude-3-opus, claude-3-haiku
- 用途:高质量推理、代码生成、长文本处理
- API Key: 已配置
2. OpenAI GPT ✅
- 模型:gpt-4o, gpt-4o-mini, gpt-3.5-turbo
- 用途:通用对话、代码辅助
- API Key: 已配置
3. OpenRouter ✅
- 提供商:多模型聚合路由
- 用途:访问多种开源和闭源模型
- API Key: 已配置
4. SiliconFlow ✅
- 模型:Qwen2-7B, DeepSeek等
- 用途:中文优化模型
- API Key: 已配置
5. Kimi (Moonshot) ✅
- 模型:moonshot-v1-8k, moonshot-v1-32k
- 用途:长上下文中文处理
- API Key: 已配置
6. Zhipu BigModel (智谱) ✅
- 模型:glm-4, glm-4-plus
- 用途:中文大模型
- API Key: 已配置
7. Poe ✅
- 提供商:多模型聚合
- API Key: 已配置
8. Google AI Studio ✅
- 模型:Gemini系列
- API Key: 已配置
9. ElevenLabs ✅
- 用途:TTS音频生成
- API Key: 已配置
MCP API端点
1. 连接MCP服务器
端点: POST /api/mcp/servers/:serverId/connect
请求体:
{
"config": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"],
"env": {
"NODE_ENV": "production"
}
}
}
响应:
{
"success": true,
"connectedAt": "2025-01-10T10:30:00.000Z"
}
使用示例:
const mcpManager = getMCPManager();
await mcpManager.addServer({
id: 'filesystem',
name: 'Filesystem Tools',
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
});
2. 获取工具列表
端点: GET /api/mcp/servers/:serverId/tools
响应:
{
"tools": [
{
"name": "read_file",
"description": "Read a file from the filesystem",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file"
}
},
"required": ["path"]
},
"serverId": "filesystem"
}
]
}
3. 调用MCP工具
端点: POST /api/mcp/servers/:serverId/call-tool
请求体:
{
"name": "read_file",
"arguments": {
"path": "/tmp/test.txt"
}
}
响应:
{
"success": true,
"content": [
{
"type": "text",
"text": "File contents here..."
}
]
}
Skill API端点
执行Skill
端点: POST /api/skills/execute
请求体:
{
"skillId": "data-analyst",
"inputs": {
"data": "name,age,salary\nJohn,30,50000\n...",
"analysisType": "summary"
},
"instructions": "You are an expert data analyst. Analyze the provided data and generate insights.",
"options": {
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.7,
"maxTokens": 4096
}
}
响应:
{
"success": true,
"outputs": {
"result": "Data analysis results..."
},
"duration": 2500,
"metadata": {
"tokensUsed": 1523,
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022"
}
}
完整使用示例
示例1: 使用MCP文件系统工具
// 1. 初始化MCP系统
import { initializeMCPManager, mcpPluginAdapter } from '@/lib/mcp';
import { initializePluginManager } from '@/lib/plugin-system';
const mcpManager = initializeMCPManager({
apiBaseUrl: '/api/mcp',
autoConnect: true,
});
// 2. 添加文件系统服务器
await mcpManager.addServer({
id: 'filesystem',
name: 'Filesystem',
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/workspace'],
});
// 3. 加载MCP适配器(自动将工具转换为节点)
const pluginManager = initializePluginManager();
await pluginManager.loadPlugin(mcpPluginAdapter);
// 4. 在工作流中使用(工具已自动注册为节点)
const workflow = {
nodes: [
{
id: 'read-file',
type: 'mcp_filesystem_read_file', // 自动注册的节点类型
data: {
label: '读取文件',
config: {
toolName: 'read_file',
},
},
},
],
};
const executor = new WorkflowExecutor(workflow, {}, {
userId: 'user-123',
workspaceId: 'ws-456',
tenantId: 'tenant-789',
});
const result = await executor.execute({
path: '/workspace/data.txt',
});
console.log(result.outputs); // 文件内容
示例2: 使用Skill进行数据分析
// 1. 初始化Skill系统
import { initializeSkillManager, skillPluginAdapter } from '@/lib/skill';
const skillManager = initializeSkillManager({
apiBaseUrl: '/api/skills',
autoEnable: true,
});
// 2. 注册自定义Skill加载器
class CustomSkillLoader implements SkillLoader {
async load(config: SkillConfig): Promise<SkillDefinition> {
return {
config,
inputs: [
{ name: 'data', type: 'string', required: true, description: 'CSV数据' },
{ name: 'analysisType', type: 'string', description: '分析类型' },
],
outputs: [
{ name: 'result', type: 'string', description: '分析结果' },
],
instructions: 'You are an expert data analyst...',
supportsStreaming: false,
};
}
async validate(definition: SkillDefinition) {
return { valid: true };
}
}
skillManager.registerLoader('custom', new CustomSkillLoader());
// 3. 注册Skill
await skillManager.registerSkill({
id: 'data-analyst',
name: 'Data Analyst',
source: 'custom',
});
// 4. 加载Skill适配器
const pluginManager = initializePluginManager();
await pluginManager.loadPlugin(skillPluginAdapter);
// 5. 在工作流中使用
const workflow = {
nodes: [
{
id: 'analyze',
type: 'skill_custom_data-analyst', // 自动注册的节点类型
data: {
label: '数据分析',
config: {
skillId: 'data-analyst',
},
},
},
],
};
const executor = new WorkflowExecutor(workflow, {}, {
userId: 'user-123',
workspaceId: 'ws-456',
tenantId: 'tenant-789',
});
const result = await executor.execute({
data: csvData,
analysisType: 'full',
});
console.log(result.outputs.result); // 分析报告
示例3: 切换不同的LLM提供商
// 使用Claude (默认)
const result1 = await llmService.complete({
provider: 'anthropic',
model: 'claude-3-5-sonnet-20241022',
messages: [
{ role: 'user', content: 'Explain quantum computing' },
],
});
// 使用OpenAI
const result2 = await llmService.complete({
provider: 'openai',
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Explain quantum computing' },
],
});
// 使用Kimi(中文优化)
const result3 = await llmService.complete({
provider: 'kimi',
model: 'moonshot-v1-32k',
messages: [
{ role: 'user', content: '解释量子计算' },
],
});
// 使用Zhipu(中文大模型)
const result4 = await llmService.complete({
provider: 'zhipu',
model: 'glm-4',
messages: [
{ role: 'user', content: '解释量子计算' },
],
});
// 使用OpenRouter(访问多种模型)
const result5 = await llmService.complete({
provider: 'openrouter',
model: 'anthropic/claude-3-opus',
messages: [
{ role: 'user', content: 'Explain quantum computing' },
],
});
环境变量配置
所有API密钥已配置在 .env.local 文件中:
# Anthropic Claude
ANTHROPIC_API_KEY=sk-ant-api03-...
# OpenAI
OPENAI_API_KEY=sk-proj-...
# Google AI Studio
GOOGLE_API_KEY=AIzaSyC...
# OpenRouter
OPENROUTER_API_KEY=sk-or-v1-...
# SiliconFlow
SILICONFLOW_API_KEY=sk-mfb...
# Kimi (Moonshot)
KIMI_API_KEY=sk-LLC...
# Zhipu BigModel
ZHIPU_API_KEY=5318...
# Poe
POE_API_KEY=qwcv...
# ElevenLabs
ELEVENLABS_API_KEY=sk_3dd...
# MCP配置
MCP_ENABLED=true
MCP_TIMEOUT=30000
# Skill配置
SKILL_ENABLED=true
SKILL_TIMEOUT=60000
测试API端点
1. 测试MCP连接
curl -X POST http://localhost:3000/api/mcp/servers/filesystem/connect \
-H "Content-Type: application/json" \
-d '{
"config": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
}
}'
2. 测试获取工具
curl http://localhost:3000/api/mcp/servers/filesystem/tools
3. 测试调用工具
curl -X POST http://localhost:3000/api/mcp/servers/filesystem/call-tool \
-H "Content-Type: application/json" \
-d '{
"name": "read_file",
"arguments": {
"path": "/tmp/test.txt"
}
}'
4. 测试Skill执行
curl -X POST http://localhost:3000/api/skills/execute \
-H "Content-Type: application/json" \
-d '{
"skillId": "test-skill",
"inputs": {
"question": "What is 2+2?"
},
"instructions": "You are a helpful assistant. Answer the question accurately.",
"options": {
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022"
}
}'
错误处理
所有API端点都返回标准的错误格式:
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": "Stack trace (仅在开发环境)"
}
}
常见错误码:
SERVER_NOT_CONNECTED- MCP服务器未连接EXECUTION_ERROR- 工具/Skill执行失败VALIDATION_ERROR- 参数验证失败
性能优化建议
1. 使用连接池
MCP客户端会在服务端保持连接,避免重复连接开销。
2. 缓存工具列表
工具列表可以缓存,定期刷新即可:
const mcpManager = initializeMCPManager({
toolsRefreshInterval: 60000, // 每分钟刷新一次
});
3. 选择合适的模型
- 快速响应: gpt-4o-mini, claude-3-haiku
- 高质量: claude-3-5-sonnet, gpt-4o
- 长文本: moonshot-v1-32k, claude-3-opus
- 中文优化: kimi, zhipu, qwen
4. 并发控制
使用队列控制并发请求数:
const pLimit = require('p-limit');
const limit = pLimit(5); // 最多5个并发
const results = await Promise.all(
requests.map(req => limit(() => llmService.complete(req)))
);
总结
✅ MCP系统已完全打通,可以连接任何MCP服务器并调用其工具 ✅ Skill系统已完全打通,支持6种LLM提供商 ✅ 所有API密钥已配置完成,可直接使用 ✅ 插件适配器会自动将MCP工具和Skills转换为工作流节点
系统现在可以实际运行和执行真实的AI任务!
猪哥云(四川)网络科技有限公司 | 合规网 www.hegui.com 猪哥云-数据产品部-Maurice | maurice_wen@proton.me 2025 猪哥云-灵阙企业级智能体平台