kuaishou-image-mcp
Version:
使用快手API生成AI图片的 MCP 服务
221 lines (220 loc) • 8.77 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const readline = __importStar(require("readline"));
const axios_1 = __importDefault(require("axios"));
// 定义 MCP 服务器类
class MCPServer {
constructor() {
this.commands = {};
// 初始化 stdio 接口用于与 Claude 通信
this.stdio = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// 从环境变量获取 API Key
this.apiKey = process.env.API_KEY;
// 注册生成图片命令
this.registerCommand('generateImage', {
execute: this.generateImage.bind(this),
description: '使用快手API生成AI图片',
parameters: {
prompt: {
type: 'string',
description: '图片生成提示词',
required: true
},
size: {
type: 'string',
description: '图片尺寸',
enum: ['1024x1024', '1024x576', '576x1024', '720x1280', '1280x720'],
default: '1024x1024'
},
count: {
type: 'number',
description: '生成图片数量',
minimum: 1,
maximum: 4,
default: 1
}
}
});
// 开始监听命令
this.start();
}
// 注册命令
registerCommand(name, command) {
this.commands[name] = command;
}
// 生成图片的核心功能
async generateImage(params) {
if (!this.apiKey) {
throw new Error('未配置API密钥,请在 MCP 配置中设置 API_KEY 环境变量');
}
try {
console.error(`开始生成图片, 提示词: ${params.prompt}`);
const response = await axios_1.default.post('https://open.kuaishou.com/openapi/v1/ai/image/generate', {
prompt: params.prompt,
size: params.size || '1024x1024',
count: params.count || 1
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
}
});
const result = {
success: true,
data: {
images: response.data.images || [],
seed: response.data.seed || Math.floor(Math.random() * 1000000),
time_taken: response.data.time_taken || 'unknown'
}
};
console.error(`图片生成成功,返回 ${result.data.images.length} 张图片`);
return result;
}
catch (error) {
console.error(`图片生成失败: ${error.message}`);
if (error.response) {
// 处理API错误响应
switch (error.response.status) {
case 400:
throw new Error(`请求错误: ${error.response.data.message}`);
case 401:
throw new Error('无效的API密钥');
case 404:
throw new Error('API端点不存在');
case 429:
throw new Error('请求频率超限');
case 503:
throw new Error('服务暂时不可用');
case 504:
throw new Error('请求超时');
default:
throw new Error(`未知错误: ${error.response.status}`);
}
}
else if (error.request) {
throw new Error('请求发送失败,网络问题');
}
else {
throw new Error(`请求配置错误: ${error.message}`);
}
}
}
// 处理接收到的 JSON-RPC 2.0 消息
async handleMessage(message) {
try {
// 检查是否是有效的 JSON-RPC 2.0 请求
if (message.jsonrpc !== '2.0' || !message.method) {
return this.sendError(message.id, -32600, '无效的请求');
}
// 处理不同类型的请求
if (message.method === 'initialize') {
// 初始化请求,返回支持的命令
const commandsInfo = Object.keys(this.commands).map(name => ({
name,
description: this.commands[name].description,
parameters: this.commands[name].parameters
}));
return this.sendResult(message.id, {
name: 'kuaishou-image-generator',
version: '1.0.0',
commands: commandsInfo
});
}
else if (message.method === 'executeCommand') {
// 执行命令请求
const { command, params } = message.params || {};
if (!command) {
return this.sendError(message.id, -32602, '缺少命令名称');
}
if (!this.commands[command]) {
return this.sendError(message.id, -32601, `未找到命令: ${command}`);
}
try {
const result = await this.commands[command].execute(params || {});
return this.sendResult(message.id, result);
}
catch (error) {
return this.sendError(message.id, -32603, `执行命令出错: ${error.message}`);
}
}
else {
// 未知方法
return this.sendError(message.id, -32601, `未知方法: ${message.method}`);
}
}
catch (error) {
return this.sendError(message.id, -32700, `解析错误: ${error.message}`);
}
}
// 发送成功结果
sendResult(id, result) {
const response = {
jsonrpc: '2.0',
id,
result
};
console.log(JSON.stringify(response));
}
// 发送错误响应
sendError(id, code, message) {
const response = {
jsonrpc: '2.0',
id,
error: {
code,
message
}
};
console.log(JSON.stringify(response));
}
// 启动服务器,监听消息
start() {
this.stdio.on('line', async (line) => {
try {
const message = JSON.parse(line);
await this.handleMessage(message);
}
catch (error) {
console.error(`处理消息出错: ${error.message}`);
this.sendError(null, -32700, `无效的JSON: ${error.message}`);
}
});
// 在启动时打印一条调试信息,但不发送给客户端
console.error('快手文生图 MCP 服务已启动');
console.error('支持的命令:', Object.keys(this.commands).join(', '));
if (!this.apiKey) {
console.error('警告: 未设置 API_KEY 环境变量,无法调用快手 API');
}
}
}
// 创建并启动 MCP 服务器
new MCPServer();