新增查詢任務與取得任務詳情的功能,允許用戶根據關鍵字或ID搜尋任務,並顯示完整的任務資訊。更新相關文檔以說明新功能的使用方式,提升系統的可用性與用戶體驗。

This commit is contained in:
siage 2025-04-14 01:05:40 +08:00
parent 12d4f84325
commit f5f606506a
11 changed files with 1754 additions and 102 deletions

196
README.md
View File

@ -1,64 +1,68 @@
# MCP 蝦米任務管理器
[English](README.md) | [中文](docs/zh/README.md)
# MCP Shrimp Task Manager
[![smithery badge](https://smithery.ai/badge/@cjo4m06/mcp-shrimp-task-manager)](https://smithery.ai/server/@cjo4m06/mcp-shrimp-task-manager)
> 🚀 基於 Model Context Protocol (MCP) 的智能任務管理系統,為 AI Agent 提供高效的程式開發工作流程框架。
> 🚀 An intelligent task management system based on Model Context Protocol (MCP), providing an efficient programming workflow framework for AI Agents.
蝦米任務管理器透過結構化的工作流程引導,協助 Agent 系統性規劃程式開發步驟,強化任務記憶管理機制,有效避免冗餘與重複的編程工作。
Shrimp Task Manager guides Agents through structured workflows for systematic programming, enhancing task memory management mechanisms, and effectively avoiding redundant and repetitive coding work.
## ✨ 功能特點
## ✨ Features
- **任務規劃與分析**:深入理解與分析複雜任務需求
- **智能任務拆分**:將大型任務自動拆分為可管理的小型任務
- **依賴關係管理**:精確處理任務間的依賴關係,確保正確的執行順序
- **執行狀態追蹤**:即時監控任務執行進度和狀態
- **任務完整性驗證**:確保任務成果符合預期要求
- **任務複雜度評估**:自動評估任務複雜度並提供最佳處理建議
- **任務摘要自動更新**:完成任務時自動產生摘要,優化記憶效能
- **任務記憶功能**:自動備份任務歷史記錄,提供長期記憶和參考能力
- **Task Planning and Analysis**: Deep understanding and analysis of complex task requirements
- **Intelligent Task Decomposition**: Automatically break down large tasks into manageable smaller tasks
- **Dependency Management**: Precisely handle dependencies between tasks, ensuring correct execution order
- **Execution Status Tracking**: Real-time monitoring of task execution progress and status
- **Task Completeness Verification**: Ensure task results meet expected requirements
- **Task Complexity Assessment**: Automatically evaluate task complexity and provide optimal handling suggestions
- **Automatic Task Summary Updates**: Automatically generate summaries upon task completion, optimizing memory performance
- **Task Memory Function**: Automatically backup task history, providing long-term memory and reference capabilities
## 🔄 任務管理工作流程
## 🔄 Task Management Workflow
本系統提供完整的任務管理生命週期:
The system provides a complete task management lifecycle:
1. **開始規劃** `plan_task`:分析任務問題,確定需求範圍
2. **深入分析** `analyze_task`:檢查現有代碼庫避免重複工作
3. **方案反思** `reflect_task`:批判性審查分析結果,確保方案完善
4. **任務拆分** `split_tasks`:將複雜任務分解為小型任務,建立明確依賴關係
5. **任務列表** `list_tasks`:查看所有任務及其執行狀態
6. **執行任務** `execute_task`:執行特定任務,同時評估複雜度
7. **結果檢驗** `verify_task`:全面檢查任務完成情況
8. **任務完成** `complete_task`:標記任務完成並生成報告,自動更新摘要
9. **任務管理** `delete_task`:管理未完成的任務(已完成任務將保留在系統中)
1. **Start Planning** `plan_task`: Analyze task problems, determine requirement scope
2. **In-depth Analysis** `analyze_task`: Check existing codebase to avoid duplicate work
3. **Solution Reflection** `reflect_task`: Critically review analysis results, ensure comprehensive solutions
4. **Task Decomposition** `split_tasks`: Break down complex tasks into smaller ones, establish clear dependencies
5. **Task List** `list_tasks`: View all tasks and their execution status
6. **Execute Task** `execute_task`: Execute specific tasks while assessing complexity
7. **Result Verification** `verify_task`: Comprehensively check task completion
8. **Task Completion** `complete_task`: Mark tasks as complete and generate reports, automatically update summaries
9. **Task Management** `delete_task`: Manage incomplete tasks (completed tasks remain in the system)
10. **Query Tasks** `query_task`: Search for related tasks in past memories using keywords
11. **Display Task** `get_task_detail`: Display complete task guidance
## 🧠 任務記憶功能
## 🧠 Task Memory Function
蝦米任務管理器具備長期記憶功能,可以自動保存任務執行的歷史記錄,並在規劃新任務時提供參考經驗。
Shrimp Task Manager has long-term memory capabilities, automatically saving task execution history and providing reference experiences when planning new tasks.
### 功能特點
### Key Features
- 系統會自動將任務備份到 memory 目錄中
- 備份文件按照時間順序命名,格式為 tasks_backup_YYYY-MM-DDThh-mm-ss.json
- 任務規劃 Agent 會自動獲得關於如何利用記憶功能的指導
- The system automatically backs up tasks to the memory directory
- Backup files are named in chronological order, in the format tasks_backup_YYYY-MM-DDThh-mm-ss.json
- Task planning Agents automatically receive guidance on how to use the memory function
### 優勢與效益
### Advantages and Benefits
- **避免重複工作**:參考過去任務,不必從零開始解決類似問題
- **借鑒成功經驗**:利用已驗證有效的解決方案,提高開發效率
- **學習與改進**:識別過去的錯誤或低效方案,持續優化工作流程
- **知識沉澱**:隨著系統使用時間增長,形成持續擴展的知識庫
- **Avoid Duplicate Work**: Reference past tasks, no need to solve similar problems from scratch
- **Learn from Successful Experiences**: Utilize proven effective solutions, improve development efficiency
- **Learning and Improvement**: Identify past mistakes or inefficient solutions, continuously optimize workflows
- **Knowledge Accumulation**: Form a continuously expanding knowledge base as system usage increases
通過有效利用任務記憶功能,系統能夠不斷積累經驗,智能化程度和工作效率將持續提升。
Through effective use of the task memory function, the system can continuously accumulate experience, with intelligence level and work efficiency continuously improving.
## 📚 文件資源
## 📚 Documentation Resources
- [系統架構](docs/architecture.md):詳細的系統設計與數據流說明
- [System Architecture](docs/en/architecture.md): Detailed system design and data flow explanation
## 🔧 安裝與使用
## 🔧 Installation and Usage
### Installing via Smithery
To install 蝦米任務管理器 for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@cjo4m06/mcp-shrimp-task-manager):
To install Shrimp Task Manager for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@cjo4m06/mcp-shrimp-task-manager):
```bash
npx -y @smithery/cli install @cjo4m06/mcp-shrimp-task-manager --client claude
@ -67,25 +71,25 @@ npx -y @smithery/cli install @cjo4m06/mcp-shrimp-task-manager --client claude
### Manual Installation
```bash
# 安裝依賴套件
# Install dependencies
npm install
# 建置並啟動服務
# Build and start service
npm run build
```
## 🔌 在支援 MCP 的客戶端中使用
## 🔌 Using with MCP-Compatible Clients
蝦米任務管理器可以與任何支援 Model Context Protocol 的客戶端一起使用,例如 Cursor IDE。
Shrimp Task Manager can be used with any client that supports the Model Context Protocol, such as Cursor IDE.
### 在 Cursor IDE 中配置
### Configuration in Cursor IDE
蝦米任務管理器提供兩種配置方式:全局配置和專案特定配置。
Shrimp Task Manager offers two configuration methods: global configuration and project-specific configuration.
#### 全局配置
#### Global Configuration
1. 開啟 Cursor IDE 的全局設定檔案(通常位於 `~/.cursor/mcp.json`
2. `mcpServers` 區段中添加以下配置:
1. Open the Cursor IDE global configuration file (usually located at `~/.cursor/mcp.json`)
2. Add the following configuration in the `mcpServers` section:
```json
{
@ -101,14 +105,14 @@ npm run build
}
```
> ⚠️ 請將 `/mcp-shrimp-task-manager` 替換為您的實際路徑。
> ⚠️ Please replace `/mcp-shrimp-task-manager` with your actual path.
#### 專案特定配置
#### Project-Specific Configuration
您也可以為每個專案設定專屬配置,以便針對不同專案使用獨立的數據目錄:
You can also set up dedicated configurations for each project to use independent data directories for different projects:
1. 在專案根目錄創建 `.cursor` 目錄
2. 在該目錄下創建 `mcp.json` 文件,內容如下:
1. Create a `.cursor` directory in the project root
2. Create an `mcp.json` file in this directory with the following content:
```json
{
@ -117,77 +121,79 @@ npm run build
"command": "node",
"args": ["/path/to/mcp-shrimp-task-manager/dist/index.js"],
"env": {
"DATA_DIR": "/path/to/project/data" // 必須使用絕對路徑
"DATA_DIR": "/path/to/project/data" // Must use absolute path
}
}
}
}
```
### ⚠️ 重要配置說明
### ⚠️ Important Configuration Notes
**DATA_DIR 參數**是蝦米任務管理器存儲任務數據、對話記錄等信息的目錄,正確設置此參數對於系統的正常運行至關重要。此參數必須使用**絕對路徑**,使用相對路徑可能導致系統無法正確定位數據目錄,造成數據丟失或功能失效。
The **DATA_DIR parameter** is the directory where Shrimp Task Manager stores task data, conversation logs, and other information. Setting this parameter correctly is crucial for the normal operation of the system. This parameter must use an **absolute path**; using a relative path may cause the system to incorrectly locate the data directory, resulting in data loss or function failure.
> **警告**:使用相對路徑可能導致以下問題:
> **Warning**: Using relative paths may cause the following issues:
>
> - 數據檔案找不到,導致系統初始化失敗
> - 任務狀態丟失或無法正確保存
> - 應用程式在不同環境下行為不一致
> - 系統崩潰或無法啟動
> - Data files not found, causing system initialization failure
> - Task status loss or inability to save correctly
> - Inconsistent application behavior across different environments
> - System crashes or failure to start
## 💡 系統提示詞指導
## 💡 System Prompt Guidance
### Cursor IDE 配置
### Cursor IDE Configuration
您可以啟用 Cursor Settings => Features => Custom modes 功能,並配置以下兩個模式:
You can enable Cursor Settings => Features => Custom modes, and configure the following two modes:
#### TaskPlanner 模式
#### TaskPlanner Mode
```
你是一個專業的任務規劃專家,你必須與用戶進行交互,分析用戶的需求,並收集專案相關資訊,最終使用 mcp_shrimp_task_manager_plan_task 建立任務,當任務建立完成後必須總結摘要,並告知用戶使用 任務執行 Model 進行任務執行。你必須專心於任務規劃禁止使用 mcp_shrimp_task_manager_execute_task 來執行任務,嚴重警告你是任務規劃專家,你不能直接修改程式碼,你只能規劃任務,並且你不能直接修改程式碼,你只能規劃任務。
You are a professional task planning expert who must interact with users, analyze their requirements, and collect project-related information, ultimately using mcp_shrimp_task_manager_plan_task to establish tasks. When tasks are established, you must summarize and inform users to use the Task Execution Model for task execution. You must focus on task planning and are prohibited from using mcp_shrimp_task_manager_execute_task to execute tasks. Serious warning: you are a task planning expert, you cannot directly modify code, you can only plan tasks, and you cannot directly modify code, you can only plan tasks.
```
#### TaskExecutor 模式
#### TaskExecutor Mode
```
你是一個專業的任務執行專家,當用戶有指定執行任務,則使用 mcp_shrimp_task_manager_execute_task 進行任務執行,沒有執行任務時則使用 mcp_shrimp_task_manager_list_tasks 尋找位執行的任務並執行,當執行完成後必須總結摘要告知用戶使用,你一次只能執行一個任務,單任務完成時除非用戶明確告知否則禁止進行下一則任務。用戶如果要求"連續模式"則按照順序連續執行所有任務
You are a professional task execution expert. When users specify task execution, use mcp_shrimp_task_manager_execute_task for task execution. Without specified tasks, use mcp_shrimp_task_manager_list_tasks to find unexecuted tasks and execute them. After completion, you must summarize and inform users. You can only execute one task at a time, and unless explicitly instructed by users, you are prohibited from proceeding to the next task after a single task is completed. If users request "continuous mode," execute all tasks in sequence.
```
> 💡 根據您的需求場景選擇適當的模式:
> 💡 Choose the appropriate mode based on your needs:
>
> - 當需要規劃任務時使用 **TaskPlanner** 模式
> - 當需要執行任務時使用 **TaskExecutor** 模式
> - Use **TaskPlanner** mode when planning tasks
> - Use **TaskExecutor** mode when executing tasks
### 在其他工具中使用
### Using with Other Tools
如果您的工具不支援 Custom modes 功能,可以:
If your tool doesn't support Custom modes, you can:
- 在不同階段手動貼上相應的提示詞
- 或直接使用簡單命令如 `請規劃以下任務:......``請開始執行任務...`
- Manually paste the appropriate prompts at different stages
- Or directly use simple commands like `Please plan the following task: ......` or `Please start executing the task...`
## 🛠️ 可用工具一覽
## 🛠️ Available Tools Overview
配置完成後,您可使用以下工具:
After configuration, you can use the following tools:
| 功能分類 | 工具名稱 | 功能描述 |
| ------------ | --------------- | ------------------ |
| **任務規劃** | `plan_task` | 開始規劃任務 |
| **任務分析** | `analyze_task` | 深入分析任務需求 |
| **方案評估** | `reflect_task` | 反思與改進方案構想 |
| **任務管理** | `split_tasks` | 將任務拆分為子任務 |
| | `list_tasks` | 顯示所有任務及狀態 |
| | `delete_task` | 刪除未完成的任務 |
| **任務執行** | `execute_task` | 執行特定任務 |
| | `verify_task` | 檢驗任務完成情況 |
| | `complete_task` | 標記任務為已完成 |
| Category | Tool Name | Description |
| ----------------------- | ----------------- | -------------------------------------- |
| **Task Planning** | `plan_task` | Start planning tasks |
| **Task Analysis** | `analyze_task` | In-depth analysis of task requirements |
| **Solution Assessment** | `reflect_task` | Reflect and improve solution concepts |
| **Task Management** | `split_tasks` | Break tasks into subtasks |
| | `list_tasks` | Display all tasks and status |
| | `query_task` | Search and list tasks |
| | `get_task_detail` | Display complete task details |
| | `delete_task` | Delete incomplete tasks |
| **Task Execution** | `execute_task` | Execute specific tasks |
| | `verify_task` | Verify task completion |
| | `complete_task` | Mark tasks as completed |
## 🔧 技術實現
## 🔧 Technical Implementation
- **Node.js**:高效能的 JavaScript 運行時環境
- **TypeScript**:提供強型別安全的開發環境
- **MCP SDK**:與大型語言模型無縫互動的接口
- **UUID**:生成唯一且可靠的任務識別碼
- **Node.js**: High-performance JavaScript runtime environment
- **TypeScript**: Provides type-safe development environment
- **MCP SDK**: Interface for seamless interaction with large language models
- **UUID**: Generate unique and reliable task identifiers
## 📄 許可協議
## 📄 License
本專案採用 MIT 許可協議發布
This project is released under the MIT License

0
docs/en/.gitkeep Normal file
View File

463
docs/en/architecture.md Normal file
View File

@ -0,0 +1,463 @@
# Architecture Design Document for Shrimp Task Manager
[English](../en/architecture.md) | [中文](../zh/architecture.md)
## 1. System Overview
The Shrimp Task Manager is designed based on the MCP (Model-Chain-Protocol) framework architecture, implementing a task management system with memory capability. The system's primary functionality is to assist Large Language Models (LLMs) in efficiently managing complex task execution processes.
## 2. Design Goals
The core design goals of the Shrimp Task Manager include:
- **Memory Enhancement**: Overcome the context limitations of LLMs, enabling long-term task processing.
- **Context Management**: Provide relevant context for each task based on dependencies and related files.
- **Process Standardization**: Establish a standardized process for task planning, execution, and verification.
- **Knowledge Accumulation**: Support continuous accumulation of task execution experience.
## 3. Architecture Layers
The system architecture consists of the following layers:
```
+-----------------+
| User Interface |
+-----------------+
|
+------------------+
| Tool Layer |
+------------------+
|
+------------------+
| Business Layer |
+------------------+
|
+------------------+
| Data Layer |
+------------------+
```
### 3.1 User Interface Layer
The user interface layer provides tool functions for users to interact with the system. These tools are registered through the MCP protocol and can be directly called by the user.
### 3.2 Tool Layer
The tool layer implements the specific logic of each tool function, handles parameter validation, and coordinates the business layer's functionality. Core tool implementations are located in the `src/tools` directory.
### 3.3 Business Layer
The business layer contains the core business logic, including task processing, task memory management, file relationship processing, etc. The main implementation is in the `src/models` directory.
### 3.4 Data Layer
The data layer is responsible for data persistence and retrieval, maintaining task lists, task execution history, etc. It implements file-based storage in the `src/utils` directory.
## 4. Core Components
### 4.1 Task Management Module
Responsible for the entire lifecycle management of tasks, including:
- Task planning and splitting
- Task execution
- Task verification
- Task completion
- Task updates
- Task queries
### 4.2 Task Memory Module
Manages the execution history and experience of tasks, with key functions:
- Automatic saving of task execution records
- Loading of historical task context
- Creation of backup files
### 4.3 File Association Module
Manages the relationship between tasks and related files, including:
- Creating file association information
- Loading file summaries
- Updating file relationships
### 4.4 Task Complexity Assessment Module
Evaluates the complexity of tasks based on various indicators, helping to determine the appropriate execution strategy.
## 5. Core Interaction Flows
### 5.1 Task Planning Flow
```
+--------------------+ +------------------+ +---------------+
| | | | | |
| plan_task Schema |---->| planTask |---->| createTaskPlan|
| | | (taskTools.ts) | | (taskModel.ts)|
+--------------------+ +--------+---------+ +-------+-------+
| |
v v
+-------+-------------------+------+
| Validate Parameters |
+-------+-------------------+------+
|
v
+-------+-------------------+------+
| Create Task Plan with Goals |
+-------+-------------------+------+
|
v
+-------+-------------------+------+
| Save Task Plan to Storage |
+-------+-------------------+------+
```
### 5.2 Task Analysis Flow
```
+----------------------+ +-------------------+ +------------------+
| | | | | |
| analyze_task Schema |---->| analyzeTask |---->| createTaskAnalysis|
| | | (taskTools.ts) | | (taskModel.ts) |
+----------------------+ +---------+---------+ +---------+--------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check for Previous Analysis |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Create Analysis with Technical Details|
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Save Analysis to Storage |
+-------+-------------------------+------+
```
### 5.3 Task Reflection Flow
```
+---------------------+ +-------------------+ +-----------------+
| | | | | |
| reflect_task Schema |---->| reflectTask |---->| createReflection|
| | | (taskTools.ts) | | (taskModel.ts) |
+---------------------+ +---------+---------+ +---------+-------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check for Previous Analysis |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Create Reflection with Review |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Save Reflection to Storage |
+-------+-------------------------+------+
```
### 5.4 Task Splitting Flow
```
+--------------------+ +------------------+ +--------------------+
| | | | | |
| split_tasks Schema |---->| splitTasks |---->| createTaskList |
| | | (taskTools.ts) | | (taskModel.ts) |
+--------------------+ +--------+---------+ +---------+----------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Process Update Mode |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Create Atomic Tasks with Dependencies |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Save Task List to Storage |
+-------+-------------------------+------+
```
### 5.5 Task Execution Flow
```
+--------------------+ +------------------+ +------------------+
| | | | | |
| execute_task Schema|---->| executeTask |---->| processExecution |
| | | (taskTools.ts) | | (taskModel.ts) |
+--------------------+ +--------+---------+ +---------+--------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check Dependency Status |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Load Task Context (Plan, Analysis) |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Load Related Files Context |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Mark Task as In Progress |
+-------+-------------------------+------+
```
### 5.6 Task Verification Flow
```
+--------------------+ +------------------+ +------------------+
| | | | | |
| verify_task Schema |---->| verifyTask |---->| processVerification|
| | | (taskTools.ts) | | (taskModel.ts) |
+--------------------+ +--------+---------+ +---------+--------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check Task Exists & In Progress |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Load Task Context (Implementation) |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Generate Verification Report |
+-------+-------------------------+------+
```
### 5.7 Task Completion Flow
```
+--------------------+ +------------------+ +--------------------+
| | | | | |
| complete_task Schema|---->| completeTask |---->| processCompletion |
| | | (taskTools.ts) | | (taskModel.ts) |
+--------------------+ +--------+---------+ +---------+----------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check Task Exists & In Progress |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Generate Completion Summary |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Update Task Status to Complete |
+-------+-------------------------+------+
```
### 5.8 Task Deletion Flow
```
+--------------------+ +------------------+ +--------------------+
| | | | | |
| delete_task Schema |---->| deleteTask |---->| processTaskDeletion|
| | | (taskTools.ts) | | (taskModel.ts) |
+--------------------+ +--------+---------+ +---------+----------+
| |
v v
+-------+-------------------------+------+
| Validate Parameters |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Check Task Exists & Not Complete |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Update Dependent Tasks |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Remove Task from Task List |
+-------+-------------------------+------+
```
### 5.9 Task Complexity Assessment Flow
```
+-------------------------+ +------------------------+
| | | |
| assessTaskComplexity |---->| Complex Analysis Logic |
| (taskModel.ts) | | |
+-------------------------+ +-----------+------------+
|
v
+-----------+------------------------+
| Check Task Description Length |
+-----------+------------------------+
|
v
+-----------+------------------------+
| Count Technical Terms |
+-----------+------------------------+
|
v
+-----------+------------------------+
| Analyze Dependency Count |
+-----------+------------------------+
|
v
+-----------+------------------------+
| Count File Operations |
+-----------+------------------------+
|
v
+-----------+------------------------+
| Calculate Weighted Complexity Score|
+-----------+------------------------+
```
### 5.10 Task File Loading Flow
```
+----------------------+ +--------------------+
| | | |
| loadTaskRelatedFiles |---->| getFileSummaries |
| (fileLoader.ts) | | (fileLoader.ts) |
+----------------------+ +---------+----------+
|
v
+--------+------------------------+
| Format Paths to Absolute Paths |
+--------+------------------------+
|
v
+--------+------------------------+
| Generate File Type Summaries |
+--------+------------------------+
|
v
+--------+------------------------+
| Return Formatted File Summaries |
+--------+------------------------+
|
v
+--------+------------------------+
| |
+--------+---------------------+--+
```
### 5.11 Updating Task Related Files Function
```
+----------------------+ +---------------------+ +----------------------+
| | | | | |
| updateTaskFilesSchema |---->| updateTaskRelatedFiles |---->| updateTaskRelatedFiles |
| | | (taskTools.ts) | | (taskModel.ts) |
+----------------------+ +-----------+---------+ +-----------+----------+
| |
v v
+-------+-------------------------+------+
| Validate File Format and Path |
+-------+-------------------------+------+
|
v
+-------+-------------------------+------+
| Update Task Related Files List |
+-------+-------------------------+------+
```
## 6. Extensibility Considerations
### 6.1 Method for New Feature Extensions
The modular design of the Shrimp Task Manager makes it easy to extend. To add new features, typically you need to:
1. Define related data types in `types/index.ts`
2. Implement core logic in the corresponding model files
3. Create corresponding tool functions in the tool layer
4. Register new tools in `index.ts`
### 6.2 Current Extension Points
The system currently provides the following extension points:
- **Task Processing Flow Extension**: Can extend the task processing flow by modifying functions like `executeTask`, `verifyTask`, etc.
- **Complexity Assessment Extension**: Can add more evaluation metrics in `assessTaskComplexity`
- **Summary Generation Extension**: Can enhance algorithms in `summaryExtractor.ts`
- **File Processing Extension**: Can support more file type summary formatting in `fileLoader.ts`
- **Filter Condition Extension**: Can add more filter condition options in task queries
## 7. System Limitations and Future Improvements
### 7.1 Current Limitations
- Uses file storage, not suitable for multi-user concurrent scenarios
- Lacks user authentication and permission control
- Summary generation uses simple rules, can be further improved
- File processing does not read actual file content, only generates summary information
### 7.2 Potential Future Improvements
- Migrate to database storage, improving concurrent processing capabilities
- Add user management and access control
- Use more advanced algorithms to optimize summary generation
- Add task priority and time planning functionality
- Implement task execution progress tracking
- Enhance file association system, supporting more complex relationship types
- Implement automatic identification of related files
- Support actual reading of file content, providing more detailed context
## 8. Conclusion
The Shrimp Task Manager adopts a modular, layered design, giving the system good maintainability and extensibility. Through 12 core tool functions and a well-developed data model, the system can effectively manage task processes in complex projects, performing exceptionally well in scenarios requiring long-term context memory.
The design focus of the system is to provide a clear task management process while enhancing the LLM's context memory capability during task execution. Through precise file association and intelligent context loading, it effectively solves the memory limitation problem that LLMs face when handling long-term complex tasks.
As the system continues to develop, future efforts will focus on improving data storage methods, optimizing summary generation algorithms, enhancing file processing capabilities, and adding more task management features, enabling the system to handle more complex task management scenarios.

View File

@ -0,0 +1,357 @@
[English](../en/functionality-checklist.md) | [中文](../zh/functionality-checklist.md)
# Shrimp Task Manager - Functionality Implementation Checklist
This document lists all the tools, functions, parameter structures, and features actually implemented in the Shrimp Task Manager system. This checklist serves as a reference baseline for documentation review.
## Type Definitions and Enumerations
### Task Status Enumeration (TaskStatus)
- `PENDING = "待處理"` - Tasks that have been created but not yet started
- `IN_PROGRESS = "進行中"` - Tasks currently being executed
- `COMPLETED = "已完成"` - Tasks that have been successfully completed and verified
- `BLOCKED = "被阻擋"` - Tasks that cannot be executed temporarily due to dependencies
### Task Dependency (TaskDependency)
- `taskId: string` - Unique identifier of the prerequisite task that must be completed before the current task
### Related File Type Enumeration (RelatedFileType)
- `TO_MODIFY = "待修改"` - Files that need to be modified in the task
- `REFERENCE = "參考資料"` - Reference materials or related documents for the task
- `CREATE = "待建立"` - Files that need to be created in the task
- `DEPENDENCY = "依賴文件"` - Component or library files that the task depends on
- `OTHER = "其他"` - Other types of related files
### Related File (RelatedFile)
- `path: string` - File path, can be relative to the project root directory or an absolute path
- `type: RelatedFileType` - Type of relationship between the file and the task
- `description?: string` - Supplementary description of the file, explaining its specific relationship or purpose to the task
- `lineStart?: number` - Starting line of the relevant code block (optional)
- `lineEnd?: number` - Ending line of the relevant code block (optional)
### Task Interface (Task)
- `id: string` - Unique identifier of the task
- `name: string` - Concise and clear task name
- `description: string` - Detailed task description, including implementation points and acceptance criteria
- `notes?: string` - Supplementary notes, special processing requirements, or implementation suggestions (optional)
- `status: TaskStatus` - Current execution status of the task
- `dependencies: TaskDependency[]` - List of prerequisite dependencies for the task
- `createdAt: Date` - Timestamp when the task was created
- `updatedAt: Date` - Timestamp when the task was last updated
- `completedAt?: Date` - Timestamp when the task was completed (only applicable to completed tasks)
- `summary?: string` - Task completion summary, concisely describing implementation results and important decisions (only applicable to completed tasks)
- `relatedFiles?: RelatedFile[]` - List of files related to the task (optional)
### Task Complexity Level Enumeration (TaskComplexityLevel)
- `LOW = "低複雜度"` - Simple and straightforward tasks that usually do not require special handling
- `MEDIUM = "中等複雜度"` - Tasks with some complexity but still manageable
- `HIGH = "高複雜度"` - Complex and time-consuming tasks that require special attention
- `VERY_HIGH = "極高複雜度"` - Extremely complex tasks that are recommended to be broken down
### Task Complexity Assessment Result (TaskComplexityAssessment)
- `level: TaskComplexityLevel` - Overall complexity level
- `metrics: object` - Detailed data for each evaluation metric
- `descriptionLength: number` - Length of description
- `dependenciesCount: number` - Number of dependencies
- `notesLength: number` - Length of notes
- `hasNotes: boolean` - Whether notes are present
- `recommendations: string[]` - List of handling recommendations
## Tool Functions and Parameters
### 1. plan_task
**Description**: Initialize and plan the task process in detail, establishing clear goals and success criteria
**Parameters**:
- `description: string` (required) - Comprehensive and detailed task problem description, should include task objectives, background, and expected outcomes
- Must be at least 10 characters
- `requirements?: string` (optional) - Specific technical requirements, business constraints, or quality standards for the task
**Return Value**:
- Returns a response containing planning prompts to guide the user in starting task analysis
### 2. analyze_task
**Description**: Deeply analyze task requirements and systematically check the codebase, evaluating technical feasibility and potential risks
**Parameters**:
- `summary: string` (required) - Structured task summary, including task objectives, scope, and key technical challenges
- Must be at least 20 characters
- `initialConcept: string` (required) - Initial solution concept, including technical solutions, architectural design, and implementation strategy
- Must be at least 50 characters
- `previousAnalysis?: string` (optional) - Analysis results from previous iterations, used for continuous improvement of the solution
**Return Value**:
- Returns a response containing technical analysis guidance to direct the user in conducting in-depth analysis
### 3. reflect_task
**Description**: Critically review analysis results, evaluate solution completeness, and identify optimization opportunities, ensuring the solution follows best practices
**Parameters**:
- `summary: string` (required) - Structured task summary, keeping consistent with the analysis phase to ensure continuity
- Must be at least 20 characters
- `analysis: string` (required) - Comprehensive and thorough technical analysis results, including all technical details, dependent components, and implementation plans
- Must be at least 100 characters
**Return Value**:
- Returns a response containing reflection prompts and implementation suggestions
### 4. split_tasks
**Description**: Break down complex tasks into independent and trackable subtasks, establishing clear dependencies and priorities
**Parameters**:
- `updateMode: "append" | "overwrite" | "selective" | "clearAllTasks"` (required) - Task update mode selection:
- `append`: Preserve all existing tasks and add new tasks
- `overwrite`: Clear all incomplete tasks and completely replace them
- `selective`: Update existing tasks based on task name matching, preserving tasks not in the list
- `clearAllTasks`: Clear all tasks and create a backup
- `tasks: Array<object>` (required) - Structured list of tasks, each task should be atomic and have clear completion criteria
- `name: string` (required) - Concise and clear task name that should clearly express the task purpose
- Not exceeding 100 characters
- `description: string` (required) - Detailed task description, including implementation points, technical details, and acceptance criteria
- Must be at least 10 characters
- `notes?: string` (optional) - Supplementary notes, special processing requirements, or implementation suggestions
- `dependencies?: string[]` (optional) - List of prerequisite task IDs or task names that this task depends on
- `relatedFiles?: RelatedFile[]` (optional) - List of files related to the task
**Return Value**:
- Returns a response containing task splitting results, including the number of successfully created tasks and the list of task IDs
### 5. list_tasks
**Description**: Generate a structured task list, including complete status tracking, priorities, and dependencies
**Parameters**: None
**Return Value**:
- Returns a response containing a task list, displaying all tasks grouped by status
### 6. execute_task
**Description**: Execute a specific task according to the predefined plan, ensuring that the output of each step meets quality standards
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be executed, must be a valid task ID existing in the system
**Return Value**:
- Returns a response containing task execution guidelines, including task details, complexity assessment, and suggested execution steps
### 7. verify_task
**Description**: Comprehensively verify task completion, ensuring all requirements and technical standards have been met, with no details omitted
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be verified, must be a valid task ID existing in the system
**Return Value**:
- Returns a response containing task verification results, including completion criteria checks and specific verification items
### 8. complete_task
**Description**: Formally mark a task as completed, generate a detailed completion report, and update the dependency status of related tasks
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be completed, must be a valid task ID existing in the system
- `summary?: string` (optional) - Task completion summary, concisely describing implementation results and important decisions
**Return Value**:
- Returns a response containing task completion confirmation, including completion time and updated dependent task status
### 9. delete_task
**Description**: Delete an incomplete task, but do not allow deletion of completed tasks, ensuring the integrity of system records
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be deleted, must be a valid and incomplete task ID existing in the system
**Return Value**:
- Returns a response containing task deletion results, including success or failure messages
### 10. clear_all_tasks
**Description**: Delete all incomplete tasks in the system, this command must be explicitly confirmed by the user to execute. At the same time, back up tasks to the memory subdirectory, saving task history records for future reference.
**Parameters**:
- `confirm: boolean` (required) - Confirm deletion of all incomplete tasks (this operation is irreversible)
**Return Value**:
- Returns a response containing the results of the clear operation, including success or failure messages, backup file name, and backup location
**Important Details**:
- Before deleting tasks, the current task list is automatically backed up to the data/memory subdirectory
- Backup files are named using timestamps, in the format tasks_memory_YYYY-MM-DDThh-mm-ss.json
- The memory subdirectory serves as a long-term memory repository for storing task history records, for future task planning reference
### 11. query_task
**Description**: Search for tasks based on keywords or ID, displaying abbreviated task information
**Parameters**:
- `query: string` (required) - Search query text, can be a task ID or multiple keywords (space-separated)
- Must be at least 1 character
- `isId: boolean` (optional) - Specify whether it is an ID query mode, default is false (keyword mode)
- `page: number` (optional) - Page number, default is page 1
- `pageSize: number` (optional) - Number of tasks displayed per page, default is 5 entries, maximum 20
- Must be a positive integer, range 1-20
**Return Value**:
- Returns a response containing search results, including a list of tasks matching the criteria, pagination information, and total number of results
**Important Details**:
- When `isId` is true, the system will precisely query the task with the specified ID
- When `isId` is false, the system will search for the specified keywords in task names, descriptions, and summaries
- Keyword mode supports multiple keywords (space-separated), returning tasks matching any of the keywords
- Results are sorted by task status and update time, making it easy to quickly find the most relevant tasks
### 12. update_task
**Description**: Update task content, including name, description, and notes, but do not allow modification of completed tasks
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be updated, must be a valid and incomplete task ID existing in the system
- `name?: string` (optional) - New name for the task
- `description?: string` (optional) - New description content for the task
- `notes?: string` (optional) - New supplementary notes for the task
**Return Value**:
- Returns a response containing task update results, including success or failure messages
### 13. get_task_detail
**Description**: Get complete detailed information of a task based on the task ID, including untruncated implementation guidelines and verification standards
**Parameters**:
- `taskId: string` (required) - ID of the task to view details
- Must be at least 1 character
**Return Value**:
- Returns a response containing complete task details, including all task attributes, especially complete implementation guidelines and verification standards
**Important Details**:
- Unlike `list_tasks`, this function returns complete details of a single task, with no content truncation
- Suitable for in-depth understanding of specific task requirements and technical details
- Provides a complete list of related files and task analysis results
- Can be used to view long text content that may be omitted during execution
### 14. update_task_files
**Description**: Update the list of related files for a task, used to record code files, reference materials, etc. related to the task
**Parameters**:
- `taskId: string` (required) - Unique identifier of the task to be updated, must be a valid and incomplete task ID existing in the system
- `relatedFiles: Array<RelatedFile>` (required) - List of files related to the task
- `path: string` (required) - File path, can be relative to the project root directory or an absolute path
- `type: RelatedFileType` (required) - Type of relationship between the file and the task
- `description?: string` (optional) - Supplementary description of the file
- `lineStart?: number` (optional) - Starting line of the relevant code block
- `lineEnd?: number` (optional) - Ending line of the relevant code block
**Return Value**:
- Returns a response containing file update results, including success or failure messages
## Important Details of Tool Functions
### Dependency (dependencies) Handling
- In `splitTasks` and other functions, the `dependencies` parameter accepts task names or task IDs (UUID)
- The system converts string arrays to `TaskDependency` object arrays when creating or updating tasks
- Task dependencies form a directed acyclic graph (DAG), used to determine task execution order and blocking status
### Task Complexity Assessment
- The system uses the `assessTaskComplexity` function to evaluate task complexity
- Evaluation is based on multiple metrics: description length, number of dependencies, notes length, etc.
- Complexity levels are determined based on thresholds defined in `TaskComplexityThresholds`
- Complexity assessment results are used to generate appropriate handling recommendations
### File Processing Features
- The `loadTaskRelatedFiles` function does not actually read file contents, it only generates file information summaries
- Files are sorted by type priority: TO_MODIFY > REFERENCE > DEPENDENCY > CREATE > OTHER
- Supports specifying code block line number ranges for precise localization of key implementations
## Utility Functions
### Summary Extraction (summaryExtractor.ts)
- `extractSummary` - Extract short summaries from text, automatically handling Markdown format
- `generateTaskSummary` - Generate task completion summaries based on task names and descriptions
- `extractTitle` - Extract text suitable as titles from content
### File Loading (fileLoader.ts)
- `loadTaskRelatedFiles` - Generate content summaries of task-related files
- `generateFileInfo` - Generate basic file information summaries
## Task Memory Feature
The Task Memory feature is an important characteristic of the Shrimp Task Manager, giving the system long-term memory capabilities to save, query, and utilize past task execution experiences.
### Core Implementation
1. **Automatic Backup Mechanism**:
- Dual backup functionality implemented in the `clearAllTasks` function
- Task backups are saved in both the data directory and the data/memory subdirectory
- Backup files are named using timestamps, in the format tasks_memory_YYYY-MM-DDThh-mm-ss.json
2. **Intelligent Prompt Guidance**:
- Task memory retrieval guidelines added to the prompt in the `planTask` function
- Guides Agents on how to find, analyze, and apply historical task records
- Provides intelligent reference suggestions, promoting knowledge reuse
### Use Cases
- **During Task Planning**: Reference implementation plans and best practices from similar tasks
- **During Problem Solving**: Consult similar problems encountered in the past and their solutions
- **During Code Reuse**: Identify reusable components or patterns implemented in the past
- **During Experience Learning**: Analyze past successful and failed cases, continuously optimize working methods
### Technical Points
- Use relative paths to reference the memory directory, maintaining code consistency and maintainability
- Ensure the memory directory exists, automatically creating it if it doesn't
- Maintain the original error handling pattern, ensuring system stability
- The backup process is transparent and unnoticeable, not affecting the user's normal operation flow
This feature requires no additional tools or configuration. The system automatically saves historical records when tasks are cleared and provides intelligent guidance during task planning, allowing Agents to fully utilize past experiences and knowledge.

0
docs/zh/.gitkeep Normal file
View File

199
docs/zh/README.md Normal file
View File

@ -0,0 +1,199 @@
[English](../../README.md) | [中文](README.md)
# MCP 蝦米任務管理器
[![smithery badge](https://smithery.ai/badge/@cjo4m06/mcp-shrimp-task-manager)](https://smithery.ai/server/@cjo4m06/mcp-shrimp-task-manager)
> 🚀 基於 Model Context Protocol (MCP) 的智能任務管理系統,為 AI Agent 提供高效的程式開發工作流程框架。
蝦米任務管理器透過結構化的工作流程引導,協助 Agent 系統性規劃程式開發步驟,強化任務記憶管理機制,有效避免冗餘與重複的編程工作。
## ✨ 功能特點
- **任務規劃與分析**:深入理解與分析複雜任務需求
- **智能任務拆分**:將大型任務自動拆分為可管理的小型任務
- **依賴關係管理**:精確處理任務間的依賴關係,確保正確的執行順序
- **執行狀態追蹤**:即時監控任務執行進度和狀態
- **任務完整性驗證**:確保任務成果符合預期要求
- **任務複雜度評估**:自動評估任務複雜度並提供最佳處理建議
- **任務摘要自動更新**:完成任務時自動產生摘要,優化記憶效能
- **任務記憶功能**:自動備份任務歷史記錄,提供長期記憶和參考能力
## 🔄 任務管理工作流程
本系統提供完整的任務管理生命週期:
1. **開始規劃** `plan_task`:分析任務問題,確定需求範圍
2. **深入分析** `analyze_task`:檢查現有代碼庫避免重複工作
3. **方案反思** `reflect_task`:批判性審查分析結果,確保方案完善
4. **任務拆分** `split_tasks`:將複雜任務分解為小型任務,建立明確依賴關係
5. **任務列表** `list_tasks`:查看所有任務及其執行狀態
6. **執行任務** `execute_task`:執行特定任務,同時評估複雜度
7. **結果檢驗** `verify_task`:全面檢查任務完成情況
8. **任務完成** `complete_task`:標記任務完成並生成報告,自動更新摘要
9. **任務管理** `delete_task`:管理未完成的任務(已完成任務將保留在系統中)
10. **查詢任務** `query_task`:透過關鍵字查詢以往記憶是否有相關任務
11. **顯示任務** `get_task_detail`:顯示完整任務指導
## 🧠 任務記憶功能
蝦米任務管理器具備長期記憶功能,可以自動保存任務執行的歷史記錄,並在規劃新任務時提供參考經驗。
### 功能特點
- 系統會自動將任務備份到 memory 目錄中
- 備份文件按照時間順序命名,格式為 tasks_backup_YYYY-MM-DDThh-mm-ss.json
- 任務規劃 Agent 會自動獲得關於如何利用記憶功能的指導
### 優勢與效益
- **避免重複工作**:參考過去任務,不必從零開始解決類似問題
- **借鑒成功經驗**:利用已驗證有效的解決方案,提高開發效率
- **學習與改進**:識別過去的錯誤或低效方案,持續優化工作流程
- **知識沉澱**:隨著系統使用時間增長,形成持續擴展的知識庫
通過有效利用任務記憶功能,系統能夠不斷積累經驗,智能化程度和工作效率將持續提升。
## 📚 文件資源
- [系統架構](architecture.md):詳細的系統設計與數據流說明
## 🔧 安裝與使用
### Installing via Smithery
To install 蝦米任務管理器 for Claude Desktop automatically via [Smithery](https://smithery.ai/server/@cjo4m06/mcp-shrimp-task-manager):
```bash
npx -y @smithery/cli install @cjo4m06/mcp-shrimp-task-manager --client claude
```
### Manual Installation
```bash
# 安裝依賴套件
npm install
# 建置並啟動服務
npm run build
```
## 🔌 在支援 MCP 的客戶端中使用
蝦米任務管理器可以與任何支援 Model Context Protocol 的客戶端一起使用,例如 Cursor IDE。
### 在 Cursor IDE 中配置
蝦米任務管理器提供兩種配置方式:全局配置和專案特定配置。
#### 全局配置
1. 開啟 Cursor IDE 的全局設定檔案(通常位於 `~/.cursor/mcp.json`
2. 在 `mcpServers` 區段中添加以下配置:
```json
{
"mcpServers": {
"shrimp-task-manager": {
"command": "node",
"args": ["/mcp-shrimp-task-manager/dist/index.js"],
"env": {
"DATA_DIR": "/mcp-shrimp-task-manager/data"
}
}
}
}
```
> ⚠️ 請將 `/mcp-shrimp-task-manager` 替換為您的實際路徑。
#### 專案特定配置
您也可以為每個專案設定專屬配置,以便針對不同專案使用獨立的數據目錄:
1. 在專案根目錄創建 `.cursor` 目錄
2. 在該目錄下創建 `mcp.json` 文件,內容如下:
```json
{
"mcpServers": {
"shrimp-task-manager": {
"command": "node",
"args": ["/path/to/mcp-shrimp-task-manager/dist/index.js"],
"env": {
"DATA_DIR": "/path/to/project/data" // 必須使用絕對路徑
}
}
}
}
```
### ⚠️ 重要配置說明
**DATA_DIR 參數**是蝦米任務管理器存儲任務數據、對話記錄等信息的目錄,正確設置此參數對於系統的正常運行至關重要。此參數必須使用**絕對路徑**,使用相對路徑可能導致系統無法正確定位數據目錄,造成數據丟失或功能失效。
> **警告**:使用相對路徑可能導致以下問題:
>
> - 數據檔案找不到,導致系統初始化失敗
> - 任務狀態丟失或無法正確保存
> - 應用程式在不同環境下行為不一致
> - 系統崩潰或無法啟動
## 💡 系統提示詞指導
### Cursor IDE 配置
您可以啟用 Cursor Settings => Features => Custom modes 功能,並配置以下兩個模式:
#### TaskPlanner 模式
```
你是一個專業的任務規劃專家,你必須與用戶進行交互,分析用戶的需求,並收集專案相關資訊,最終使用 mcp_shrimp_task_manager_plan_task 建立任務,當任務建立完成後必須總結摘要,並告知用戶使用 任務執行 Model 進行任務執行。你必須專心於任務規劃禁止使用 mcp_shrimp_task_manager_execute_task 來執行任務,嚴重警告你是任務規劃專家,你不能直接修改程式碼,你只能規劃任務,並且你不能直接修改程式碼,你只能規劃任務。
```
#### TaskExecutor 模式
```
你是一個專業的任務執行專家,當用戶有指定執行任務,則使用 mcp_shrimp_task_manager_execute_task 進行任務執行,沒有執行任務時則使用 mcp_shrimp_task_manager_list_tasks 尋找位執行的任務並執行,當執行完成後必須總結摘要告知用戶使用,你一次只能執行一個任務,單任務完成時除非用戶明確告知否則禁止進行下一則任務。用戶如果要求"連續模式"則按照順序連續執行所有任務
```
> 💡 根據您的需求場景選擇適當的模式:
>
> - 當需要規劃任務時使用 **TaskPlanner** 模式
> - 當需要執行任務時使用 **TaskExecutor** 模式
### 在其他工具中使用
如果您的工具不支援 Custom modes 功能,可以:
- 在不同階段手動貼上相應的提示詞
- 或直接使用簡單命令如 `請規劃以下任務:......``請開始執行任務...`
## 🛠️ 可用工具一覽
配置完成後,您可使用以下工具:
| 功能分類 | 工具名稱 | 功能描述 |
| ------------ | ----------------- | ------------------ |
| **任務規劃** | `plan_task` | 開始規劃任務 |
| **任務分析** | `analyze_task` | 深入分析任務需求 |
| **方案評估** | `reflect_task` | 反思與改進方案構想 |
| **任務管理** | `split_tasks` | 將任務拆分為子任務 |
| | `list_tasks` | 顯示所有任務及狀態 |
| | `query_task` | 搜尋並列出任務 |
| | `get_task_detail` | 顯示完整任務詳情 |
| | `delete_task` | 刪除未完成的任務 |
| **任務執行** | `execute_task` | 執行特定任務 |
| | `verify_task` | 檢驗任務完成情況 |
| | `complete_task` | 標記任務為已完成 |
## 🔧 技術實現
- **Node.js**:高效能的 JavaScript 運行時環境
- **TypeScript**:提供強型別安全的開發環境
- **MCP SDK**:與大型語言模型無縫互動的接口
- **UUID**:生成唯一且可靠的任務識別碼
## 📄 許可協議
本專案採用 MIT 許可協議發布

View File

@ -1,5 +1,7 @@
# 蝦米任務管理器系統架構
[English](../en/architecture.md) | [中文](../zh/architecture.md)
本文檔描述蝦米任務管理器的系統架構設計,包括各組件的功能、交互方式和數據流。
## 1. 系統整體架構
@ -115,7 +117,7 @@
- `TaskStatus` 枚舉:定義任務狀態,包括待處理、進行中、已完成和被阻擋
- `TaskDependency` 接口:定義任務依賴關係
- `RelatedFileType` 枚舉:定義文件關聯類型,如待修改、參考資料、輸出結果、依賴文件和其他
- `RelatedFileType` 枚舉:定義文件關聯類型,如待修改、參考資料、待建立、依賴文件和其他
- `RelatedFile` 接口:定義任務相關文件結構
- `Task` 接口:定義任務的完整數據結構
- `TaskComplexityLevel` 枚舉:定義任務複雜度級別,如低複雜度、中等複雜度、高複雜度和極高複雜度
@ -247,6 +249,7 @@ LLM 調用 clear_all_tasks
|
v
載入當前任務列表
|
|
v
篩選出未完成的任務
@ -326,7 +329,7 @@ LLM 調用 update_task_files
v
根據文件類型進行優先級排序
| |
| +---> 待修改 > 參考資料 > 依賴文件 > 輸出結果 > 其他
| +---> 待修改 > 參考資料 > 依賴文件 > 待建立 > 其他
|
v
生成文件摘要

View File

@ -1,3 +1,5 @@
[English](../en/functionality-checklist.md) | [中文](../zh/functionality-checklist.md)
# 蝦米任務管理器 - 功能實現清單
本文檔列出蝦米任務管理器系統中所有實際實現的工具函數、參數結構和功能。此清單作為文檔審查的基準參考。
@ -19,7 +21,7 @@
- `TO_MODIFY = "待修改"` - 需要在任務中修改的文件
- `REFERENCE = "參考資料"` - 任務的參考資料或相關文檔
- `OUTPUT = "輸出結果"` - 任務產生的輸出文件
- `CREATE = "待建立"` - 需要在任務中建立的文件
- `DEPENDENCY = "依賴文件"` - 任務依賴的組件或庫文件
- `OTHER = "其他"` - 其他類型的相關文件
@ -210,7 +212,31 @@
- 備份文件使用時間戳命名,格式為 tasks_memory_YYYY-MM-DDThh-mm-ss.json
- memory 子目錄作為長期記憶庫,用於存儲任務歷史記錄,供未來任務規劃參考
### 11. update_task
### 11. query_task
**描述**:根據關鍵字或 ID 搜尋任務,顯示省略版的任務資訊
**參數**
- `query: string` (必填) - 搜尋查詢文字,可以是任務 ID 或多個關鍵字(空格分隔)
- 必須至少 1 個字符
- `isId: boolean` (選填) - 指定是否為 ID 查詢模式,默認為否(關鍵字模式)
- `page: number` (選填) - 分頁頁碼,默認為第 1 頁
- `pageSize: number` (選填) - 每頁顯示的任務數量,默認為 5 筆,最大 20 筆
- 必須為正整數,範圍 1-20
**返回值**
- 返回一個包含搜尋結果的響應,包括符合條件的任務列表、分頁資訊和總結果數量
**重要細節**
- 當 `isId` 為 true 時,系統會精確查詢指定 ID 的任務
- 當 `isId` 為 false 時,系統會在任務名稱、描述和摘要中搜尋指定關鍵字
- 關鍵字模式支持多個關鍵字(以空格分隔),將返回符合任一關鍵字的任務
- 結果會按任務狀態和更新時間排序,便於快速找到最相關的任務
### 12. update_task
**描述**:更新任務內容,包括名稱、描述和注記,但不允許修改已完成的任務
@ -225,7 +251,27 @@
- 返回一個包含任務更新結果的響應,包括成功或失敗的訊息
### 12. update_task_files
### 13. get_task_detail
**描述**:根據任務 ID 獲取任務的完整詳細信息,包括未截斷的實現指南和驗證標準等
**參數**
- `taskId: string` (必填) - 欲檢視詳情的任務 ID
- 必須至少 1 個字符
**返回值**
- 返回一個包含任務完整詳情的響應,包括所有任務屬性,特別是完整的實現指南和驗證標準
**重要細節**
- 與 `list_tasks` 不同,此功能返回單個任務的完整詳情,沒有內容截斷
- 適用於深入了解特定任務的要求和技術細節
- 提供完整的相關文件列表和任務分析結果
- 可用於檢視執行過程中可能被省略的長文本內容
### 14. update_task_files
**描述**:更新任務相關文件列表,用於記錄與任務相關的代碼文件、參考資料等
@ -261,7 +307,7 @@
### 文件處理功能
- `loadTaskRelatedFiles` 函數不實際讀取檔案內容,僅生成文件資訊摘要
- 文件按類型優先級排序:待修改 > 參考資料 > 依賴文件 > 輸出結果 > 其他
- 文件按類型優先級排序:待修改 > 參考資料 > 依賴文件 > 待建立 > 其他
- 支持指定代碼區塊行號範圍,便於精確定位關鍵實現
## 實用工具函數

View File

@ -28,6 +28,10 @@ import {
updateTaskContentSchema,
updateTaskRelatedFiles,
updateTaskRelatedFilesSchema,
queryTask,
queryTaskSchema,
getTaskDetail,
getTaskDetailSchema,
} from "./tools/taskTools.js";
async function main() {
@ -398,6 +402,61 @@ async function main() {
}
);
// 註冊查詢任務工具
server.tool(
"query_task",
"根據關鍵字或ID搜尋任務顯示省略版的任務資訊",
{
query: z
.string()
.min(1, {
message: "查詢內容不能為空請提供任務ID或搜尋關鍵字",
})
.describe("搜尋查詢文字可以是任務ID或多個關鍵字空格分隔"),
isId: z
.boolean()
.optional()
.default(false)
.describe("指定是否為ID查詢模式默認為否關鍵字模式"),
page: z
.number()
.int()
.positive()
.optional()
.default(1)
.describe("分頁頁碼默認為第1頁"),
pageSize: z
.number()
.int()
.positive()
.min(1)
.max(20)
.optional()
.default(5)
.describe("每頁顯示的任務數量默認為5筆最大20筆"),
},
async (args) => {
return await queryTask(args);
}
);
// 註冊取得任務完整詳情工具
server.tool(
"get_task_detail",
"根據任務ID獲取任務的完整詳細信息包括未截斷的實現指南和驗證標準等",
{
taskId: z
.string()
.min(1, {
message: "任務ID不能為空請提供有效的任務ID",
})
.describe("欲檢視詳情的任務ID"),
},
async (args) => {
return await getTaskDetail(args);
}
);
// 建立連接
const transport = new StdioServerTransport();
await server.connect(transport);

View File

@ -11,6 +11,8 @@ import fs from "fs/promises";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { fileURLToPath } from "url";
import { exec } from "child_process";
import { promisify } from "util";
// 確保獲取專案資料夾路徑
const __filename = fileURLToPath(import.meta.url);
@ -21,6 +23,9 @@ const PROJECT_ROOT = path.resolve(__dirname, "../..");
const DATA_DIR = process.env.DATA_DIR || path.join(PROJECT_ROOT, "data");
const TASKS_FILE = path.join(DATA_DIR, "tasks.json");
// 將exec轉換為Promise形式
const execPromise = promisify(exec);
// 確保數據目錄存在
async function ensureDataDir() {
try {
@ -749,3 +754,267 @@ export async function clearAllTasks(): Promise<{
};
}
}
// 使用系統指令搜尋任務記憶
export async function searchTasksWithCommand(
query: string,
isId: boolean = false,
page: number = 1,
pageSize: number = 5
): Promise<{
tasks: Task[];
pagination: {
currentPage: number;
totalPages: number;
totalResults: number;
hasMore: boolean;
};
}> {
// 讀取當前任務檔案中的任務
const currentTasks = await readTasks();
let memoryTasks: Task[] = [];
// 搜尋記憶資料夾中的任務
const MEMORY_DIR = path.join(DATA_DIR, "memory");
try {
// 確保記憶資料夾存在
await fs.access(MEMORY_DIR);
// 生成搜尋命令
const cmd = generateSearchCommand(query, isId, MEMORY_DIR);
// 如果有搜尋命令,執行它
if (cmd) {
try {
console.log(`Executing command: ${cmd}`);
const { stdout } = await execPromise(cmd, {
maxBuffer: 1024 * 1024 * 10,
});
if (stdout) {
// 解析搜尋結果,提取符合的檔案路徑
const matchedFiles = new Set<string>();
stdout.split("\n").forEach((line) => {
if (line.trim()) {
// 格式通常是: 文件路徑:匹配內容
const filePath = line.split(":")[0];
if (filePath) {
matchedFiles.add(filePath);
}
}
});
// 限制讀取檔案數量
const MAX_FILES_TO_READ = 10;
const sortedFiles = Array.from(matchedFiles)
.sort()
.reverse()
.slice(0, MAX_FILES_TO_READ);
// 只處理符合條件的檔案
for (const filePath of sortedFiles) {
try {
const data = await fs.readFile(filePath, "utf-8");
const tasks = JSON.parse(data).tasks || [];
// 格式化日期字段
const formattedTasks = tasks.map((task: any) => ({
...task,
createdAt: task.createdAt
? new Date(task.createdAt)
: new Date(),
updatedAt: task.updatedAt
? new Date(task.updatedAt)
: new Date(),
completedAt: task.completedAt
? new Date(task.completedAt)
: undefined,
}));
// 進一步過濾任務確保符合條件
const filteredTasks = isId
? formattedTasks.filter((task: Task) => task.id === query)
: formattedTasks.filter((task: Task) => {
const keywords = query
.split(/\s+/)
.filter((k) => k.length > 0);
if (keywords.length === 0) return true;
return keywords.every((keyword) => {
const lowerKeyword = keyword.toLowerCase();
return (
task.name.toLowerCase().includes(lowerKeyword) ||
task.description.toLowerCase().includes(lowerKeyword) ||
(task.notes &&
task.notes.toLowerCase().includes(lowerKeyword)) ||
(task.implementationGuide &&
task.implementationGuide
.toLowerCase()
.includes(lowerKeyword)) ||
(task.summary &&
task.summary.toLowerCase().includes(lowerKeyword))
);
});
});
memoryTasks.push(...filteredTasks);
} catch (error: unknown) {
console.error(`讀取檔案 ${filePath} 時發生錯誤:`, error);
}
}
}
} catch (error: unknown) {
// grep沒有找到匹配項時會返回錯誤但這不是真正的錯誤
// 只有當錯誤代碼不是1(沒有匹配)時才記錄錯誤
const err = error as { code?: number };
if (err.code !== 1) {
console.error("執行搜尋指令時發生錯誤:", error);
}
}
}
} catch (error: unknown) {
console.error("搜尋記憶資料夾時發生錯誤:", error);
}
// 從當前任務中過濾符合條件的任務
const filteredCurrentTasks = filterCurrentTasks(currentTasks, query, isId);
// 合併結果並去重
const taskMap = new Map<string, Task>();
// 當前任務優先
filteredCurrentTasks.forEach((task) => {
taskMap.set(task.id, task);
});
// 加入記憶任務,避免重複
memoryTasks.forEach((task) => {
if (!taskMap.has(task.id)) {
taskMap.set(task.id, task);
}
});
// 合併後的結果
const allTasks = Array.from(taskMap.values());
// 排序 - 按照更新或完成時間降序排列
allTasks.sort((a, b) => {
// 優先按完成時間排序
if (a.completedAt && b.completedAt) {
return b.completedAt.getTime() - a.completedAt.getTime();
} else if (a.completedAt) {
return -1; // a完成了但b未完成a排前面
} else if (b.completedAt) {
return 1; // b完成了但a未完成b排前面
}
// 否則按更新時間排序
return b.updatedAt.getTime() - a.updatedAt.getTime();
});
// 分頁處理
const totalResults = allTasks.length;
const totalPages = Math.ceil(totalResults / pageSize);
const safePage = Math.max(1, Math.min(page, totalPages || 1)); // 確保頁碼有效
const startIndex = (safePage - 1) * pageSize;
const endIndex = Math.min(startIndex + pageSize, totalResults);
const paginatedTasks = allTasks.slice(startIndex, endIndex);
return {
tasks: paginatedTasks,
pagination: {
currentPage: safePage,
totalPages: totalPages || 1,
totalResults,
hasMore: safePage < totalPages,
},
};
}
// 根據平台生成適當的搜尋命令
function generateSearchCommand(
query: string,
isId: boolean,
memoryDir: string
): string {
// 安全地轉義用戶輸入
const safeQuery = escapeShellArg(query);
const keywords = safeQuery.split(/\s+/).filter((k) => k.length > 0);
// 檢測操作系統類型
const isWindows = process.platform === "win32";
if (isWindows) {
// Windows環境使用findstr命令
if (isId) {
// ID搜尋
return `findstr /s /i /c:"${safeQuery}" "${memoryDir}\\*.json"`;
} else if (keywords.length === 1) {
// 單一關鍵字
return `findstr /s /i /c:"${safeQuery}" "${memoryDir}\\*.json"`;
} else {
// 多關鍵字搜尋 - Windows中使用PowerShell
const keywordPatterns = keywords.map((k) => `'${k}'`).join(" -and ");
return `powershell -Command "Get-ChildItem -Path '${memoryDir}' -Filter *.json -Recurse | Select-String -Pattern ${keywordPatterns} | ForEach-Object { $_.Path }"`;
}
} else {
// Unix/Linux/MacOS環境使用grep命令
if (isId) {
return `grep -r --include="*.json" "${safeQuery}" "${memoryDir}"`;
} else if (keywords.length === 1) {
return `grep -r --include="*.json" "${safeQuery}" "${memoryDir}"`;
} else {
// 多關鍵字用管道連接多個grep命令
const firstKeyword = escapeShellArg(keywords[0]);
const otherKeywords = keywords.slice(1).map((k) => escapeShellArg(k));
let cmd = `grep -r --include="*.json" "${firstKeyword}" "${memoryDir}"`;
for (const keyword of otherKeywords) {
cmd += ` | grep "${keyword}"`;
}
return cmd;
}
}
}
/**
* shell參數
*/
function escapeShellArg(arg: string): string {
if (!arg) return "";
// 移除所有控制字符和特殊字符
return arg
.replace(/[\x00-\x1F\x7F]/g, "") // 控制字符
.replace(/[&;`$"'<>|]/g, ""); // Shell 特殊字符
}
// 過濾當前任務列表
function filterCurrentTasks(
tasks: Task[],
query: string,
isId: boolean
): Task[] {
if (isId) {
return tasks.filter((task) => task.id === query);
} else {
const keywords = query.split(/\s+/).filter((k) => k.length > 0);
if (keywords.length === 0) return tasks;
return tasks.filter((task) => {
return keywords.every((keyword) => {
const lowerKeyword = keyword.toLowerCase();
return (
task.name.toLowerCase().includes(lowerKeyword) ||
task.description.toLowerCase().includes(lowerKeyword) ||
(task.notes && task.notes.toLowerCase().includes(lowerKeyword)) ||
(task.implementationGuide &&
task.implementationGuide.toLowerCase().includes(lowerKeyword)) ||
(task.summary && task.summary.toLowerCase().includes(lowerKeyword))
);
});
});
}
}

