index.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. #!/usr/bin/env node
  2. import { Server } from '@modelcontextprotocol/sdk/server/index.js';
  3. import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
  4. import {
  5. CallToolRequestSchema,
  6. ListToolsRequestSchema,
  7. } from '@modelcontextprotocol/sdk/types.js';
  8. import {
  9. getPendingTasks,
  10. getTaskById,
  11. updateTaskStatus,
  12. createTask,
  13. getAllTasks,
  14. closePool,
  15. } from './database.js';
  16. import { processTask } from './task-processor.js';
  17. import { info, error, setMcpServer } from './logger.js';
  18. /**
  19. * Task Manager MCP Server
  20. *
  21. * 提供任务管理功能,从PostgreSQL数据库读取任务,
  22. * 通过MCP协议与Cursor交互执行代码开发任务。
  23. */
  24. class TaskManagerServer {
  25. constructor() {
  26. this.server = new Server(
  27. {
  28. name: 'task-manager',
  29. version: '1.0.0',
  30. },
  31. {
  32. capabilities: {
  33. tools: {},
  34. logging: {}, // 启用日志通知功能
  35. },
  36. }
  37. );
  38. this.setupHandlers();
  39. this.pollingInterval = null;
  40. this.isProcessing = false;
  41. // 将 Server 实例传递给 logger,以便通过 MCP 协议发送日志
  42. setMcpServer(this.server);
  43. }
  44. setupHandlers() {
  45. // 列出所有可用工具
  46. this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
  47. tools: [
  48. {
  49. name: 'get_pending_tasks',
  50. description: '获取所有待处理的任务列表',
  51. inputSchema: {
  52. type: 'object',
  53. properties: {},
  54. },
  55. },
  56. {
  57. name: 'get_task_by_id',
  58. description: '根据任务ID获取任务详情',
  59. inputSchema: {
  60. type: 'object',
  61. properties: {
  62. task_id: {
  63. type: 'number',
  64. description: '任务ID',
  65. },
  66. },
  67. required: ['task_id'],
  68. },
  69. },
  70. {
  71. name: 'execute_task',
  72. description: '执行单个任务,支持自动完成模式(AI自动生成代码并更新状态)',
  73. inputSchema: {
  74. type: 'object',
  75. properties: {
  76. task_id: {
  77. type: 'number',
  78. description: '要执行的任务ID',
  79. },
  80. auto_complete: {
  81. type: 'boolean',
  82. description: '是否启用自动完成模式(AI自动生成代码并更新状态),默认为 true',
  83. default: true,
  84. },
  85. },
  86. required: ['task_id'],
  87. },
  88. },
  89. {
  90. name: 'update_task_status',
  91. description: '更新任务状态',
  92. inputSchema: {
  93. type: 'object',
  94. properties: {
  95. task_id: {
  96. type: 'number',
  97. description: '任务ID',
  98. },
  99. status: {
  100. type: 'string',
  101. enum: ['pending', 'processing', 'completed', 'failed'],
  102. description: '新状态',
  103. },
  104. code_name: {
  105. type: 'string',
  106. description: '生成的代码文件名(可选)',
  107. },
  108. code_path: {
  109. type: 'string',
  110. description: '代码文件路径(可选)',
  111. },
  112. },
  113. required: ['task_id', 'status'],
  114. },
  115. },
  116. {
  117. name: 'process_all_tasks',
  118. description: '批量处理所有待处理的任务',
  119. inputSchema: {
  120. type: 'object',
  121. properties: {
  122. auto_poll: {
  123. type: 'boolean',
  124. description: '是否启用自动轮询(每5分钟检查一次新任务)',
  125. default: false,
  126. },
  127. },
  128. },
  129. },
  130. {
  131. name: 'create_task',
  132. description: '创建新任务',
  133. inputSchema: {
  134. type: 'object',
  135. properties: {
  136. task_name: {
  137. type: 'string',
  138. description: '任务名称',
  139. },
  140. task_description: {
  141. type: 'string',
  142. description: '任务描述(markdown格式)',
  143. },
  144. create_by: {
  145. type: 'string',
  146. description: '创建者',
  147. },
  148. },
  149. required: ['task_name', 'task_description', 'create_by'],
  150. },
  151. },
  152. {
  153. name: 'get_all_tasks',
  154. description: '获取所有任务(用于调试)',
  155. inputSchema: {
  156. type: 'object',
  157. properties: {
  158. limit: {
  159. type: 'number',
  160. description: '返回的任务数量限制',
  161. default: 100,
  162. },
  163. },
  164. },
  165. },
  166. ],
  167. }));
  168. // 处理工具调用
  169. this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
  170. const { name, arguments: args } = request.params;
  171. try {
  172. switch (name) {
  173. case 'get_pending_tasks': {
  174. const tasks = await getPendingTasks();
  175. return {
  176. content: [
  177. {
  178. type: 'text',
  179. text: JSON.stringify(tasks, null, 2),
  180. },
  181. ],
  182. };
  183. }
  184. case 'get_task_by_id': {
  185. const task = await getTaskById(args.task_id);
  186. if (!task) {
  187. return {
  188. content: [
  189. {
  190. type: 'text',
  191. text: `Task with ID ${args.task_id} not found`,
  192. },
  193. ],
  194. isError: true,
  195. };
  196. }
  197. return {
  198. content: [
  199. {
  200. type: 'text',
  201. text: JSON.stringify(task, null, 2),
  202. },
  203. ],
  204. };
  205. }
  206. case 'execute_task': {
  207. info(`[Task Manager] Executing task ${args.task_id}...`);
  208. const task = await getTaskById(args.task_id);
  209. if (!task) {
  210. error(`[Task Manager] Task ${args.task_id} not found`);
  211. return {
  212. content: [
  213. {
  214. type: 'text',
  215. text: `Task with ID ${args.task_id} not found`,
  216. },
  217. ],
  218. isError: true,
  219. };
  220. }
  221. if (task.status !== 'pending') {
  222. error(`[Task Manager] Task ${args.task_id} is not in pending status. Current status: ${task.status}`);
  223. return {
  224. content: [
  225. {
  226. type: 'text',
  227. text: `Task ${args.task_id} is not in pending status. Current status: ${task.status}`,
  228. },
  229. ],
  230. isError: true,
  231. };
  232. }
  233. // 更新状态为处理中
  234. await updateTaskStatus(args.task_id, 'processing');
  235. info(`[Task Manager] Task ${args.task_id} status updated to 'processing'`);
  236. // 处理任务(支持自动完成模式)
  237. const autoComplete = args.auto_complete !== false; // 默认启用自动完成
  238. const result = await processTask(task, autoComplete);
  239. if (result.success) {
  240. if (autoComplete) {
  241. info(`[Task Manager] Task ${args.task_id} prepared for AUTO code generation.`);
  242. info(`[Task Manager] AI will automatically generate code and update task status.`);
  243. } else {
  244. info(`[Task Manager] Task ${args.task_id} prepared for MANUAL code generation.`);
  245. info(`[Task Manager] Please generate code and manually call update_task_status.`);
  246. }
  247. } else {
  248. error(`[Task Manager] Task ${args.task_id} preparation failed: ${result.message || 'Unknown error'}`);
  249. await updateTaskStatus(args.task_id, 'failed');
  250. }
  251. return {
  252. content: [
  253. {
  254. type: 'text',
  255. text: result.execution_instructions || JSON.stringify(result, null, 2),
  256. },
  257. ],
  258. };
  259. }
  260. case 'update_task_status': {
  261. const updated = await updateTaskStatus(
  262. args.task_id,
  263. args.status,
  264. args.code_name || null,
  265. args.code_path || null
  266. );
  267. return {
  268. content: [
  269. {
  270. type: 'text',
  271. text: JSON.stringify(updated, null, 2),
  272. },
  273. ],
  274. };
  275. }
  276. case 'process_all_tasks': {
  277. const result = await this.processAllTasks(args.auto_poll || false);
  278. return {
  279. content: [
  280. {
  281. type: 'text',
  282. text: JSON.stringify(result, null, 2),
  283. },
  284. ],
  285. };
  286. }
  287. case 'create_task': {
  288. const task = await createTask(
  289. args.task_name,
  290. args.task_description,
  291. args.create_by
  292. );
  293. return {
  294. content: [
  295. {
  296. type: 'text',
  297. text: JSON.stringify(task, null, 2),
  298. },
  299. ],
  300. };
  301. }
  302. case 'get_all_tasks': {
  303. const tasks = await getAllTasks(args.limit || 100);
  304. return {
  305. content: [
  306. {
  307. type: 'text',
  308. text: JSON.stringify(tasks, null, 2),
  309. },
  310. ],
  311. };
  312. }
  313. default:
  314. return {
  315. content: [
  316. {
  317. type: 'text',
  318. text: `Unknown tool: ${name}`,
  319. },
  320. ],
  321. isError: true,
  322. };
  323. }
  324. } catch (error) {
  325. return {
  326. content: [
  327. {
  328. type: 'text',
  329. text: `Error executing tool ${name}: ${error.message}\n${error.stack}`,
  330. },
  331. ],
  332. isError: true,
  333. };
  334. }
  335. });
  336. }
  337. /**
  338. * 处理所有待处理的任务
  339. */
  340. async processAllTasks(autoPoll = false) {
  341. if (this.isProcessing) {
  342. info('[Task Manager] Task processing is already in progress, skipping...');
  343. return {
  344. success: false,
  345. message: 'Task processing is already in progress',
  346. };
  347. }
  348. info('[Task Manager] Starting to process all pending tasks...');
  349. const processStartTime = Date.now();
  350. this.isProcessing = true;
  351. const results = {
  352. processed: 0,
  353. succeeded: 0,
  354. failed: 0,
  355. tasks: [],
  356. };
  357. try {
  358. const tasks = await getPendingTasks();
  359. if (tasks.length === 0) {
  360. info('[Task Manager] No pending tasks found, skipping processing.');
  361. return {
  362. success: true,
  363. message: 'No pending tasks to process',
  364. ...results,
  365. };
  366. }
  367. info(`[Task Manager] Processing ${tasks.length} task(s)...`);
  368. for (const task of tasks) {
  369. try {
  370. info(`[Task Manager] Processing task ${task.task_id}: ${task.task_name}`);
  371. // 更新状态为处理中
  372. await updateTaskStatus(task.task_id, 'processing');
  373. // 处理任务(默认启用自动完成模式)
  374. const autoComplete = true; // process_all_tasks 默认自动完成
  375. const result = await processTask(task, autoComplete);
  376. results.processed++;
  377. if (result.success) {
  378. results.succeeded++;
  379. // 注意:不立即标记为 completed
  380. // 任务保持 'processing' 状态,等待 AI 完成代码生成后
  381. // AI 会自动调用 update_task_status 工具更新状态
  382. info(`[Task Manager] Task ${task.task_id} prepared for AUTO execution.`);
  383. } else {
  384. results.failed++;
  385. await updateTaskStatus(task.task_id, 'failed');
  386. error(`[Task Manager] Task ${task.task_id} preparation failed: ${result.message || 'Unknown error'}`);
  387. }
  388. results.tasks.push({
  389. task_id: task.task_id,
  390. task_name: task.task_name,
  391. success: result.success,
  392. message: result.message,
  393. auto_complete: result.auto_complete,
  394. execution_instructions: result.execution_instructions,
  395. formatted_description: result.formatted_description,
  396. });
  397. } catch (err) {
  398. results.failed++;
  399. await updateTaskStatus(task.task_id, 'failed');
  400. error(`[Task Manager] Task ${task.task_id} failed with error: ${err.message}`);
  401. results.tasks.push({
  402. task_id: task.task_id,
  403. task_name: task.task_name,
  404. success: false,
  405. error: err.message,
  406. });
  407. }
  408. }
  409. const processDuration = Date.now() - processStartTime;
  410. info(`[Task Manager] Task processing completed. Processed: ${results.processed}, Succeeded: ${results.succeeded}, Failed: ${results.failed}, Duration: ${processDuration}ms`);
  411. // 如果启用自动轮询,启动轮询机制
  412. if (autoPoll && !this.pollingInterval) {
  413. this.startPolling();
  414. }
  415. return {
  416. success: true,
  417. message: `Processed ${results.processed} tasks. Succeeded: ${results.succeeded}, Failed: ${results.failed}`,
  418. ...results,
  419. };
  420. } finally {
  421. this.isProcessing = false;
  422. }
  423. }
  424. /**
  425. * 启动轮询机制
  426. */
  427. startPolling() {
  428. const pollInterval = parseInt(process.env.POLL_INTERVAL || '300000', 10); // 默认5分钟
  429. if (this.pollingInterval) {
  430. clearInterval(this.pollingInterval);
  431. }
  432. this.pollingInterval = setInterval(async () => {
  433. if (!this.isProcessing) {
  434. try {
  435. const tasks = await getPendingTasks();
  436. if (tasks.length > 0) {
  437. info(`Found ${tasks.length} new pending tasks, processing...`);
  438. await this.processAllTasks(false);
  439. }
  440. } catch (err) {
  441. error('Error during polling: ' + err.message);
  442. }
  443. }
  444. }, pollInterval);
  445. info(`Polling started with interval: ${pollInterval}ms (${pollInterval / 1000}s)`);
  446. }
  447. /**
  448. * 停止轮询机制
  449. */
  450. stopPolling() {
  451. if (this.pollingInterval) {
  452. clearInterval(this.pollingInterval);
  453. this.pollingInterval = null;
  454. info('Polling stopped');
  455. }
  456. }
  457. /**
  458. * 启动服务器
  459. */
  460. async start() {
  461. const transport = new StdioServerTransport();
  462. await this.server.connect(transport);
  463. info('Task Manager MCP Server started');
  464. // 自动启动轮询机制(如果环境变量 AUTO_START_POLLING 为 true 或未设置)
  465. const autoStartPolling = process.env.AUTO_START_POLLING !== 'false';
  466. if (autoStartPolling) {
  467. // 延迟启动,等待数据库连接就绪
  468. setTimeout(() => {
  469. this.startPolling();
  470. // 立即检查一次待处理任务
  471. this.processAllTasks(false).catch((err) => {
  472. error('Error during initial task processing: ' + err.message);
  473. });
  474. }, 2000); // 2秒后启动
  475. }
  476. }
  477. /**
  478. * 关闭服务器
  479. */
  480. async close() {
  481. this.stopPolling();
  482. await closePool();
  483. // MCP SDK会自动处理连接关闭
  484. }
  485. }
  486. // 启动服务器
  487. const server = new TaskManagerServer();
  488. // 处理进程退出
  489. process.on('SIGINT', async () => {
  490. await server.close();
  491. process.exit(0);
  492. });
  493. process.on('SIGTERM', async () => {
  494. await server.close();
  495. process.exit(0);
  496. });
  497. server.start().catch((err) => {
  498. error('Failed to start server: ' + err.message);
  499. process.exit(1);
  500. });