View File

@ -13,6 +13,7 @@ import {
clearAllTasks as modelClearAllTasks,
updateTaskContent as modelUpdateTaskContent,
updateTaskRelatedFiles as modelUpdateTaskRelatedFiles,
searchTasksWithCommand,
} from "../models/taskModel.js";
import {
TaskStatus,
@ -211,9 +212,12 @@ export async function planTask({
prompt += `## 資訊收集指南\n\n`;
prompt += `1. **詢問用戶** - 當你對任務要求有疑問時,直接詢問用戶\n`;
prompt += `2. **查詢記憶** - 使用「query_task」工具查詢以往記憶是否有相關任務\n`;
prompt += `3. **網路搜索** - 當出現你不理解的名詞或概念時,使用網路搜尋工具找尋答案\n\n`;
prompt += `## 下一步行動\n\n完成初步分析後使用「analyze_task」工具提交分析結果包含\n\n`;
prompt += `## 下一步行動\n\n`;
prompt += `- 如果需要請先使用「query_task」工具查詢以往記憶是否有相關任務\n`;
prompt += `- 完成初步分析後使用「analyze_task」工具提交分析結果包含\n\n`;
prompt += `1. **任務摘要** - 目標、範圍、挑戰和限制條件\n`;
prompt += `2. **初步解答構想** - 可行的技術方案和實施計劃\n`;
@ -1616,3 +1620,249 @@ const formatTaskDetails = (task: Task) => {
return details;
};
// 查詢任務工具
export const queryTaskSchema = z.object({
query: z
.string()
.min(1, {
message: "查詢內容不能為空請提供任務ID或搜尋關鍵字",
})
.describe("搜尋查詢文字可以是任務ID或多個關鍵字空格分隔"),
isId: z
.boolean()
.optional()
.default(false)
.describe("指定是否為ID查詢模式默認為否關鍵字模式"),
page: z
.number()
.int()
.positive()
.optional()
.default(1)
.describe("分頁頁碼默認為第1頁"),
pageSize: z
.number()
.int()
.positive()
.min(1)
.max(20)
.optional()
.default(5)
.describe("每頁顯示的任務數量默認為5筆最大20筆"),
});
export async function queryTask({
query,
isId = false,
page = 1,
pageSize = 3,
}: z.infer<typeof queryTaskSchema>) {
try {
// 使用系統指令搜尋函數
const results = await searchTasksWithCommand(query, isId, page, pageSize);
// 格式化任務顯示內容
const tasksDisplay = results.tasks.map((task) =>
formatTaskForDisplay(task)
);
// 構建分頁指導訊息
let paginationMessage = "";
if (results.pagination.totalResults > 0) {
paginationMessage = `\n\n## 分頁資訊\n\n- 當前頁: ${results.pagination.currentPage}/${results.pagination.totalPages}\n- 顯示結果: ${results.tasks.length}筆(共${results.pagination.totalResults}筆)`;
if (results.pagination.hasMore) {
paginationMessage += `\n\n要查看下一頁結果請使用相同的查詢參數但將頁碼設為 ${
results.pagination.currentPage + 1
}`;
}
}
let responseText = "";
if (results.tasks.length === 0) {
responseText = `## 查詢結果\n\n未找到符合條件的任務。請嘗試使用不同的關鍵字或檢查任務ID是否正確。`;
} else {
responseText = `## 查詢結果 (${
results.pagination.totalResults
})\n\n${tasksDisplay.join("\n\n")}${paginationMessage}`;
}
return {
content: [
{
type: "text" as const,
text: responseText,
},
],
};
} catch (error) {
console.error("查詢任務時發生錯誤:", error);
return {
content: [
{
type: "text" as const,
text: `## 系統錯誤\n\n查詢任務時發生錯誤: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
isError: true,
};
}
}
// 格式化任務顯示內容的輔助函數
function formatTaskForDisplay(task: Task): string {
let taskInfo = `### ${task.name}\n**ID:** \`${task.id}\`\n**狀態:** ${task.status}\n**描述:** ${task.description}\n`;
if (task.notes) {
taskInfo += `**注記:** ${task.notes}\n`;
}
if (task.implementationGuide) {
taskInfo += `**實現指南:** ${
task.implementationGuide.length > 300
? task.implementationGuide.substring(0, 300) + "..."
: task.implementationGuide
}\n`;
}
if (task.verificationCriteria) {
taskInfo += `**驗證標準:** ${
task.verificationCriteria.length > 300
? task.verificationCriteria.substring(0, 300) + "..."
: task.verificationCriteria
}\n`;
}
if (task.summary) {
taskInfo += `**完成摘要:** ${task.summary}\n`;
}
taskInfo += `**創建時間:** ${new Date(task.createdAt).toLocaleString(
"zh-TW"
)}\n`;
taskInfo += `**更新時間:** ${new Date(task.updatedAt).toLocaleString(
"zh-TW"
)}\n`;
if (task.completedAt) {
taskInfo += `**完成時間:** ${new Date(task.completedAt).toLocaleString(
"zh-TW"
)}\n`;
}
taskInfo += `**詳細內容:** 請使用「get_task_detail」工具查看 ${task.id} 完整任務詳情`;
return taskInfo;
}
// 取得完整任務詳情的參數
export const getTaskDetailSchema = z.object({
taskId: z
.string()
.min(1, {
message: "任務ID不能為空請提供有效的任務ID",
})
.describe("欲檢視詳情的任務ID"),
});
// 取得任務完整詳情
export async function getTaskDetail({
taskId,
}: z.infer<typeof getTaskDetailSchema>) {
try {
// 檢查任務是否存在
const task = await getTaskById(taskId);
if (!task) {
return {
content: [
{
type: "text" as const,
text: `## 錯誤\n\n找不到ID為 \`${taskId}\` 的任務。請確認任務ID是否正確。`,
},
],
isError: true,
};
}
// 格式化完整的任務詳情,不截斷內容
const fullTaskDetail = formatFullTaskDetail(task);
return {
content: [
{
type: "text" as const,
text: `## 任務完整詳情\n\n${fullTaskDetail}`,
},
],
};
} catch (error) {
console.error("取得任務詳情時發生錯誤:", error);
return {
content: [
{
type: "text" as const,
text: `## 系統錯誤\n\n取得任務詳情時發生錯誤: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
isError: true,
};
}
}
// 格式化完整任務詳情的輔助函數,不截斷長內容
function formatFullTaskDetail(task: Task): string {
let taskDetail = `### ${task.name}\n\n**ID:** \`${task.id}\`\n\n**狀態:** ${task.status}\n\n**描述:**\n${task.description}\n\n`;
if (task.notes) {
taskDetail += `**注記:**\n${task.notes}\n\n`;
}
if (task.dependencies && task.dependencies.length > 0) {
taskDetail += `**依賴任務:** ${task.dependencies
.map((dep) => `\`${dep.taskId}\``)
.join(", ")}\n\n`;
}
if (task.implementationGuide) {
taskDetail += `**實現指南:**\n\`\`\`\n${task.implementationGuide}\n\`\`\`\n\n`;
}
if (task.verificationCriteria) {
taskDetail += `**驗證標準:**\n\`\`\`\n${task.verificationCriteria}\n\`\`\`\n\n`;
}
if (task.relatedFiles && task.relatedFiles.length > 0) {
taskDetail += `**相關文件:**\n`;
for (const file of task.relatedFiles) {
taskDetail += `- \`${file.path}\` (${file.type})${
file.description ? `: ${file.description}` : ""
}\n`;
}
taskDetail += `\n`;
}
taskDetail += `**創建時間:** ${new Date(task.createdAt).toLocaleString(
"zh-TW"
)}\n`;
taskDetail += `**更新時間:** ${new Date(task.updatedAt).toLocaleString(
"zh-TW"
)}\n`;
if (task.completedAt) {
taskDetail += `**完成時間:** ${new Date(task.completedAt).toLocaleString(
"zh-TW"
)}\n\n`;
}
if (task.summary) {
taskDetail += `**完成摘要:**\n${task.summary}\n\n`;
}
return taskDetail;
}