From 0e21fe5a40138ac0854a7d046714c883e8931eb3 Mon Sep 17 00:00:00 2001 From: Alex's Mac Date: Tue, 31 Mar 2026 11:02:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20v2=20=E2=80=94=20=E9=A3=9E=E4=B9=A6?= =?UTF-8?q?=E5=85=A8=E8=83=BD=E9=9B=86=E6=88=90=E5=A5=97=E4=BB=B6=20(CLI?= =?UTF-8?q?=20+=20MCP=20integration=20kit)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Transform feishu-mcp from MCP-only tool into a comprehensive integration kit combining Feishu CLI (200+ commands, 19 skills) with community MCP (15 doc editing tools) for non-technical users. New deliverables: - setup-v2.sh: smart setup script with CLI + MCP install, OpenClaw detection - SKILL.md: 544-line decision matrix (49 intents → tool routing) - AGENTS.md: 749-line master agent reference with decision tree - QUICKSTART-AGENT.md: 9-step automated setup guide for AI agents - TROUBLESHOOT-AGENT.md: 17 error entries with recovery procedures - GUIDE.md: step-by-step visual setup guide for non-technical users - 3 platform config templates (OpenClaw, Claude Code, Cursor) - 5 workflow skills demonstrating CLI + MCP synergy Architecture: two-layer (CLI for breadth, community MCP for depth). Co-Authored-By: Claude Opus 4.6 (1M context) --- AGENTS.md | 749 +++++++++++++++++++++++ CLAUDE.md | 193 ++++++ GUIDE.md | 392 ++++++++++++ QUICKSTART-AGENT.md | 308 ++++++++++ README.md | 371 ++++++------ SKILL.md | 565 ++++++++++++++++-- TROUBLESHOOT-AGENT.md | 452 ++++++++++++++ configs/claude-code.json | 18 + configs/cursor.json | 18 + configs/openclaw.json | 18 + setup-v2.sh | 1022 ++++++++++++++++++++++++++++++++ skills/data-to-doc.md | 191 ++++++ skills/doc-review.md | 164 +++++ skills/feishu-overview.md | 135 +++++ skills/knowledge-sync.md | 186 ++++++ skills/meeting-summary-plus.md | 186 ++++++ 16 files changed, 4726 insertions(+), 242 deletions(-) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 GUIDE.md create mode 100644 QUICKSTART-AGENT.md create mode 100644 TROUBLESHOOT-AGENT.md create mode 100644 configs/claude-code.json create mode 100644 configs/cursor.json create mode 100644 configs/openclaw.json create mode 100755 setup-v2.sh create mode 100644 skills/data-to-doc.md create mode 100644 skills/doc-review.md create mode 100644 skills/feishu-overview.md create mode 100644 skills/knowledge-sync.md create mode 100644 skills/meeting-summary-plus.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..bbcfd78 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,749 @@ +# AGENTS.md — Feishu Integration Master Agent Reference + +**Audience**: AI agents (Claude Code, OpenClaw, Cursor, etc.) +**Purpose**: Complete reference for all Feishu operations — tool inventory, decision tree, auth verification, command examples. +**Quick reference**: Consult SKILL.md for routing decisions. This file is the full manual. + +All instructions in this file are imperative. Execute them literally. + +--- + +## Architecture Overview + +The Feishu integration uses a two-layer architecture: + +``` +User <-> AI Agent <-> feishu-mcp Integration Layer + | + +---------+---------+ + | | + Feishu CLI Community MCP + (@larksuite/cli) (feishu-mcp) + 200+ commands 15 doc editing tools + 19 AI skills Block-level precision + 11 business domains + OAuth port: 3000 OAuth port: 3333 +``` + +- **Feishu CLI** (`@larksuite/cli`): Breadth layer. 19 AI skills covering 11 business domains with 200+ commands. Auth stored in OS keychain. OAuth callback on port 3000. Shortcut syntax uses `+` prefix (e.g., `+agenda`, `+send`, `+create`). +- **Community MCP** (`feishu-mcp`): Depth layer. 15 document editing tools with block-level precision, batch operations, and formatting control (8-color palette, alignment). Auth via env vars (`FEISHU_APP_ID`, `FEISHU_APP_SECRET`). OAuth callback on port 3333. +- **Official MCP** (`@larksuiteoapi/lark-mcp`): Optional. Advanced bitable, doc search, and wiki tools. Not installed by default. + +Key principle: Use CLI for breadth (anything beyond documents). Use MCP for depth (precise block manipulation, formatting, batch operations). + +--- + +## Complete Tool Inventory + +### CLI Skills (19 total, 11 business domains) + +#### lark-shared — 认证与身份 +应用配置初始化、认证登录、身份切换、权限管理。 +```bash +lark-cli auth status # Check current auth state +lark-cli auth login --recommend # OAuth browser login +lark-cli config init --new # Initialize app configuration +``` + +#### lark-calendar — 日历 +日历与日程管理:查看/搜索日程、创建/更新日程、管理参会人、查询忙闲状态。 +```bash +lark-cli calendar +agenda # View today's schedule +lark-cli calendar +create # Create calendar event +lark-cli calendar +freebusy # Check free/busy status +lark-cli calendar +suggestion # Get meeting time suggestions +``` + +#### lark-im — 即时通讯 +收发消息、搜索聊天记录、管理群聊。 +```bash +lark-cli im +send # Send message +lark-cli im +search # Search chat history +``` + +#### lark-doc — 文档 +从 Markdown 创建文档、获取内容、更新、搜索。 +```bash +lark-cli doc +create # Create document from Markdown +lark-cli doc +search # Search documents in cloud space +lark-cli docs +update # Update document (append/overwrite/replace/insert/delete) +lark-cli docs +media-insert # Insert image/file into document +``` + +#### lark-drive — 云空间 +上传/下载文件、管理文件夹、管理权限和评论。 +```bash +lark-cli drive upload # Upload file to cloud space +lark-cli drive download # Download file from cloud space +``` + +#### lark-sheets — 电子表格 +创建、读写、搜索、导出电子表格。 +```bash +lark-cli sheets +create # Create spreadsheet with headers +lark-cli sheets +write # Write cell data +lark-cli sheets +read # Read cell range +``` + +#### lark-base — 多维表格 +表、字段、记录、视图、仪表盘管理。 +```bash +lark-cli base +query # Query records (filter/sort) +lark-cli base +create # Create bitable +``` + +#### lark-task — 任务 +创建/更新任务、子任务、清单、分配成员。 +```bash +lark-cli task +create # Create task +lark-cli task +get-my-tasks # Get my task list +``` + +#### lark-mail — 邮件 +起草、发送、回复、转发、搜索邮件。 +```bash +lark-cli mail +compose # Compose and send email +lark-cli mail +inbox # View inbox +lark-cli mail +search # Search emails +``` + +#### lark-contact — 通讯录 +查询组织架构、搜索员工信息。 +```bash +lark-cli contact +search # Search contacts (name/email/phone) +``` + +#### lark-wiki — 知识库 +管理知识空间、文档节点、层级结构。 +```bash +lark-cli wiki +list # List knowledge spaces +lark-cli wiki +create # Create wiki document +``` + +#### lark-event — 事件订阅 +WebSocket 实时监听飞书事件。 +```bash +lark-cli event # Subscribe to events (NDJSON output) +``` + +#### lark-vc — 视频会议 +查询会议记录、获取会议纪要。 +```bash +lark-cli vc # Query meeting records +``` + +#### lark-minutes — 妙记 +获取妙记基础信息和 AI 产物。 +```bash +lark-cli minutes # Get minutes info (summary, todos, chapters) +``` + +#### lark-whiteboard — 画板 +Mermaid 图表、流程图、架构图、思维导图。 +```bash +lark-cli whiteboard +create # Create new whiteboard +lark-cli docs +whiteboard-update # Edit whiteboard content +``` + +#### lark-openapi-explorer — API 探索 +从官方文档库挖掘未封装的原生 OpenAPI 接口。 +```bash +lark-cli openapi-explorer # Explore unwrapped OpenAPI endpoints +``` + +#### lark-skill-maker — 技能创建 +创建自定义 lark-cli Skill。 +```bash +lark-cli skill-maker # Create custom CLI skill +``` + +#### lark-workflow-meeting-summary — 会议纪要工作流 +汇总会议纪要并生成结构化报告。 +```bash +lark-cli workflow-meeting-summary # Aggregate meeting minutes into report +``` + +#### lark-workflow-standup-report — 站会报告工作流 +生成日程 + 未完成任务摘要。 +```bash +lark-cli workflow-standup-report # Generate schedule + task summary +``` + +--- + +### Community MCP Tools (17 total) + +Each tool is invoked via direct tool call or mcporter: + +#### create_feishu_document +Create a document in a folder. +- Parameters: `title` (string, required), `folderToken` (string, optional) +```bash +mcporter call feishu.create_feishu_document --args '{"title":"新文档"}' +``` + +#### get_feishu_document_info +Get document metadata (title, revision, create/update time). +- Parameters: `document_id` (string, required) +```bash +mcporter call feishu.get_feishu_document_info --args '{"document_id":"doxcnXXX"}' +``` + +#### get_feishu_document_blocks +Get the block structure tree of a document. +- Parameters: `document_id` (string, required) +```bash +mcporter call feishu.get_feishu_document_blocks --args '{"document_id":"doxcnXXX"}' +``` + +#### get_feishu_document_text +Extract plain text from a document. +- Parameters: `document_id` (string, required) +```bash +mcporter call feishu.get_feishu_document_text --args '{"document_id":"doxcnXXX"}' +``` + +#### batch_create_feishu_blocks +Batch create blocks (text, code, heading, list) atomically. +- Parameters: `document_id` (string, required), `blocks` (array, required) +```bash +mcporter call feishu.batch_create_feishu_blocks --args '{"document_id":"doxcnXXX","blocks":[{"type":"heading2","content":"标题"},{"type":"text","content":"正文"}]}' +``` + +#### update_feishu_block_text +Update text/code/heading block with formatting (8 colors, alignment). +- Parameters: `document_id` (string, required), `block_id` (string, required), `content` (string, required), `text_color` (string, optional), `align` (string, optional) +```bash +mcporter call feishu.update_feishu_block_text --args '{"document_id":"doxcnXXX","block_id":"blkXXX","content":"更新内容","text_color":"red"}' +``` + +#### delete_feishu_document_blocks +Delete blocks by block_id. +- Parameters: `document_id` (string, required), `block_ids` (array, required) +```bash +mcporter call feishu.delete_feishu_document_blocks --args '{"document_id":"doxcnXXX","block_ids":["blkXXX"]}' +``` + +#### upload_and_bind_image_to_block +Upload an image and bind it to a block in one step. +- Parameters: `document_id` (string, required), `image_path` or `image_url` (string, required) +```bash +mcporter call feishu.upload_and_bind_image_to_block --args '{"document_id":"doxcnXXX","image_url":"https://example.com/img.png"}' +``` + +#### create_feishu_table +Create a table in a document. +- Parameters: `document_id` (string, required), `rows` (number, required), `cols` (number, required) +```bash +mcporter call feishu.create_feishu_table --args '{"document_id":"doxcnXXX","rows":3,"cols":3}' +``` + +#### create_feishu_folder +Create a folder in cloud space. +- Parameters: `name` (string, required), `folderToken` (string, optional) +```bash +mcporter call feishu.create_feishu_folder --args '{"name":"项目文档"}' +``` + +#### list_feishu_folder_contents +List contents of a folder. +- Parameters: `folderToken` (string, required) +```bash +mcporter call feishu.list_feishu_folder_contents --args '{"folderToken":"fldcnXXX"}' +``` + +#### get_feishu_folder_files +Get file listing from a folder. +- Parameters: `folderToken` (string, required) +```bash +mcporter call feishu.get_feishu_folder_files --args '{"folderToken":"fldcnXXX"}' +``` + +#### search_feishu_documents +Search documents by keyword. +- Parameters: `query` (string, required), `count` (number, optional) +```bash +mcporter call feishu.search_feishu_documents --args '{"query":"会议记录","count":10}' +``` + +#### get_feishu_wiki_node_info +Get wiki node metadata. +- Parameters: `token` (string, required) +```bash +mcporter call feishu.get_feishu_wiki_node_info --args '{"token":"wikcnXXX"}' +``` + +#### get_feishu_whiteboard_content +Read whiteboard content (read-only). +- Parameters: `whiteboard_id` (string, required) +```bash +mcporter call feishu.get_feishu_whiteboard_content --args '{"whiteboard_id":"wbXXX"}' +``` + +--- + +### Official MCP Tools (Optional) + +If `@larksuiteoapi/lark-mcp` is installed, these additional tools become available. This layer is optional and not part of the default installation. + +| Tool | Description | Example | +|---|---|---| +| `bitable_v1_app_create` | Create bitable app | `mcporter call lark.bitable_v1_app_create --args '{"data":{"name":"表"}}'` | +| `bitable_v1_appTableRecord_create` | Create bitable record | `mcporter call lark.bitable_v1_appTableRecord_create --args '...'` | +| `bitable_v1_appTableRecord_search` | Search bitable records | `mcporter call lark.bitable_v1_appTableRecord_search --args '...'` | +| `docx_builtin_search` | Search cloud documents | `mcporter call lark-user.docx_builtin_search --args '{"data":{"search_key":"..."}}'` | +| `docx_v1_document_rawContent` | Get document raw text | `mcporter call lark-user.docx_v1_document_rawContent --args '...'` | +| `wiki_v1_node_search` | Search wiki nodes | `mcporter call lark-user.wiki_v1_node_search --args '...'` | +| `wiki_v2_space_getNode` | Get wiki space node | `mcporter call lark-user.wiki_v2_space_getNode --args '...'` | + +--- + +## Decision Tree + +Follow this tree step-by-step. At each numbered item, evaluate the condition and follow the matching branch. Every path ends at a specific tool/command. + +1. **User wants to send or read messages** + 1. Send message → `lark-cli im +send` + 2. Search chat history → `lark-cli im +search` + +2. **User wants to create a document** + 1. Has Markdown content or simple creation → `lark-cli doc +create` + 2. Needs to specify target folder by token → `create_feishu_document` + 3. Needs batch formatted blocks immediately after creation → `lark-cli doc +create` then `batch_create_feishu_blocks` + +3. **User wants to edit an existing document** + 1. Simple append/overwrite/replace → `lark-cli docs +update` + 2. Needs specific block color or alignment → `update_feishu_block_text` + 3. Needs batch creation of multiple formatted blocks → `batch_create_feishu_blocks` + 4. Needs to delete specific blocks by ID → `delete_feishu_document_blocks` + 5. Needs to insert image → `lark-cli docs +media-insert` + 6. Needs to insert table → `create_feishu_table` + +4. **User wants to search for something** + 1. Search cloud documents → `lark-cli doc +search` + 2. Search chat messages → `lark-cli im +search` + 3. Search emails → `lark-cli mail +search` + 4. Search contacts → `lark-cli contact +search` + +5. **User wants calendar/scheduling operations** + 1. View schedule → `lark-cli calendar +agenda` + 2. Create event → `lark-cli calendar +create` + 3. Check free/busy → `lark-cli calendar +freebusy` + 4. Get time suggestions → `lark-cli calendar +suggestion` + +6. **User wants to manage tasks** + 1. Create task → `lark-cli task +create` + 2. View my tasks → `lark-cli task +get-my-tasks` + +7. **User wants to send email** + 1. Compose/send → `lark-cli mail +compose` + 2. View inbox → `lark-cli mail +inbox` + 3. Search → `lark-cli mail +search` + +8. **User wants to work with spreadsheets** + 1. Create spreadsheet → `lark-cli sheets +create` + 2. Write data → `lark-cli sheets +write` + 3. Read data → `lark-cli sheets +read` + +9. **User wants to work with bitable (multi-dimensional tables)** + 1. Query records → `lark-cli base +query` + 2. Create bitable → `lark-cli base +create` + +10. **User wants meeting/minutes information** + 1. Query past meeting records → `lark-cli vc` + 2. Get meeting minutes/AI summary → `lark-cli minutes` + 3. Query future meetings (schedule) → `lark-cli calendar +agenda` + 4. Generate meeting summary report → `lark-cli workflow-meeting-summary` + +11. **User wants to manage wiki/knowledge base** + 1. List knowledge spaces → `lark-cli wiki +list` + 2. Create wiki document → `lark-cli wiki +create` + 3. Get wiki node metadata → `get_feishu_wiki_node_info` + +12. **User wants to create diagrams/charts** + 1. Mermaid flowchart/sequence/mindmap → `lark-cli docs +whiteboard-update` + 2. Create new whiteboard → `lark-cli whiteboard +create` + 3. Read whiteboard content → `get_feishu_whiteboard_content` + +13. **User wants file/folder operations** + 1. Upload file → `lark-cli drive upload` + 2. Download file → `lark-cli drive download` + 3. Create folder → `create_feishu_folder` + 4. List folder contents → `list_feishu_folder_contents` + +14. **User wants contact/people information** + 1. Search by name/email/phone → `lark-cli contact +search` + +15. **User wants to subscribe to events** + 1. Real-time event monitoring → `lark-cli event` + +**Fallback**: If CLI returns "skill not found", run `npx skills add larksuite/cli -y -g` and retry the command. + +--- + +## Auth Verification Procedures + +### Procedure 1: CLI Auth Check + +1. Run `lark-cli auth status`. +2. If output shows a valid App ID, user identity, and unexpired token → auth is valid. Proceed. +3. If output shows "Not logged in" or "Token expired" → run `lark-cli auth login --recommend`. +4. If `lark-cli` is not found → run `npm install -g @larksuite/cli` then `npx skills add larksuite/cli -y -g`. + +### Procedure 2: MCP Auth Check + +1. Check that `FEISHU_APP_ID` env var is set and starts with `cli_`. +2. Check that `FEISHU_APP_SECRET` env var is set and is non-empty. +3. If either is missing → ask the user for their Feishu App ID and App Secret. +4. Test with a minimal MCP call: `mcporter call feishu.get_feishu_document_info --args '{"document_id":"test"}'`. If the error is about document_id (not auth), auth is working. +5. If the error mentions "unauthorized" or "invalid token" → verify env vars and restart mcporter. + +### Procedure 3: Token Refresh + +1. **CLI token refresh**: Run `lark-cli auth login --recommend`. The browser opens for OAuth. Wait for user to approve. +2. **MCP token refresh**: If using user auth mode, the user must re-authorize. Run the community MCP startup command to trigger OAuth on port 3333. If using tenant mode, tokens are auto-refreshed via App ID + App Secret. +3. **Verify after refresh**: Run `lark-cli auth status` for CLI. Run a test MCP call for MCP. + +--- + +## Extracting IDs from Feishu URLs + +When a user provides a Feishu URL instead of a token/ID, extract the ID using these patterns: + +| URL Format | ID Type | Regex | +|---|---|---| +| `https://*.feishu.cn/docx/{id}` | document_id | `/docx/([A-Za-z0-9]+)` | +| `https://*.feishu.cn/wiki/{token}` | wiki_token | `/wiki/([A-Za-z0-9]+)` | +| `https://*.feishu.cn/sheets/{token}` | spreadsheet_token | `/sheets/([A-Za-z0-9]+)` | +| `https://*.feishu.cn/base/{token}` | bitable app_token | `/base/([A-Za-z0-9]+)` | +| `https://*.feishu.cn/drive/folder/{token}` | folder_token | `/folder/([A-Za-z0-9]+)` | +| `https://*.feishu.cn/minutes/{token}` | minute_token | `/minutes/([A-Za-z0-9]+)` | + +Example: From `https://abc.feishu.cn/docx/doxcn1234567890`, extract `doxcn1234567890` as the document_id. + +--- + +## Command Examples (30+) + +### Calendar Domain + +**1.** "查看今天的日程" (View today's schedule) +```bash +lark-cli calendar +agenda +``` +Expected output: List of today's events with time, title, and attendees. + +**2.** "帮我创建一个明天下午 2 点的会议" (Create a meeting tomorrow at 2 PM) +```bash +lark-cli calendar +create +``` +Expected output: Event created confirmation with event link. + +**3.** "查一下张三这周的忙闲" (Check Zhang San's availability this week) +```bash +lark-cli calendar +freebusy +``` +Expected output: Free/busy time blocks for the specified user. + +**4.** "推荐一个三人都有空的时间" (Suggest a time when all three are free) +```bash +lark-cli calendar +suggestion +``` +Expected output: Multiple time slot suggestions with availability info. + +### Messaging Domain + +**5.** "给张三发消息说明天开会" (Send Zhang San a message about tomorrow's meeting) +```bash +lark-cli im +send +``` +Expected output: Message sent confirmation with message_id. + +**6.** "搜索关于项目上线的聊天记录" (Search chat history about project launch) +```bash +lark-cli im +search +``` +Expected output: List of matching messages with sender, time, and content preview. + +### Documents Domain + +**7.** "创建一个项目周报文档" (Create a weekly report document) +```bash +lark-cli doc +create +``` +Expected output: Document created with URL. + +**8.** "搜索上周的会议纪要" (Search for last week's meeting notes) +```bash +lark-cli doc +search +``` +Expected output: List of matching documents with titles and URLs. + +**9.** "在文档末尾追加一段总结" (Append a summary to the document) +```bash +lark-cli docs +update +``` +Expected output: Document updated confirmation. + +**10.** "在文档里插入一张截图" (Insert a screenshot into the document) +```bash +lark-cli docs +media-insert +``` +Expected output: Image inserted confirmation with image key. + +**11.** "获取文档的 Block 结构" (Get block structure of a document) +```bash +mcporter call feishu.get_feishu_document_blocks --args '{"document_id":"doxcnXXX"}' +``` +Expected output: JSON array of blocks with type, content, and block_id. + +**12.** "提取文档的纯文本" (Extract plain text from a document) +```bash +mcporter call feishu.get_feishu_document_text --args '{"document_id":"doxcnXXX"}' +``` +Expected output: Plain text string of the document content. + +**13.** "一次性添加三个标题段落" (Batch add three heading paragraphs) +```bash +mcporter call feishu.batch_create_feishu_blocks --args '{"document_id":"doxcnXXX","blocks":[{"type":"heading2","content":"第一章"},{"type":"heading2","content":"第二章"},{"type":"heading2","content":"第三章"}]}' +``` +Expected output: Array of created block_ids. + +**14.** "把标题改成红色" (Change heading color to red) +```bash +mcporter call feishu.update_feishu_block_text --args '{"document_id":"doxcnXXX","block_id":"blkXXX","content":"标题","text_color":"red"}' +``` +Expected output: Block updated confirmation. + +**15.** "删除文档中的第三个 Block" (Delete the third block) +```bash +mcporter call feishu.delete_feishu_document_blocks --args '{"document_id":"doxcnXXX","block_ids":["blk3XXX"]}' +``` +Expected output: Deletion confirmation. + +**16.** "上传图片到文档" (Upload image to document) +```bash +mcporter call feishu.upload_and_bind_image_to_block --args '{"document_id":"doxcnXXX","image_url":"https://example.com/img.png"}' +``` +Expected output: Image uploaded and bound, returns block_id. + +**17.** "在文档中创建一个 3x4 表格" (Create a 3x4 table in the document) +```bash +mcporter call feishu.create_feishu_table --args '{"document_id":"doxcnXXX","rows":3,"cols":4}' +``` +Expected output: Table created, returns table block_id. + +### Cloud Storage Domain + +**18.** "上传这个 PDF" (Upload this PDF) +```bash +lark-cli drive upload +``` +Expected output: Upload confirmation with file token. + +**19.** "下载这个文件" (Download this file) +```bash +lark-cli drive download +``` +Expected output: File downloaded to local path. + +**20.** "创建一个叫项目资料的文件夹" (Create a folder called Project Materials) +```bash +mcporter call feishu.create_feishu_folder --args '{"name":"项目资料"}' +``` +Expected output: Folder created with folder_token. + +**21.** "列出项目文档文件夹的内容" (List contents of the project documents folder) +```bash +mcporter call feishu.list_feishu_folder_contents --args '{"folderToken":"fldcnXXX"}' +``` +Expected output: Array of files/folders with names, types, and tokens. + +### Spreadsheets Domain + +**22.** "创建一个销售数据表" (Create a sales data spreadsheet) +```bash +lark-cli sheets +create +``` +Expected output: Spreadsheet created with URL and token. + +**23.** "把数据写入 A1:C5" (Write data to A1:C5) +```bash +lark-cli sheets +write +``` +Expected output: Cells updated confirmation. + +**24.** "读取 A1:D10 的数据" (Read data from A1:D10) +```bash +lark-cli sheets +read +``` +Expected output: Cell values in tabular format. + +### Bitable Domain + +**25.** "查询项目表中本周的记录" (Query this week's records from the project table) +```bash +lark-cli base +query +``` +Expected output: Records matching the filter with field values. + +**26.** "新建一个 Bug 跟踪表" (Create a new bug tracking table) +```bash +lark-cli base +create +``` +Expected output: Bitable created with app_token and URL. + +### Tasks Domain + +**27.** "创建一个任务:下周五前完成设计评审" (Create a task: complete design review by next Friday) +```bash +lark-cli task +create +``` +Expected output: Task created with task_id and link. + +**28.** "看看我的待办任务" (View my pending tasks) +```bash +lark-cli task +get-my-tasks +``` +Expected output: List of tasks with status, due date, and assignee. + +### Email Domain + +**29.** "给团队发一封项目进度邮件" (Send a project progress email to the team) +```bash +lark-cli mail +compose +``` +Expected output: Email sent confirmation with message_id. + +**30.** "搜索关于合同的邮件" (Search for emails about contracts) +```bash +lark-cli mail +search +``` +Expected output: List of matching emails with subject, sender, and date. + +### Wiki Domain + +**31.** "列出所有知识空间" (List all knowledge spaces) +```bash +lark-cli wiki +list +``` +Expected output: List of wiki spaces with names and tokens. + +**32.** "获取这个 Wiki 节点的信息" (Get wiki node information) +```bash +mcporter call feishu.get_feishu_wiki_node_info --args '{"token":"wikcnXXX"}' +``` +Expected output: Node metadata including title, type, parent. + +### Whiteboard Domain + +**33.** "创建一个新画板" (Create a new whiteboard) +```bash +lark-cli whiteboard +create +``` +Expected output: Whiteboard created with URL. + +**34.** "在画板上画一个流程图" (Draw a flowchart on the whiteboard) +```bash +lark-cli docs +whiteboard-update +``` +Expected output: Whiteboard updated with Mermaid diagram. + +**35.** "获取画板内容" (Get whiteboard content) +```bash +mcporter call feishu.get_feishu_whiteboard_content --args '{"whiteboard_id":"wbXXX"}' +``` +Expected output: JSON structure of whiteboard elements. + +### Contacts Domain + +**36.** "搜索张三的联系方式" (Search for Zhang San's contact info) +```bash +lark-cli contact +search +``` +Expected output: User profile with name, email, phone, department. + +### Meetings Domain + +**37.** "看看昨天有哪些会议记录" (View yesterday's meeting records) +```bash +lark-cli vc +``` +Expected output: List of meeting records with title, time, organizer. + +### Search Domain (cross-domain) + +**38.** "搜索关于 Q1 的文档" (Search for documents about Q1) +```bash +lark-cli doc +search +``` +Expected output: List of documents matching the query. + +**39.** "搜索文档(通过 MCP)" (Search documents via MCP) +```bash +mcporter call feishu.search_feishu_documents --args '{"query":"Q1","count":10}' +``` +Expected output: Array of matching documents with title and token. + +--- + +## Operating in MCP-Only Mode + +If CLI is not installed (setup ran with `--mcp-only`), only the following capabilities are available: + +**Available (via Community MCP):** +- Document creation, editing, reading, and block manipulation +- Folder creation and listing +- Document search +- Wiki node metadata queries +- Whiteboard content reading (read-only) + +**Not available (CLI required):** +- Messaging (im) +- Calendar +- Email +- Tasks +- Contacts +- Meetings / Minutes +- Spreadsheets +- Bitable +- Event subscriptions +- Whiteboard creation and editing +- Mermaid diagrams / advanced charts +- File upload / download + +If a user requests an unavailable capability in MCP-only mode, inform them: "此功能需要飞书 CLI。运行 `npm install -g @larksuite/cli && npx skills add larksuite/cli -y -g` 安装 CLI。" + +--- + +## Permissions Quick Reference + +| Domain | Required Scope | +|---|---| +| Documents | `docx:document` | +| Cloud Storage | `drive:drive` | +| Wiki | `wiki:wiki` | +| Bitable | `bitable:app` | +| Messaging | `im:message` | +| Search | `search:docs:read` | +| Calendar | `calendar:calendar` | +| Email | `mail:message` | +| Contacts | `contact:user.base:readonly` | +| Meetings | `vc:meeting:readonly` | +| Minutes | `minutes:minute:readonly` | +| Tasks | `task:task` | + +Manage permissions at: `https://open.feishu.cn/app/{APP_ID}/security` + +--- + +## Error Handling Quick Reference + +If any command fails, consult TROUBLESHOOT-AGENT.md for diagnosis and recovery steps. + +Common quick fixes: +- "command not found: lark-cli" → `npm install -g @larksuite/cli` +- "skill not found" → `npx skills add larksuite/cli -y -g` +- "Token expired" → `lark-cli auth login --recommend` +- "Permission denied" → Add missing scope at `https://open.feishu.cn/app/{APP_ID}/security` +- "FEISHU_APP_ID not set" → Set env vars and restart mcporter diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..bf0ab32 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,193 @@ +# Feishu-MCP v2 — 飞书全能集成套件 + +## What This Project Is + +**feishu-mcp 是飞书全能集成套件(Meta-Skill Package)**— 让飞书 CLI 和社区 MCP 作为一个统一系统工作的集成层。 + +它不是 MCP 服务器,不是 CLI 替代品,不是运行时组件。它是: +1. **一条命令安装脚本** — 安装 + 配置 CLI + 社区 MCP + OpenClaw 检测 +2. **决策矩阵 Skill** (`SKILL.md`) — 告诉 AI agent 每个任务该用哪个工具 +3. **Agent 文档** — 让 AI 助手自助完成安装、诊断、错误恢复 +4. **用户引导文档** — 零技术背景用户的中文指南 +5. **平台配置模板** — OpenClaw / Claude Code / Cursor 预配置 +6. **工作流 Skill** — 展示 CLI + MCP 协同能力 + 中文友好化包装 + +## Harness Methodology + +This project uses a **Planner → Builder → QA** harness for ALL development (full process). + +### Agent Roles +- **@planner**: Expands goals into specs with acceptance criteria. Writes WHAT, never HOW. +- **@builder**: Implements features according to specs. Follows existing patterns. +- **@qa**: Independently verifies output. Scores 5 dimensions, any < 6 = FAIL. +- **@coordinator**: Routes requests to the right agent based on change size. + +### Communication +Agents communicate through files in `.harness/`: +- `spec.md` — Overall transformation plan (ground truth) +- `contracts/{unit}.md` — Per-unit specs (Planner output) +- `reports/build_{unit}_r{N}.md` — Builder reports +- `reports/qa_{unit}_r{N}.md` — QA reports +- `progress.tsv` — Iteration history +- `experience/` — Accumulated patterns and lessons + +### Workflow +``` +Plan → Build → QA ─── PASS → git commit → next unit + └─ FAIL → same failure? + ├─ NO → fix → re-verify + └─ YES → replan +``` + +## Architecture: Two-Layer (CLI + Community MCP) + +``` +User <-> OpenClaw/Claude Code/Cursor <-> feishu-mcp 集成层 + | + +---------+---------+ + | | + Feishu CLI Community MCP + (@larksuite/cli) (feishu-mcp) + 200+ commands 15 doc editing tools + 19 AI skills Block-level precision + 11 business domains +``` + +**Key Principle: CLI for breadth, Community MCP for depth.** + +### Why Two Layers (Not Three) + +CLI 已覆盖官方 MCP 的大部分能力。官方 MCP(Beta)作为高级可选项,不在默认安装中。 + +### CLI vs Community MCP: Complementary Capabilities + +| Capability | Feishu CLI | Community MCP | Who Wins | +|-----------|-----------|---------------|----------| +| Batch block creation | ⚠️ Partial (Markdown) | ✅ `batch_create` | **MCP unique advantage** | +| Text formatting (color/align) | ✅ (Markdown syntax) | ✅ (8-color, alignment) | **MCP more precise** | +| Mermaid diagrams | ✅ (whiteboard skill) | ❌ (planned) | **CLI unique advantage** | +| Advanced charts/DSL | ✅ (DSL path) | ❌ (planned) | **CLI unique advantage** | +| Whiteboard editing | ✅ (create+edit) | ⚠️ (read-only) | **CLI unique advantage** | +| Image upload | ✅ | ✅ | CLI more robust | +| Block editing | ✅ (selection) | ✅ (direct API) | MCP more granular | +| Block deletion | ✅ | ✅ | Equal | +| Messaging/Calendar/Mail/Tasks/Contacts/Meetings/Wiki/Sheets/Base | ✅ | ❌ | **CLI only** | + +### Decision Matrix: CLI vs MCP + +| Task | Use | Reason | +|------|-----|--------| +| Send message | CLI (`lark-cli im +send`) | Full control, attachments | +| Calendar ops | CLI (`lark-cli calendar +agenda`) | Complete API coverage | +| Create document | CLI (`lark-cli doc +create`) | Markdown input, simpler | +| Edit doc blocks precisely | Community MCP (`update_feishu_block_text`) | Granular block control | +| Batch create blocks | Community MCP (`batch_create_feishu_blocks`) | Atomic batch operation | +| Text color/alignment | Community MCP (style properties) | 8-color palette, explicit align | +| Insert Mermaid diagram | CLI (`lark-cli whiteboard`) | Community MCP doesn't support yet | +| Insert charts | CLI (whiteboard DSL) | Community MCP doesn't support yet | +| Whiteboard create/edit | CLI (`lark-cli docs +whiteboard-update`) | MCP is read-only | +| Upload image to doc | CLI (`lark-cli docs +media-insert`) or MCP | Both work, CLI more robust | +| Query bitable | CLI (`lark-cli base +query`) | CLI simpler | +| Search docs | CLI (`lark-cli doc +search`) | Official, more reliable | +| Send mail | CLI (`lark-cli mail +compose`) | Only option | +| Manage tasks | CLI (`lark-cli task +list`) | Only option | +| Wiki operations | CLI (`lark-cli wiki`) | Only option | +| Contacts | CLI (`lark-cli contact`) | Only option | +| Meetings/Minutes | CLI (`lark-cli vc`, `lark-cli minutes`) | Only option | + +## Conventions + +### Languages +- **User-facing content**: Chinese (primary), English section headers +- **Agent-facing docs**: English (primary), Chinese examples where helpful +- **Code comments**: English +- **Commit messages**: English + +### File Structure +``` +feishu-mcp/ + setup.sh ← Legacy setup (v1, kept for compatibility) + setup-v2.sh ← New smart setup script + README.md ← User-facing intro + quick start + GUIDE.md ← Step-by-step visual guide for non-technical users + SKILL.md ← Decision matrix (CLI + MCP routing) + AGENTS.md ← Master reference for AI agents + QUICKSTART-AGENT.md ← Agent setup automation guide + TROUBLESHOOT-AGENT.md ← Agent error recovery guide + CLAUDE.md ← This file (project context + harness rules) + configs/ + openclaw.json ← OpenClaw config template + claude-code.json ← Claude Code config template + cursor.json ← Cursor config template + skills/ + feishu-overview.md ← Overview: Chinese index of all 19 CLI skills + MCP tools + doc-review.md ← Workflow: read blocks (MCP) → create tasks (CLI) → send summary (CLI) + data-to-doc.md ← Workflow: query bitable (CLI) → generate formatted doc (MCP) + knowledge-sync.md ← Workflow: read Wiki (CLI) → update doc content (MCP) + meeting-summary-plus.md ← Enhanced: CLI built-in + MCP formatted doc output + .claude/ + agents/ + planner.md + builder.md + qa.md + coordinator.md + settings.json + .harness/ + spec.md + progress.tsv + contracts/ + reports/ + experience/ +``` + +### Naming +- Shell scripts: `kebab-case.sh` +- Top-level docs: `UPPER-CASE.md` +- Subdirectory docs: `kebab-case.md` +- Config files: `{tool-name}.json` + +### Shell Script Standards +- Shebang: `#!/usr/bin/env bash` +- `set -euo pipefail` at top +- All user prompts in Chinese +- Error messages suggest fix action +- No `sudo` required +- No hardcoded paths (use `$HOME`, `$XDG_CONFIG_HOME`) +- Idempotent (safe to re-run) + +### Documentation Standards +- Agent docs: imperative voice ("Do X", "Check Y", "If Z then W") +- User docs: conversational, zero jargon, step-by-step +- Every doc has a clear audience header +- No placeholder values in published docs — use descriptive comments + +## Quality Dimensions + +QA scores 5 dimensions (1-10 each). Any < 6 = FAIL: +1. **User Experience** (30%) — minimal steps, no config editing, clear errors +2. **Agent Operability** (25%) — unambiguous tool selection, automated recovery +3. **Completeness** (20%) — all Feishu capabilities accessible +4. **Error Handling** (15%) — common errors have recovery paths +5. **Documentation Clarity** (10%) — non-technical user can follow + +## Key Dependencies + +### Required (default install) +- Node.js >= 16 +- npm +- `@larksuite/cli` >= 1.0.0 (official Feishu CLI) +- `feishu-mcp` (community MCP for document editing) +- `mcporter` (MCP port multiplexer) +- Feishu Open Platform app (user creates at open.feishu.cn) + +### Optional +- `@larksuiteoapi/lark-mcp` (official MCP, advanced users only) +- `@larksuiteoapi/feishu-openclaw-plugin` (OpenClaw channel plugin) + +## Auth Flow Summary + +1. User creates app at open.feishu.cn → gets App ID + App Secret +2. Setup script configures redirect URL (http://localhost:3000/callback for CLI, http://localhost:3333/callback for community MCP) +3. `lark-cli auth login --recommend` opens browser for OAuth +4. User approves permissions → token stored in OS keychain (CLI) and env vars (MCP) +5. Token refresh: CLI handles automatically, community MCP may need manual refresh diff --git a/GUIDE.md b/GUIDE.md new file mode 100644 index 0000000..87c0135 --- /dev/null +++ b/GUIDE.md @@ -0,0 +1,392 @@ +# 从零开始配置飞书 AI 助手 + +本指南面向**从未使用过飞书开放平台**的用户。按照以下步骤操作,你就能让 AI 助手完整控制你的飞书。 + +全程大约需要 10-15 分钟。 + +--- + +## 目录 + +- [第一步:创建飞书应用](#第一步创建飞书应用) +- [第二步:配置应用权限](#第二步配置应用权限) +- [第三步:配置安全设置](#第三步配置安全设置) +- [第四步:发布应用](#第四步发布应用) +- [第五步:运行安装脚本](#第五步运行安装脚本) +- [第六步:验证安装](#第六步验证安装) +- [第七步:第一次对话 — 试试这些例子](#第七步第一次对话--试试这些例子) +- [常见问题](#常见问题) + +--- + +## 第一步:创建飞书应用 + +你需要在飞书开放平台创建一个「自建应用」。这个应用相当于 AI 助手操作飞书时使用的「身份证」。 + +### 1.1 打开飞书开放平台 + +在浏览器中访问:**https://open.feishu.cn** + +如果还没有登录,使用你的飞书账号登录。 + +### 1.2 进入开发者后台 + +登录后,点击页面右上角的「开发者后台」按钮。 + +### 1.3 创建新应用 + +1. 点击「创建自建应用」按钮 +2. 填写应用信息: + - **应用名称**:填一个你能认出来的名字,比如「AI 飞书助手」或「我的飞书 MCP」 + - **应用描述**:可以填「通过 AI 工具操作飞书」(随意填写,不影响功能) + - **应用图标**:可以上传一个图标,也可以使用默认图标 +3. 点击「确认创建」 + +### 1.4 记下 App ID 和 App Secret + +创建完成后,你会进入应用管理页面。在「凭证与基础信息」页面中,你可以看到: + +- **App ID**:以 `cli_` 开头的一串字符,比如 `cli_a1b2c3d4e5f6` +- **App Secret**:一串较长的字符 + +**请把这两个值复制下来保存好**,后面安装的时候需要用到。 + +> 注意:App Secret 是敏感信息,不要分享给他人或提交到公开的代码仓库。 + +--- + +## 第二步:配置应用权限 + +权限决定了 AI 助手可以操作飞书的哪些功能。你可以根据自己的需要选择开通。 + +### 2.1 进入权限管理页面 + +在应用管理页面的左侧菜单中,找到并点击「权限管理」。 + +### 2.2 开通基础权限 + +在搜索框中搜索以下权限名称,找到后点击「开通」按钮: + +**必须开通的权限:** + +| 在搜索框中输入 | 权限名称 | 作用 | +|---------------|---------|------| +| `docx:document` | 查看、评论和编辑云文档 | AI 能创建和编辑飞书文档 | +| `drive:drive` | 查看、管理和上传/下载云空间中的文件 | AI 能管理文件和文件夹 | +| `wiki:wiki` | 查看、编辑和管理知识库 | AI 能访问知识库内容 | + +### 2.3 开通推荐权限(按需) + +以下权限对应不同的飞书功能,根据你的需求选择开通: + +**消息功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `im:message` | 获取与发送消息 | 让 AI 发送和接收飞书消息 | +| `im:chat` | 获取群信息 | 让 AI 查看群聊信息 | + +**日历功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `calendar:calendar` | 查看和管理日历及日程 | 让 AI 查看日程、创建会议 | + +**表格功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `bitable:app` | 查看、评论和编辑多维表格 | 让 AI 操作多维表格 | +| `sheets:spreadsheet` | 查看和管理电子表格 | 让 AI 创建和编辑电子表格 | + +**任务功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `task:task` | 查看和管理任务 | 让 AI 创建和管理待办任务 | + +**邮件功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `mail:message` | 读取和发送邮件 | 让 AI 收发邮件 | + +**通讯录功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `contact:user.base:readonly` | 获取用户基本信息 | 让 AI 搜索员工联系方式 | + +**会议和妙记功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `vc:meeting` | 查看会议记录 | 让 AI 查询已结束的会议 | +| `minutes:minute` | 查看妙记 | 让 AI 获取会议 AI 总结 | + +**搜索功能:** + +| 搜索 | 权限名称 | 开通后可以 | +|------|---------|-----------| +| `search:docs:read` | 搜索云文档 | 让 AI 按关键词搜索文档 | + +> 不确定需要哪些?建议先开通基础权限和日历、消息功能。其他权限以后随时可以补开——当 AI 提示「权限不足」时,再回来开通对应权限即可。 + +--- + +## 第三步:配置安全设置 + +安装脚本在获取授权时需要通过浏览器回调,所以需要把回调地址配置到应用中。 + +### 3.1 进入安全设置 + +在应用管理页面的左侧菜单中,点击「安全设置」。 + +### 3.2 添加重定向 URL + +找到「重定向 URL」部分,点击「添加」按钮,依次添加以下两个地址: + +**第一个地址(用于飞书 CLI 授权):** +``` +http://localhost:3000/callback +``` + +**第二个地址(用于社区 MCP 授权):** +``` +http://localhost:3333/callback +``` + +添加完成后,确认列表中显示了这两个地址。 + +> 这两个地址是本地回调地址,只在你的电脑上使用,不会暴露到互联网。 + +--- + +## 第四步:发布应用 + +飞书应用需要发布后才能正常使用。 + +### 4.1 创建版本 + +1. 在应用管理页面的左侧菜单中,点击「版本管理与发布」 +2. 点击「创建版本」 +3. 填写版本信息: + - **版本号**:填 `1.0.0` 即可 + - **更新说明**:随意填写,比如「初始版本」 +4. 点击「保存」 + +### 4.2 申请发布 + +1. 点击「申请发布」 +2. 如果你是企业管理员,会直接通过 +3. 如果你不是管理员,需要等待管理员审批 + +> 如果你只是在个人环境使用(比如个人版飞书),通常创建后就可以直接使用,不需要额外审批。 + +--- + +## 第五步:运行安装脚本 + +### 5.1 确认前置条件 + +在运行脚本前,确认你的电脑上已安装 Node.js。打开终端(macOS 的「终端」应用或 Linux 的终端),输入: + +```bash +node --version +``` + +如果显示 `v16.x.x` 或更高版本(比如 `v18.17.0`、`v20.11.0`),说明已准备好。 + +如果提示找不到命令,请先安装 Node.js:前往 https://nodejs.org 下载并安装。 + +### 5.2 运行安装命令 + +在终端中执行: + +```bash +curl -fsSL https://raw.githubusercontent.com/AlexAnys/feishu-mcp/main/setup-v2.sh | bash +``` + +### 5.3 按提示操作 + +脚本会依次提示你: + +1. **输入 App ID** — 粘贴你在第一步中保存的 App ID(以 `cli_` 开头) +2. **输入 App Secret** — 粘贴你保存的 App Secret +3. **浏览器授权** — 脚本会自动打开浏览器,页面上会显示飞书授权确认。点击「授权」按钮 +4. **检测 AI 工具** — 脚本会自动检测你系统上安装的 AI 工具(OpenClaw、Claude Code、Cursor),并生成对应配置 + +整个过程大约 2-3 分钟,脚本会在每一步显示进度。 + +### 5.4 安装完成 + +当你看到安装成功的提示信息时,说明一切就绪。 + +--- + +## 第六步:验证安装 + +打开你的 AI 工具(OpenClaw、Claude Code 或 Cursor),在对话中输入: + +> "帮我检查一下飞书的认证状态" + +如果 AI 回复了认证信息(比如显示当前登录的用户名),说明安装成功。 + +你也可以试试: + +> "帮我看一下今天的飞书日程" + +如果 AI 返回了你的日程信息(或者提示今天没有日程),说明一切正常。 + +--- + +## 第七步:第一次对话 — 试试这些例子 + +以下是一些你可以立刻尝试的对话示例,涵盖不同的飞书功能: + +### 查看日程 + +> "我今天有什么安排?" + +AI 会列出你今天的飞书日历日程。 + +### 发送消息 + +> "给张三发一条飞书消息,内容是:明天的周会改到下午 3 点" + +AI 会通过飞书给张三发送消息。(需要先确认张三在你的通讯录中。) + +### 创建文档 + +> "帮我创建一个飞书文档,标题是《Q1 工作总结》,里面加三个章节:目标回顾、主要成果、下季度计划" + +AI 会在飞书中创建文档并添加章节标题,然后给你返回文档链接。 + +### 搜索文档 + +> "搜索一下飞书里关于产品上线的文档" + +AI 会搜索你的飞书云空间,返回匹配的文档列表。 + +### 查看任务 + +> "看看我在飞书里还有哪些未完成的任务" + +AI 会列出你的待办任务列表。 + +### 查收件箱 + +> "看看我最近有什么飞书邮件" + +AI 会显示你的最近收件箱内容。 + +### 查询多维表格 + +> "帮我查一下项目跟踪表里状态为「进行中」的记录" + +AI 会查询你的多维表格并返回符合条件的数据。 + +### 搜索同事 + +> "搜索一下李四的飞书联系方式" + +AI 会在通讯录中搜索并返回李四的信息。 + +### 创建画板流程图 + +> "帮我创建一个飞书画板,画一个用户注册流程图" + +AI 会创建画板并在上面画出流程图。 + +### 组合操作 + +> "帮我看一下昨天所有会议的纪要,整理成一份总结文档" + +AI 会先查询昨天的会议记录,获取纪要内容,然后创建一个新文档把总结写进去。 + +--- + +## 常见问题 + +### 创建应用相关 + +**Q: 我没有飞书开放平台的权限怎么办?** + +所有飞书用户都可以访问飞书开放平台并创建自建应用。如果你无法访问 open.feishu.cn,可能是企业管理员限制了开发者功能,请联系你的 IT 管理员。 + +**Q: 我应该创建「自建应用」还是「商店应用」?** + +选择「自建应用」。商店应用是给第三方开发者上架到飞书应用市场用的,不适合个人使用。 + +**Q: App Secret 泄露了怎么办?** + +在飞书开放平台的应用管理页面中,找到「凭证与基础信息」,点击 App Secret 旁边的「重置」按钮生成新的密钥。重置后需要重新运行安装脚本。 + +### 权限相关 + +**Q: 不知道该开通哪些权限?** + +建议先只开通三个基础权限(文档、云空间、知识库)。当你使用某个功能时,如果 AI 提示「权限不足」,再回来开通对应权限即可。这样最安全,也最简单。 + +**Q: 开通权限后需要重新发布应用吗?** + +如果只是增加权限范围(scope),通常不需要重新发布。但如果平台提示需要发布新版本,按照第四步的操作再发布一次即可。 + +**Q: 权限审批需要多久?** + +如果你是管理员,权限会立即生效。如果需要管理员审批,时间取决于你公司的审批流程。 + +### 安装脚本相关 + +**Q: 脚本提示 Node.js 版本过低怎么办?** + +请前往 https://nodejs.org 下载并安装最新的 LTS(长期支持)版本。安装完成后重新运行脚本。 + +**Q: 浏览器没有自动打开怎么办?** + +脚本会在终端中显示授权链接。手动复制这个链接到浏览器中打开,完成授权后回到终端继续。 + +**Q: 安装中断了,可以重新运行吗?** + +可以。安装脚本设计为可以安全地反复运行,不会重复安装已有组件或覆盖已有配置。直接重新运行即可。 + +**Q: 授权页面显示错误怎么办?** + +请检查: +1. 重定向 URL 是否正确配置(`http://localhost:3000/callback` 和 `http://localhost:3333/callback`) +2. 应用是否已发布 +3. 是否开通了所需权限 + +如果以上都确认无误,尝试重新运行安装脚本。 + +### 使用相关 + +**Q: AI 说「找不到工具」或「功能不可用」怎么办?** + +这通常意味着飞书 CLI 技能没有正确安装。在终端中运行以下命令检查: + +```bash +lark-cli skills list +``` + +如果列表为空或不完整,运行以下命令重新安装技能: + +```bash +npx skills add larksuite/cli -y -g +``` + +**Q: AI 提示「认证过期」或「token 无效」怎么办?** + +告诉 AI「重新登录飞书」,AI 会自动执行重新授权流程。也可以在终端手动运行: + +```bash +lark-cli auth login --recommend +``` + +**Q: 我想在另一台电脑上也使用,怎么做?** + +在新电脑上重新运行安装脚本即可。使用同一个 App ID 和 App Secret,不需要重新创建应用。 + +--- + +> 遇到本指南未覆盖的问题?请在 [GitHub Issues](https://github.com/AlexAnys/feishu-mcp/issues) 中提出,我们会尽快回复。 diff --git a/QUICKSTART-AGENT.md b/QUICKSTART-AGENT.md new file mode 100644 index 0000000..f252b7e --- /dev/null +++ b/QUICKSTART-AGENT.md @@ -0,0 +1,308 @@ +# QUICKSTART-AGENT.md — Feishu Integration Setup Automation + +**Audience**: AI agents automating Feishu setup for a new user. +**Purpose**: Step-by-step procedure to install and configure CLI + Community MCP from scratch. +**Prerequisites**: Node.js >= 16, npm, internet access. + +All instructions are imperative. Execute steps in order. Prompt the user only when prefixed with `[ASK USER]` or `[USER ACTION]`. + +--- + +## Pre-Setup Checks + +Run these checks before starting. If any fails, resolve before proceeding. + +### Check 1: Node.js version + +```bash +node --version +``` +- **Expected**: `v16.x.x` or higher (e.g., `v18.17.0`, `v20.11.0`). +- **If fails**: Output "Node.js 未安装或版本过低。请安装 Node.js 16 或更高版本:https://nodejs.org/". Stop. + +### Check 2: npm presence + +```bash +npm --version +``` +- **Expected**: Any version number (e.g., `9.8.1`). +- **If fails**: Output "npm 未找到。Node.js 安装通常自带 npm。请重新安装 Node.js:https://nodejs.org/". Stop. + +### Check 3: CLI already installed + +```bash +which lark-cli +``` +- **Expected**: A path (e.g., `/usr/local/bin/lark-cli`). +- **If not found**: CLI not installed. Continue to setup — installation will happen in the procedure. + +### Check 4: MCP already configured + +```bash +echo $FEISHU_APP_ID +``` +- **Expected**: A string starting with `cli_` (e.g., `cli_a1234567890`). +- **If empty**: MCP not configured. Continue to setup. +- **If set**: MCP may already be configured. Verify with a test call in the smoke test section. + +### Check 5: mcporter presence + +```bash +which mcporter +``` +- **Expected**: A path (e.g., `/usr/local/bin/mcporter`). +- **If not found**: mcporter not installed. Will be installed during setup. + +--- + +## Setup Procedure + +### Step 1: Run setup script + +**[EXECUTE]** Run the setup script: + +```bash +bash setup-v2.sh +``` + +If `setup-v2.sh` does not exist in the current directory, download it: + +```bash +curl -fsSL https://raw.githubusercontent.com/AlexAnys/feishu-mcp/main/setup-v2.sh -o setup-v2.sh && bash setup-v2.sh +``` + +**If fails**: Check error output. Common issues: +- "npm: command not found" → Node.js/npm not installed. Go back to Pre-Setup Checks. +- Network error → Check internet connectivity. Retry after network is restored. +- Permission error → Do not use `sudo`. Check npm global directory permissions. + +If the setup script is not available, proceed with manual steps (Steps 2-6 below). If the script ran successfully, skip to Step 7. + +--- + +### Step 2: Install Feishu CLI + +**[EXECUTE]** Install the CLI globally: + +```bash +npm install -g @larksuite/cli +``` + +**If fails**: Try with explicit registry: +```bash +npm install -g @larksuite/cli --registry https://registry.npmjs.org +``` +If still fails, check npm permissions. Output the error to the user. + +--- + +### Step 3: Install CLI skills + +**[EXECUTE]** Load all 19 AI skills: + +```bash +npx skills add larksuite/cli -y -g +``` + +**If fails**: Retry once. If still fails, output "CLI 技能安装失败。请检查网络连接后重试。" and continue — skills can be installed later. + +--- + +### Step 4: Guide user through Feishu app creation + +**[ASK USER]** Display: + +> 需要创建一个飞书自建应用来获取 API 凭证。 +> +> 请打开飞书开放平台:https://open.feishu.cn/app +> +> 1. 点击「创建企业自建应用」 +> 2. 输入应用名称(如:我的 AI 助手) +> 3. 创建完成后,在「凭证与基础信息」页面找到 **App ID** 和 **App Secret** +> +> 请提供你的 App ID(以 cli_ 开头): + +Wait for user to provide the App ID. Store as `APP_ID`. + +**[ASK USER]** Display: + +> 请提供 App Secret: + +Wait for user to provide the App Secret. Store as `APP_SECRET`. + +**If user cannot create the app**: Direct them to https://open.feishu.cn/app with step-by-step guidance. They must be a Feishu admin or have app creation permissions. + +--- + +### Step 5: Configure redirect URLs + +**[USER ACTION]** Display: + +> 在飞书开放平台的应用设置中,请添加以下重定向 URL: +> +> 安全设置 → 重定向 URL → 添加: +> - `http://localhost:3000/callback`(CLI 认证用) +> - `http://localhost:3333/callback`(MCP 认证用) +> +> 添加完成后请确认。 + +Wait for user confirmation. + +**If user cannot find the setting**: Direct them to: `https://open.feishu.cn/app/{APP_ID}/security` → "重定向 URL" section. + +--- + +### Step 6: Configure and authenticate + +**[EXECUTE]** Initialize CLI configuration: + +```bash +lark-cli config init --new +``` + +When prompted, enter the App ID and App Secret provided by the user. + +**[EXECUTE]** Start OAuth login: + +```bash +lark-cli auth login --recommend +``` + +**[USER ACTION]** Display: + +> 浏览器将打开飞书授权页面。请在浏览器中: +> 1. 使用飞书账号登录 +> 2. 点击「授权」按钮 +> 3. 看到「授权成功」后回到这里 + +Wait for OAuth to complete. + +**If fails**: Check that port 3000 is not in use (`lsof -i :3000`). If occupied, kill the process and retry. + +--- + +### Step 7: Configure community MCP + +**[EXECUTE]** Install mcporter if not present: + +```bash +npm install -g mcporter +``` + +**[EXECUTE]** Set MCP environment variables (use the App ID and App Secret from Step 4): + +```bash +export FEISHU_APP_ID="$APP_ID" +export FEISHU_APP_SECRET="$APP_SECRET" +``` + +**If setup-v2.sh was used**: These should already be configured. Verify with `echo $FEISHU_APP_ID`. + +--- + +### Step 8: Verify auth status + +**[EXECUTE]** Check CLI auth: + +```bash +lark-cli auth status +``` + +- **Expected**: Shows App ID, user identity, valid token. +- **If "Not logged in"**: Re-run `lark-cli auth login --recommend`. +- **If "Token expired"**: Re-run `lark-cli auth login --recommend`. + +**[EXECUTE]** Check MCP env vars: + +```bash +echo "APP_ID: $FEISHU_APP_ID" +echo "SECRET set: $([ -n "$FEISHU_APP_SECRET" ] && echo yes || echo no)" +``` + +- **Expected**: APP_ID shows `cli_xxx`, SECRET shows `yes`. +- **If empty**: Re-set the environment variables from Step 7. + +--- + +### Step 9: Enable Feishu permissions + +**[USER ACTION]** Display: + +> 请在飞书开放平台开通以下权限: +> +> 打开:https://open.feishu.cn/app/{APP_ID}/security +> +> 基础权限(必需): +> - `docx:document` — 读写文档 +> - `drive:drive` — 云空间 +> - `wiki:wiki` — 知识库 +> +> 推荐权限: +> - `bitable:app` — 多维表格 +> - `im:message` — 消息 +> - `search:docs:read` — 搜索 +> - `calendar:calendar` — 日历 +> - `mail:message` — 邮件 +> - `contact:user.base:readonly` — 通讯录 +> - `task:task` — 任务 +> +> 开通后请确认。 + +Wait for user confirmation. + +--- + +## Smoke Tests + +After setup completes, run these tests to verify the integration works end-to-end. + +### Smoke Test 1: CLI Layer + +```bash +lark-cli auth status +``` + +- **Success**: Output shows valid App ID and user identity with unexpired token. +- **Failure**: Output shows "Not logged in" or error. +- **Recovery**: Run `lark-cli auth login --recommend` and repeat. + +### Smoke Test 2: CLI Command + +```bash +lark-cli calendar +agenda +``` + +- **Success**: Output shows today's calendar events (or empty list if no events). +- **Failure — "skill not found"**: Run `npx skills add larksuite/cli -y -g` then retry. +- **Failure — "permission denied"**: Add `calendar:calendar` scope at `https://open.feishu.cn/app/{APP_ID}/security`. +- **Failure — auth error**: Run `lark-cli auth login --recommend` then retry. + +### Smoke Test 3: MCP Layer + +```bash +mcporter call feishu.create_feishu_document --args '{"title":"测试文档"}' +``` + +- **Success**: Output returns a document_id and URL. Delete the test document afterwards. +- **Failure — "unauthorized"**: Check `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars. Re-set and restart mcporter. +- **Failure — "permission denied"**: Add `docx:document` scope at `https://open.feishu.cn/app/{APP_ID}/security`. +- **Failure — "mcporter: command not found"**: Run `npm install -g mcporter` and retry. + +--- + +## Post-Setup Summary + +After all smoke tests pass, output: + +> 飞书集成配置完成! +> +> - CLI 认证:已通过 ✓ +> - MCP 连接:已通过 ✓ +> - 权限配置:已完成 ✓ +> +> 现在可以使用以下功能: +> - 发消息、管理日历、查看任务(CLI) +> - 创建/编辑文档、精确 Block 操作(MCP) +> - 搜索文档、管理知识库、上传文件 +> +> 详细用法参考 SKILL.md(路由决策)或 AGENTS.md(完整工具手册)。 diff --git a/README.md b/README.md index bdba612..972af3f 100644 --- a/README.md +++ b/README.md @@ -1,265 +1,248 @@ -# feishu-mcp +# feishu-mcp — 飞书全能集成套件 -飞书全能 MCP — 让 AI 助手完整操作你的飞书:创建文档、编辑内容、插入图表、管理表格。 +**让 AI 助手完整操作你的飞书** -专为 **Moltbot/Clawdbot** 用户设计,也适用于 Cursor、Claude Desktop、Windsurf 等 AI 工具。 +一条命令安装,用自然语言控制飞书的消息、日历、文档、表格、任务、邮件等全部功能。 -## ✨ 能做什么? +--- -### 📄 文档操作 -- **创建文档** — "帮我新建一个项目周报文档" -- **编辑内容** — "在文档开头加一段摘要" -- **读取内容** — "总结一下这篇文档的要点" -- **批量更新** — "把所有标题改成粗体" +## What can AI do? — 你可以让 AI 做什么 -### 📊 表格与图表 -- **创建表格** — "插入一个三列的对比表" -- **Mermaid 图表** — "画一个用户注册流程图" -- **思维导图** — "把这些要点整理成思维导图" +安装完成后,你可以在 AI 对话中直接说出以下需求,AI 会自动帮你完成: -### 🖼️ 多媒体 -- **插入图片** — "把这张截图加到文档里" -- **画板内容** — "获取画板里的流程图" +### 消息与沟通 +- "给张三发条消息,提醒他明天开会" +- "搜索聊天记录中关于项目上线的讨论" -### 📚 知识管理 -- **搜索文档** — "找一下上周的会议记录" -- **浏览文件夹** — "列出项目文档文件夹的内容" -- **知识库** — "在 Wiki 里创建一个新页面" +### 日历与日程 +- "看看我今天有什么会议" +- "帮我约一个明天下午 3 点的会议,邀请李四" +- "查一下王五这周有没有空" -### 📋 多维表格 -- **创建表格** — "新建一个项目跟踪表" -- **写入数据** — "把这些任务添加到表里" -- **查询记录** — "查一下本周的待办事项" +### 文档与编辑 +- "帮我新建一个项目周报文档" +- "在文档末尾追加一段总结" +- "把这个标题改成红色" +- "一次性添加 5 个格式化段落" -## 🚀 快速开始 +### 表格与数据 +- "创建一个销售数据电子表格" +- "查询项目跟踪表中本周的记录" +- "把这些数据写入表格" -### 1. 准备飞书应用 +### 任务与待办 +- "创建一个任务:下周五前完成设计评审" +- "看看我还有哪些未完成的任务" -去 [飞书开放平台](https://open.feishu.cn/app) 创建自建应用: +### 邮件 +- "给团队发一封项目进度邮件" +- "查看最近的收件箱" +- "搜索关于合同的邮件" -1. 创建应用,拿到 **App ID** 和 **App Secret** -2. 开通权限(见下方权限列表) -3. 安全设置 → 重定向 URL 添加:`http://localhost:3333/callback` -4. 发布应用 +### 知识库与搜索 +- "列出所有知识空间" +- "搜索关于 Q1 的文档" +- "在技术文档知识库里创建一个新页面" -### 2. 一键配置 +### 会议与妙记 +- "看看昨天有哪些会议记录" +- "获取这个妙记的 AI 总结" -```bash -curl -fsSL https://raw.githubusercontent.com/AlexAnys/feishu-mcp/main/setup.sh | bash -``` +### 画板与图表 +- "创建一个新画板" +- "在画板上画一个用户注册流程图" -按提示输入 App ID 和 App Secret,脚本会自动完成所有配置。 +### 通讯录 +- "搜索张三的联系方式" +- "查一下产品部有哪些人" -### 3. 开始使用 - -在 Moltbot 对话中直接说: -> "帮我在飞书创建一个新文档,标题是《项目周报》" +### 云空间文件管理 +- "上传这个 PDF 到飞书云空间" +- "创建一个新文件夹叫项目资料" --- -## 📦 包含的 MCP 服务 +## Quick Start — 一键安装 -本 Skill 整合了两个 MCP,发挥各自优势: +### 第一步:准备飞书应用 -| MCP | 用途 | 服务名 | -|-----|------|--------| -| [feishu-mcp](https://github.com/cso1z/Feishu-MCP) (社区版) | 文档创建/编辑、图表、图片 | `feishu` | -| [lark-openapi-mcp](https://github.com/larksuite/lark-openapi-mcp) (官方) | 多维表格、日历、消息、搜索 | `lark` / `lark-user` | +你需要先在飞书开放平台创建一个自建应用,获取 App ID 和 App Secret。 -## 🔑 需要的权限 +> 如果你从未使用过飞书开放平台,请查看 **[GUIDE.md — 从零开始配置飞书 AI 助手](./GUIDE.md)**,里面有详细的每一步操作说明。 -在飞书开放平台开通以下权限: +简要步骤: +1. 打开 [飞书开放平台](https://open.feishu.cn/app),登录后点击「创建自建应用」 +2. 记下应用的 **App ID** 和 **App Secret** +3. 在应用的「安全设置」中添加两个重定向 URL: + - `http://localhost:3000/callback` + - `http://localhost:3333/callback` +4. 在「权限管理」中开通所需权限(见下方[权限列表](#permissions--需要的权限)) +5. 发布应用(创建版本并发布) -### 基础权限(必需) -| 权限 | 说明 | -|------|------| -| `docx:document` | 读写文档 | -| `drive:drive` | 访问云空间 | -| `wiki:wiki` | 访问知识库 | +### 第二步:运行安装脚本 -### 推荐权限 -| 权限 | 说明 | -|------|------| -| `bitable:app` | 多维表格 | -| `im:message` | 发送消息 | -| `search:docs:read` | 搜索文档 | -| `calendar:calendar` | 日历管理 | +```bash +curl -fsSL https://raw.githubusercontent.com/AlexAnys/feishu-mcp/main/setup-v2.sh | bash +``` -> 💡 首次调用某功能时如果提示权限不足,按提示链接开通即可。 +脚本会引导你: +- 输入 App ID 和 App Secret +- 自动安装飞书 CLI 和社区 MCP +- 打开浏览器完成 OAuth 授权 +- 检测你使用的 AI 工具并生成对应配置 -## 🛠️ 可用工具一览 +整个过程大约 2-3 分钟。 -### 文档管理(feishu-mcp) +### 第三步:开始对话 -| 工具 | 功能 | -|------|------| -| `create_feishu_document` | 创建新文档 | -| `get_feishu_document_info` | 获取文档信息 | -| `get_feishu_document_blocks` | 获取文档结构 | -| `batch_create_feishu_blocks` | 批量创建内容块 | -| `update_feishu_block_text` | 更新文本内容 | -| `delete_feishu_document_blocks` | 删除内容块 | -| `create_feishu_table` | 创建表格 | -| `upload_and_bind_image_to_block` | 上传图片 | -| `get_feishu_folder_files` | 获取文件夹内容 | -| `create_feishu_folder` | 创建文件夹 | -| `search_feishu_documents` | 搜索文档 | -| `get_feishu_whiteboard_content` | 获取画板内容 | +在你的 AI 工具中直接说: -### 多维表格(lark-mcp) +> "帮我看一下今天的飞书日程" -| 工具 | 功能 | -|------|------| -| `bitable_v1_app_create` | 创建多维表格 | -| `bitable_v1_appTable_list` | 列出数据表 | -| `bitable_v1_appTableRecord_create` | 创建记录 | -| `bitable_v1_appTableRecord_search` | 搜索记录 | -| `bitable_v1_appTableRecord_update` | 更新记录 | +如果 AI 成功返回了你的日程安排,说明安装已完成。 -### 搜索与知识库(lark-mcp) +--- -| 工具 | 功能 | -|------|------| -| `docx_builtin_search` | 搜索云文档 | -| `docx_v1_document_rawContent` | 获取文档纯文本 | -| `wiki_v1_node_search` | 搜索知识库 | -| `wiki_v2_space_getNode` | 获取 Wiki 节点 | +## Supported AI Tools — 支持的 AI 工具 -## 📝 使用示例 +| AI 工具 | 支持程度 | 说明 | +|---------|---------|------| +| **OpenClaw** | 推荐 | 主要适配平台,安装脚本自动检测并配置 | +| **Claude Code** | 完全支持 | 自动生成 MCP 配置文件 | +| **Cursor** | 完全支持 | 自动生成 MCP 配置文件 | -### 创建并编辑文档 +安装脚本会自动检测你系统上安装了哪些 AI 工具,并生成对应的配置文件到 `configs/` 目录。 -``` -用户:帮我创建一个文档,标题是"Q1 工作总结" +--- -AI:我来创建文档... - [调用 create_feishu_document] - 文档已创建:https://xxx.feishu.cn/docx/xxx - -用户:在里面加上三个章节:目标回顾、主要成果、下季度计划 +## Architecture — 工作原理 -AI:正在添加章节... - [调用 batch_create_feishu_blocks] - 已添加三个章节标题,请查看文档。 -``` +如果你好奇这个套件是怎么让 AI 操作飞书的,这里做一个简单说明。 -### 插入流程图 +feishu-mcp 整合了两个工具层,它们各有所长、互相配合: ``` -用户:在文档里画一个用户注册流程图 - -AI:我来创建 Mermaid 流程图... - [调用 batch_create_feishu_blocks with mermaid] - - 已插入流程图: - 用户访问 → 填写信息 → 验证手机 → 注册成功 +你 <-> AI 助手 (OpenClaw / Claude Code / Cursor) + | + feishu-mcp 集成层 + | + +---------+---------+ + | | + 飞书 CLI 社区 MCP + (官方命令行工具) (文档精编工具) + 覆盖 11 个业务域 15 个文档编辑工具 + 消息/日历/邮件/ 精确到每个内容块 + 任务/表格/知识库... 颜色/对齐/批量操作 ``` -### 搜索并总结 +**简单理解**: +- **飞书 CLI** 负责「广度」— 消息、日历、邮件、任务、表格、知识库等所有非文档领域都靠它 +- **社区 MCP** 负责「深度」— 需要精确编辑文档内容(比如给标题改颜色、一次创建多个格式化段落)时用它 +- AI 助手根据你的需求自动选择用哪个工具,你不需要关心这些细节 -``` -用户:找一下上周的产品会议记录,总结出行动项 - -AI:搜索中... - [调用 docx_builtin_search] - 找到 3 篇相关文档,正在读取... - [调用 docx_v1_document_rawContent] - - 行动项汇总: - 1. @张三 完成原型设计 - 本周五 - 2. @李四 准备用户访谈 - 下周一 - ... -``` +> 想了解更多技术细节?请查看 [SKILL.md](./SKILL.md)(AI 决策矩阵)和 [AGENTS.md](./AGENTS.md)(AI 操作手册)。 -### 写入多维表格 +--- -``` -用户:把这些任务添加到项目跟踪表 +## Permissions — 需要的权限 -AI:正在写入... - [调用 bitable_v1_appTableRecord_create] - 已添加 5 条记录到多维表格。 -``` +在飞书开放平台的「权限管理」页面中开通以下权限。 -## 🔧 手动配置(可选) +### 基础权限(必须开通) -
-点击展开手动配置步骤 +| 权限标识 | 说明 | 用于 | +|---------|------|------| +| `docx:document` | 读写云文档 | 创建和编辑文档 | +| `drive:drive` | 访问云空间 | 管理文件和文件夹 | +| `wiki:wiki` | 访问知识库 | 浏览和管理知识空间 | -### 安装依赖 +### 推荐权限(按需开通) -```bash -npm install -g mcporter -``` +| 权限标识 | 说明 | 用于 | +|---------|------|------| +| `im:message` | 发送和接收消息 | 消息和聊天功能 | +| `calendar:calendar` | 日历管理 | 查看日程、创建会议 | +| `bitable:app` | 多维表格 | 查询和管理多维表格数据 | +| `search:docs:read` | 搜索文档 | 搜索云空间内容 | +| `task:task` | 任务管理 | 创建和查看待办任务 | +| `mail:message` | 邮件读写 | 收发邮件 | +| `contact:user.base:readonly` | 通讯录基础信息 | 搜索员工和查看联系方式 | +| `vc:meeting` | 视频会议 | 查询会议记录 | +| `minutes:minute` | 妙记 | 获取会议纪要和 AI 总结 | +| `sheets:spreadsheet` | 电子表格 | 创建和编辑表格 | -### 配置文件 - -编辑 `config/mcporter.json`: - -```json -{ - "mcpServers": { - "feishu": { - "command": "npx", - "args": ["-y", "feishu-mcp@latest", "--stdio"], - "env": { - "FEISHU_APP_ID": "cli_你的AppID", - "FEISHU_APP_SECRET": "你的AppSecret", - "FEISHU_AUTH_TYPE": "user" - } - }, - "lark": { - "command": "npx", - "args": ["-y", "@larksuiteoapi/lark-mcp", "mcp", "-a", "cli_你的AppID", "-s", "你的AppSecret"] - }, - "lark-user": { - "command": "npx", - "args": ["-y", "@larksuiteoapi/lark-mcp", "mcp", "-a", "cli_你的AppID", "-s", "你的AppSecret", "--oauth", "--token-mode", "user_access_token"] - } - } -} -``` +> 不需要一次全部开通。首次使用某个功能时如果提示权限不足,再去开通即可。 -### 用户授权 +--- -```bash -# 社区版授权 -npx feishu-mcp@latest --feishu-app-id="cli_xxx" --feishu-app-secret="secret" --feishu-auth-type="user" +## FAQ — 常见问题 -# 官方版授权 -npx -y @larksuiteoapi/lark-mcp login -a "cli_xxx" -s "secret" -``` +### 安装相关 + +**Q: 安装脚本需要什么环境?** + +需要 Node.js 16 或更高版本和 npm。macOS 和 Linux 系统都支持。不需要管理员权限(sudo)。 + +**Q: 安装失败怎么办?** -
+脚本在每一步都会显示中文错误提示和修复建议。如果遇到问题,可以重新运行脚本(它是安全的,可以反复执行),或查看 [GUIDE.md](./GUIDE.md) 中的常见问题部分。 -## ❓ 常见问题 +**Q: 可以重新运行安装脚本吗?** -### Q: tenant 和 user 认证有什么区别? +可以。脚本设计为可重复运行(幂等),不会重复安装已有的组件,也不会覆盖你已有的配置。 + +### 认证相关 + +**Q: tenant 和 user 认证有什么区别?** | 认证类型 | 身份 | 适用场景 | |----------|------|----------| -| `tenant` | 应用 | 操作应用创建的资源 | -| `user` | 用户本人 | 访问个人文档(推荐)| +| `tenant`(应用身份) | 以应用名义操作 | 操作应用自己创建的资源 | +| `user`(用户身份) | 以你本人名义操作 | 访问你自己的文档、日程等 | + +**强烈建议使用 user 认证**,这样 AI 操作的飞书内容会显示为你本人的操作,功能也更完整。安装脚本默认使用 user 认证。 + +**Q: 授权过期了怎么办?** + +AI 工具通常会自动刷新授权。如果确实过期了,你可以说「重新登录飞书」,AI 会帮你重新完成授权。 -**强烈建议使用 user 认证**,功能更完整。 +### 使用相关 -### Q: 权限不足怎么办? +**Q: 文档链接里的 token 怎么获取?** -按错误提示的链接开通权限,或在开放平台手动添加。 +飞书文档链接格式:`https://xxx.feishu.cn/docx/AbCdEfGhIjKl` +最后一段 `AbCdEfGhIjKl` 就是 document_token。你也可以直接把链接发给 AI,它会自动提取。 -### Q: 文档链接怎么获取 token? +**Q: 支持哪些飞书功能?** + +目前覆盖 11 个业务域:消息、日历、文档、云空间、电子表格、多维表格、任务、邮件、通讯录、知识库、会议/妙记,以及画板和事件订阅。完整的功能列表见 [SKILL.md](./SKILL.md)。 + +**Q: AI 是怎么决定用哪个工具的?** + +feishu-mcp 自带一个「决策矩阵」([SKILL.md](./SKILL.md)),AI 会根据你的需求自动路由到合适的工具。你只需要用自然语言描述需求,不需要关心底层实现。 + +--- + +## Related Docs — 其他文档 + +| 文档 | 说明 | 适合谁看 | +|------|------|---------| +| [GUIDE.md](./GUIDE.md) | 从零开始的安装配置图文指南 | 第一次使用飞书开放平台的用户 | +| [SKILL.md](./SKILL.md) | AI 决策矩阵 — 每个操作对应哪个工具 | 好奇 AI 怎么选择工具的用户 | +| [AGENTS.md](./AGENTS.md) | AI 操作完整手册 | AI 开发者 / 高级用户 | +| [QUICKSTART-AGENT.md](./QUICKSTART-AGENT.md) | AI 自动安装指南 | AI 代理自动化使用 | +| [TROUBLESHOOT-AGENT.md](./TROUBLESHOOT-AGENT.md) | 错误诊断与恢复 | 遇到问题时参考 | + +--- -飞书文档链接格式:`https://xxx.feishu.cn/docx/AbCdEfGhIjKl` -最后一段 `AbCdEfGhIjKl` 就是 document_token。 +## Contributing — 参与贡献 -## 🔗 相关资源 +欢迎提交 Issue 和 Pull Request。 -- [feishu-mcp (社区版)](https://github.com/cso1z/Feishu-MCP) — 文档编辑能力 -- [lark-openapi-mcp (官方)](https://github.com/larksuite/lark-openapi-mcp) — 官方 API -- [moltbot-feishu](https://github.com/AlexAnys/moltbot-feishu) — 飞书消息通道插件 -- [飞书开放平台](https://open.feishu.cn) -- [Moltbot](https://github.com/moltbot/moltbot) +- **报告问题**:在 [Issues](https://github.com/AlexAnys/feishu-mcp/issues) 中描述你遇到的问题 +- **功能建议**:同样在 Issues 中提出 +- **代码贡献**:Fork 后提交 PR,请遵循项目现有的代码风格 -## 📜 License +## License MIT diff --git a/SKILL.md b/SKILL.md index c19765a..8368734 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,75 +1,544 @@ --- name: feishu-mcp -description: 飞书全能 MCP - 创建/编辑文档、插入图表、管理表格、搜索知识库。整合社区版+官方 MCP,适配 Moltbot/Clawdbot。 -metadata: {"clawdbot":{"emoji":"📘","requires":{"bins":["mcporter"]}}} +description: 飞书全能集成套件 — CLI(19 技能、11 业务域、200+ 命令)+ 社区 MCP(15 文档编辑工具、Block 级精度)统一路由决策矩阵,让 AI Agent 精准选择每个飞书操作的最佳工具。 +metadata: + clawdbot: + emoji: "📘" + requires: + bins: + - mcporter --- -# 飞书全能 MCP +# 飞书全能集成套件 — 决策矩阵 -整合社区版 feishu-mcp(文档编辑)+ 官方 lark-mcp(多维表格/搜索),让 Clawdbot 完整操作飞书。 +整合飞书 CLI(`@larksuite/cli`,19 AI 技能,200+ 命令,覆盖 11 业务域)和社区 MCP(`feishu-mcp`,15 文档编辑工具,Block 级精度),为 AI Agent 提供统一路由决策。 -## 快速配置 +--- -```bash -curl -fsSL https://raw.githubusercontent.com/AlexAnys/feishu-mcp/main/setup.sh | bash -``` +## Decision Principles — 决策原则 -## 三个 MCP 服务 +按顺序应用以下规则,选择第一条匹配的规则: -| 服务 | 来源 | 能力 | -|------|------|------| -| `feishu` | 社区版 | 创建/编辑文档、图表、图片 | -| `lark` | 官方 | 多维表格、发消息 | -| `lark-user` | 官方 | 搜索文档、读取知识库 | +1. **非文档域一律用 CLI** — 如果任务涉及消息、日历、邮件、任务、通讯录、会议、妙记、电子表格、多维表格、Wiki 管理 或 事件订阅,使用 CLI。 +2. **精确 Block 编辑用 MCP** — 如果任务需要精确的 Block 级文档编辑(指定颜色、对齐方式、批量创建格式化 Block、更新特定 Block 的样式),使用社区 MCP。 +3. **CLI 和 MCP 都能做时优先 CLI** — 如果两层都能完成任务,优先使用 CLI,除非 MCP 在精度上有明确优势。 +4. **图表和画板编辑用 CLI** — Mermaid 图表、高级图表 DSL、画板创建/编辑仅 CLI 支持(MCP 仅能读取画板内容)。 +5. **多步工作流可组合两层** — 如果任务需要先查询数据(CLI)再生成格式化文档(MCP),按步骤组合使用。 -## 主要工具 +--- -### 文档操作 (feishu) -```bash -# 创建文档 -mcporter call feishu.create_feishu_document --args '{"title":"新文档"}' +## Quick Decision Table — 快速决策表 -# 添加内容 -mcporter call feishu.batch_create_feishu_blocks --args '{"document_id":"xxx","blocks":[...]}' +| User Intent (用户意图) | Tool Layer | Specific Tool/Command | Notes | +|---|---|---|---| +| 查看今天的日程 | CLI | `lark-cli calendar +agenda` | 快速概览今日行程 | +| 创建日程/会议 | CLI | `lark-cli calendar +create` | 支持邀请参会人 | +| 查询某人忙闲状态 | CLI | `lark-cli calendar +freebusy` | 查询主日历忙闲 | +| 推荐空闲会议时段 | CLI | `lark-cli calendar +suggestion` | 多方案推荐 | +| 发送飞书消息 | CLI | `lark-cli im +send` | 支持文本/富文本/附件 | +| 搜索聊天记录 | CLI | `lark-cli im +search` | 按关键词搜索 | +| 从 Markdown 创建文档 | CLI | `lark-cli doc +create` | Markdown 输入最简单 | +| 搜索云空间文档 | CLI | `lark-cli doc +search` | 官方接口更可靠 | +| 更新文档内容(追加/覆盖) | CLI | `lark-cli docs +update` | 支持 append/overwrite/replace/insert/delete 模式 | +| 在文档中插入图片 | CLI | `lark-cli docs +media-insert` | CLI 更健壮 | +| 创建文档(指定文件夹) | MCP | `create_feishu_document` | 可指定 folderToken | +| 获取文档元信息 | MCP | `get_feishu_document_info` | 返回标题、修改时间等 | +| 获取文档 Block 结构 | MCP | `get_feishu_document_blocks` | 返回完整 Block 树 | +| 提取文档纯文本 | MCP | `get_feishu_document_text` | 纯文本提取 | +| 批量创建格式化 Block | MCP | `batch_create_feishu_blocks` | 原子操作,支持 text/code/heading/list | +| 更新 Block 文本及样式 | MCP | `update_feishu_block_text` | 8 色彩、对齐方式 | +| 删除文档中的 Block | MCP | `delete_feishu_document_blocks` | 按 block_id 删除 | +| 上传图片并绑定到 Block | MCP | `upload_and_bind_image_to_block` | 图片上传 + 绑定一步完成 | +| 在文档中创建表格 | MCP | `create_feishu_table` | 指定行列数 | +| 创建文件夹 | MCP | `create_feishu_folder` | 云空间文件夹 | +| 列出文件夹内容 | MCP | `list_feishu_folder_contents` | 浏览文件夹结构 | +| 获取文件夹文件列表 | MCP | `get_feishu_folder_files` | 文件夹内文件清单 | +| 搜索文档(MCP 层) | MCP | `search_feishu_documents` | 社区 MCP 搜索 | +| 获取 Wiki 节点信息 | MCP | `get_feishu_wiki_node_info` | Wiki 元数据 | +| 获取画板内容 | MCP | `get_feishu_whiteboard_content` | 仅读取,不可编辑 | +| 上传文件到云空间 | CLI | `lark-cli drive upload` | 支持多种文件类型 | +| 下载云空间文件 | CLI | `lark-cli drive download` | 下载到本地 | +| 创建电子表格 | CLI | `lark-cli sheets +create` | 创建并写入表头 | +| 读取电子表格数据 | CLI | `lark-cli sheets +read` | 读取单元格范围 | +| 写入电子表格数据 | CLI | `lark-cli sheets +write` | 批量写入单元格 | +| 查询多维表格记录 | CLI | `lark-cli base +query` | 支持筛选/排序 | +| 创建多维表格 | CLI | `lark-cli base +create` | 创建表 + 字段 | +| 创建待办任务 | CLI | `lark-cli task +create` | 支持分配/截止日期 | +| 查看我的任务列表 | CLI | `lark-cli task +get-my-tasks` | 个人待办 | +| 写邮件并发送 | CLI | `lark-cli mail +compose` | 支持抄送/附件 | +| 查看收件箱 | CLI | `lark-cli mail +inbox` | 最近邮件列表 | +| 搜索邮件 | CLI | `lark-cli mail +search` | 按关键词搜索 | +| 搜索员工/联系人 | CLI | `lark-cli contact +search` | 姓名/邮箱/手机号 | +| 列出 Wiki 知识空间 | CLI | `lark-cli wiki +list` | 浏览知识空间 | +| 在 Wiki 中创建文档 | CLI | `lark-cli wiki +create` | 知识库节点创建 | +| 创建画板 | CLI | `lark-cli whiteboard +create` | 新建飞书画板 | +| 编辑画板内容 | CLI | `lark-cli docs +whiteboard-update` | Mermaid/图表/视觉编辑 | +| 查看认证状态 | CLI | `lark-cli auth status` | 检查 token 是否有效 | +| 登录认证 | CLI | `lark-cli auth login` | OAuth 浏览器认证 | +| Check my schedule for tomorrow | CLI | `lark-cli calendar +agenda` | English: same command | +| Create a document from notes | CLI | `lark-cli doc +create` | English: Markdown input | +| Search for meeting minutes | CLI | `lark-cli doc +search` | English: keyword search | +| 生成格式化报告(查询 + 文档) | CLI+MCP | `lark-cli base +query` → `batch_create_feishu_blocks` | 多步:先查数据再写文档 | +| 整理会议纪要到文档 | CLI+MCP | `lark-cli vc` → `batch_create_feishu_blocks` | 多步:获取纪要再格式化 | -# 插入表格 -mcporter call feishu.create_feishu_table --args '{"document_id":"xxx","rows":3,"cols":3}' -``` +--- + +## Domain Sections — 业务域详解 + +### Auth/Identity — 认证与身份 + +**Skill**: `lark-shared` — 应用配置初始化、认证登录、身份切换、权限管理。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli config init --new` | 初始化应用配置 | +| `lark-cli auth login --recommend` | OAuth 浏览器登录 | +| `lark-cli auth status` | 查看当前认证状态 | +| `lark-cli auth check` | 检查 token 有效性 | + +**示例 Prompt:** +- "检查一下飞书认证状态" → `lark-cli auth status` +- "重新登录飞书" → `lark-cli auth login --recommend` + +**路由说明:** CLI only。社区 MCP 认证通过环境变量,不提供交互式认证命令。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Calendar — 日历 + +**Skill**: `lark-calendar` — 提供日历与日程的全面管理:查看/搜索日程、创建/更新日程、管理参会人、查询忙闲状态及推荐空闲时段。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli calendar +agenda` | 快速概览今日/近期行程 | +| `lark-cli calendar +create` | 创建日程并邀请参会人 | +| `lark-cli calendar +freebusy` | 查询用户主日历忙闲信息 | +| `lark-cli calendar +suggestion` | 提供多个时间推荐方案 | + +**示例 Prompt:** +- "看一下今天有什么会议" → `lark-cli calendar +agenda` +- "帮我约一个明天下午的会议" → `lark-cli calendar +create` +- "查一下张三这周的忙闲状态" → `lark-cli calendar +freebusy` + +**路由说明:** CLI only。社区 MCP 不支持日历操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Messaging — 即时通讯 + +**Skill**: `lark-im` — 收发消息和管理群聊:发送/回复消息、搜索聊天记录、管理群聊成员、上传下载文件/图片、管理表情回复。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli im +send` | 发送消息(文本/富文本/附件) | +| `lark-cli im +search` | 搜索聊天记录 | + +**示例 Prompt:** +- "给张三发条消息说明天开会" → `lark-cli im +send` +- "搜索最近关于项目上线的聊天记录" → `lark-cli im +search` + +**路由说明:** CLI only。社区 MCP 不支持消息操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Documents — 文档操作 + +**Skill**: `lark-doc` — 创建和编辑飞书文档:从 Markdown 创建、获取内容、更新(追加/覆盖/替换/插入/删除)、上传图片和文件、搜索文档。此域 CLI 和 MCP 重叠最多,需仔细路由。 + +**CLI 命令:** + +| 命令 | 描述 | +|---|---| +| `lark-cli doc +create` | 从 Markdown 创建文档 | +| `lark-cli doc +search` | 搜索云空间文档 | +| `lark-cli docs +update` | 更新文档(append/overwrite/replace/insert/delete) | +| `lark-cli docs +media-insert` | 在文档中插入图片/文件 | + +**MCP 工具:** + +| 工具 | 描述 | +|---|---| +| `create_feishu_document` | 创建文档(可指定文件夹) | +| `get_feishu_document_info` | 获取文档元信息 | +| `get_feishu_document_blocks` | 获取文档 Block 结构树 | +| `get_feishu_document_text` | 提取文档纯文本 | +| `batch_create_feishu_blocks` | 批量创建 Block(text/code/heading/list),原子操作 | +| `update_feishu_block_text` | 更新 Block 文本及样式(8 色彩、对齐方式) | +| `delete_feishu_document_blocks` | 按 block_id 删除 Block | +| `upload_and_bind_image_to_block` | 上传图片并绑定到 Block | +| `create_feishu_table` | 在文档中创建表格 | + +**示例 Prompt:** +- "帮我新建一个项目周报文档" → `lark-cli doc +create` +- "搜索一下上周的会议纪要" → `lark-cli doc +search` +- "在文档末尾追加一段总结" → `lark-cli docs +update` (append 模式) +- "在文档里插入截图" → `lark-cli docs +media-insert` +- "获取这篇文档的所有 Block 结构" → `get_feishu_document_blocks` +- "给文档的第二个标题改成红色" → `update_feishu_block_text` +- "一次性添加 5 个格式化段落" → `batch_create_feishu_blocks` +- "删除文档中指定的 Block" → `delete_feishu_document_blocks` +- "Create a new doc titled Q1 Summary" → `lark-cli doc +create` + +**路由说明:** +- 简单创建/搜索/追加/覆盖 → 用 CLI(更简洁) +- 需要精确 Block 操作(指定颜色、对齐、批量格式化 Block)→ 用 MCP +- 需要读取 Block 结构树 → 用 MCP(`get_feishu_document_blocks`) +- 需要提取纯文本 → 用 MCP(`get_feishu_document_text`) +- 如果此技能不可用,检查:`lark-cli skills list` + +--- + +### Cloud Storage — 云空间 + +**Skill**: `lark-drive` — 管理云空间中的文件和文件夹:上传/下载文件、创建文件夹、复制/移动/删除文件、管理文档评论和权限。 + +**CLI 命令:** + +| 命令 | 描述 | +|---|---| +| `lark-cli drive upload` | 上传文件到云空间 | +| `lark-cli drive download` | 下载文件到本地 | + +**MCP 工具:** + +| 工具 | 描述 | +|---|---| +| `create_feishu_folder` | 创建文件夹 | +| `list_feishu_folder_contents` | 列出文件夹内容 | +| `get_feishu_folder_files` | 获取文件夹文件列表 | + +**示例 Prompt:** +- "上传这个 PDF 到飞书云空间" → `lark-cli drive upload` +- "下载这个文件" → `lark-cli drive download` +- "创建一个新文件夹叫项目资料" → `create_feishu_folder` +- "列出项目文档文件夹的内容" → `list_feishu_folder_contents` + +**路由说明:** 上传/下载用 CLI;文件夹管理 CLI 和 MCP 都可用,CLI 更完整。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Spreadsheets — 电子表格 + +**Skill**: `lark-sheets` — 创建和操作电子表格:创建表格并写入数据、读取和写入单元格、追加行、查找内容、导出文件。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli sheets +create` | 创建电子表格并写入表头 | +| `lark-cli sheets +write` | 批量写入单元格 | +| `lark-cli sheets +read` | 读取单元格范围 | + +**示例 Prompt:** +- "创建一个销售数据表" → `lark-cli sheets +create` +- "把这些数据写入表格" → `lark-cli sheets +write` +- "读取 A1:D10 的数据" → `lark-cli sheets +read` + +**路由说明:** CLI only。社区 MCP 不支持电子表格操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Bitable — 多维表格 + +**Skill**: `lark-base` — 管理多维表格:创建表/字段/记录、查询数据、配置视图、管理仪表盘。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli base +query` | 查询多维表格记录(支持筛选/排序) | +| `lark-cli base +create` | 创建多维表格 | + +**示例 Prompt:** +- "查询项目表中本周的记录" → `lark-cli base +query` +- "新建一个 Bug 追踪多维表格" → `lark-cli base +create` + +**路由说明:** CLI only。社区 MCP 不支持多维表格。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Tasks — 任务 + +**Skill**: `lark-task` — 管理任务和清单:创建待办、查看/更新状态、子任务拆分、分配协作成员。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli task +create` | 创建待办任务 | +| `lark-cli task +get-my-tasks` | 查看个人任务列表 | + +**示例 Prompt:** +- "创建一个任务:下周五前完成设计评审" → `lark-cli task +create` +- "看看我还有哪些未完成的任务" → `lark-cli task +get-my-tasks` + +**路由说明:** CLI only。社区 MCP 不支持任务操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Email — 邮件 + +**Skill**: `lark-mail` — 飞书邮箱管理:起草/发送/回复/转发/搜索邮件,管理草稿和通讯录。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli mail +compose` | 写邮件并发送 | +| `lark-cli mail +inbox` | 查看收件箱 | +| `lark-cli mail +search` | 搜索邮件 | + +**示例 Prompt:** +- "给团队发一封项目进度邮件" → `lark-cli mail +compose` +- "查看最近的收件箱" → `lark-cli mail +inbox` +- "搜索关于合同的邮件" → `lark-cli mail +search` + +**路由说明:** CLI only。社区 MCP 不支持邮件操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Contacts — 通讯录 + +**Skill**: `lark-contact` — 查询组织架构和人员信息:搜索员工、查看个人信息、查询部门结构。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli contact +search` | 搜索员工(姓名/邮箱/手机号) | + +**示例 Prompt:** +- "搜索张三的联系方式" → `lark-cli contact +search` +- "查一下产品部有哪些人" → `lark-cli contact +search` + +**路由说明:** CLI only。社区 MCP 不支持通讯录操作。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Wiki — 知识库 + +**Skill**: `lark-wiki` — 管理知识空间和文档节点:创建/查询知识空间、管理节点层级、组织文档。 + +**CLI 命令:** + +| 命令 | 描述 | +|---|---| +| `lark-cli wiki +list` | 列出知识空间 | +| `lark-cli wiki +create` | 在知识库中创建文档 | + +**MCP 工具:** + +| 工具 | 描述 | +|---|---| +| `get_feishu_wiki_node_info` | 获取 Wiki 节点元数据 | + +**示例 Prompt:** +- "列出所有知识空间" → `lark-cli wiki +list` +- "在技术文档知识库里创建一个新页面" → `lark-cli wiki +create` +- "获取这个 Wiki 节点的元信息" → `get_feishu_wiki_node_info` + +**路由说明:** 管理操作(创建、列表、导航)用 CLI;仅查询节点元数据可用 MCP。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Meetings/Minutes — 会议与妙记 + +**Skills**: `lark-vc` + `lark-minutes` — 查询会议记录、获取会议纪要产物(总结、待办、章节、逐字稿)。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli vc` | 查询视频会议记录(结束的会议) | +| `lark-cli minutes` | 获取妙记信息(标题、时长、AI 总结) | + +**示例 Prompt:** +- "看看昨天有哪些会议记录" → `lark-cli vc` +- "获取这个妙记的 AI 总结" → `lark-cli minutes` + +**路由说明:** CLI only。社区 MCP 不支持会议操作。查未来日程用 `lark-cli calendar +agenda`,查已结束会议用 `lark-cli vc`。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Whiteboard — 画板 + +**Skill**: `lark-whiteboard` — 创建和编辑飞书画板:Mermaid 图表、流程图、架构图、思维导图。 + +**CLI 命令:** + +| 命令 | 描述 | +|---|---| +| `lark-cli whiteboard +create` | 创建新画板 | +| `lark-cli docs +whiteboard-update` | 编辑画板(Mermaid/图表/视觉内容) | + +**MCP 工具:** + +| 工具 | 描述 | +|---|---| +| `get_feishu_whiteboard_content` | 读取画板内容(只读) | + +**示例 Prompt:** +- "创建一个新画板" → `lark-cli whiteboard +create` +- "在画板上画一个流程图" → `lark-cli docs +whiteboard-update` +- "获取这个画板的内容" → `get_feishu_whiteboard_content` + +**路由说明:** 创建和编辑用 CLI(MCP 不支持写入);读取画板内容 CLI 和 MCP 均可,MCP 返回结构化数据。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Events — 事件订阅 + +**Skill**: `lark-event` — 通过 WebSocket 实时监听飞书事件(消息变更、通讯录变更、日历变更等)。 + +| 命令/工具 | 描述 | +|---|---| +| `lark-cli event` | WebSocket 事件订阅,输出 NDJSON | + +**示例 Prompt:** +- "监听飞书的新消息事件" → `lark-cli event` +- "订阅日历变更事件" → `lark-cli event` + +**路由说明:** CLI only。社区 MCP 不支持事件订阅。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +### Search — 文档搜索 + +跨域搜索飞书文档和知识库内容。 + +**CLI 命令:** + +| 命令 | 描述 | +|---|---| +| `lark-cli doc +search` | 搜索云空间文档(官方接口) | + +**MCP 工具:** + +| 工具 | 描述 | +|---|---| +| `search_feishu_documents` | 搜索文档(社区 MCP) | + +**示例 Prompt:** +- "搜索关于 Q1 的文档" → `lark-cli doc +search` +- "Find documents about onboarding" → `lark-cli doc +search` + +**路由说明:** 优先使用 CLI(`doc +search`),官方接口更可靠。如果 CLI 不可用,使用 MCP(`search_feishu_documents`)。如果此技能不可用,检查:`lark-cli skills list`。 + +--- + +## Additional CLI Skills — 扩展技能 + +以下技能提供高级工作流和 API 探索能力: + +| 技能 | 描述 | +|---|---| +| `lark-openapi-explorer` | 从官方文档库中挖掘未封装的原生 OpenAPI 接口 | +| `lark-skill-maker` | 创建自定义 lark-cli Skill | +| `lark-workflow-meeting-summary` | 汇总会议纪要并生成结构化报告 | +| `lark-workflow-standup-report` | 生成日程 + 未完成任务摘要 | + +--- + +## Overlap Resolution — 重叠能力路由 + +当 CLI 和 MCP 都能完成某个操作时,参考此表选择: + +| Capability | CLI Tool | MCP Tool | Recommended | Reason | +|---|---|---|---|---| +| 文档创建 | `lark-cli doc +create` | `create_feishu_document` | CLI | Markdown 输入更简洁,无需指定 folderToken | +| 文档文本读取 | `lark-cli docs +update` (read) | `get_feishu_document_text` | Depends | 需要纯文本提取用 MCP;需要 Markdown 格式用 CLI | +| Block 编辑/更新 | `lark-cli docs +update` | `update_feishu_block_text` | Depends | 需要指定颜色或对齐方式用 MCP;简单文本替换用 CLI | +| Block 删除 | `lark-cli docs +update` (delete) | `delete_feishu_document_blocks` | Depends | 需要按 block_id 精确删除用 MCP;按位置删除用 CLI | +| 图片上传到文档 | `lark-cli docs +media-insert` | `upload_and_bind_image_to_block` | CLI | CLI 更健壮,错误处理更完善 | +| 文档搜索 | `lark-cli doc +search` | `search_feishu_documents` | CLI | 官方接口,更可靠 | +| Wiki 节点读取 | `lark-cli wiki +list` | `get_feishu_wiki_node_info` | Depends | 需要节点元数据详情用 MCP;浏览知识空间结构用 CLI | +| 画板内容读取 | `lark-cli whiteboard` | `get_feishu_whiteboard_content` | Depends | 需要结构化 JSON 数据用 MCP;需要视觉编辑用 CLI | +| 批量创建 Block | `lark-cli docs +update` (append) | `batch_create_feishu_blocks` | MCP | 原子操作,支持精确格式化(颜色、对齐、类型) | +| 文件夹创建 | `lark-cli drive` | `create_feishu_folder` | CLI | CLI 支持更多文件夹操作 | + +--- + +## Auth Prerequisites — 认证前置条件 + +### CLI 层认证 -### 多维表格 (lark) ```bash -# 创建表格 -mcporter call lark.bitable_v1_app_create --args '{"data":{"name":"项目表"}}' +# 检查认证状态 +lark-cli auth status +# 成功输出:显示当前 App ID、用户身份、token 有效期 +# 失败输出:Not logged in 或 Token expired +``` -# 写入记录 -mcporter call lark.bitable_v1_appTableRecord_create --args '{"path":{"app_token":"xxx","table_id":"xxx"},"data":{"fields":{"标题":"任务1"}}}' +如果未认证: +```bash +lark-cli config init --new # 初始化应用配置 +lark-cli auth login --recommend # OAuth 浏览器登录(端口 3000) ``` -### 搜索 (lark-user) +### 社区 MCP 层认证 + +检查环境变量是否设置: ```bash -# 搜索文档 -mcporter call lark-user.docx_builtin_search --args '{"data":{"search_key":"会议","count":5}}' +echo $FEISHU_APP_ID # 应输出 cli_xxxxxxxx +echo $FEISHU_APP_SECRET # 应输出非空字符串 +``` -# 读取内容 -mcporter call lark-user.docx_v1_document_rawContent --args '{"path":{"document_id":"xxx"}}' +社区 MCP OAuth 使用端口 3333(重定向 URL: `http://localhost:3333/callback`)。 -# 搜索知识库 -mcporter call lark-user.wiki_v1_node_search --args '{"data":{"query":"入职"}}' +### 官方 MCP 层认证(可选) + +```bash +npx -y @larksuiteoapi/lark-mcp login -a "$APP_ID" -s "$APP_SECRET" ``` -## 权限配置 +### Pre-flight Checklist — 操作前检查清单 + +执行任何飞书操作前,按顺序检查: + +1. CLI 已安装:`which lark-cli` 应返回路径 +2. CLI 已认证:`lark-cli auth status` 应显示有效 token +3. CLI 技能已加载:`lark-cli skills list` 应列出所需技能 +4. MCP 环境变量已设置:`FEISHU_APP_ID` 和 `FEISHU_APP_SECRET` 非空 +5. mcporter 已安装:`which mcporter` 应返回路径 + +--- + +## Permissions Reference — 权限参考 + +| Domain | Required Scopes | Optional Scopes | +|---|---|---| +| Documents | `docx:document` | `docx:document:readonly` | +| Cloud Storage | `drive:drive` | `drive:drive:readonly` | +| Wiki | `wiki:wiki` | `wiki:wiki:readonly` | +| Bitable | `bitable:app` | `bitable:app:readonly` | +| Messaging | `im:message` | `im:message:readonly`, `im:chat:readonly` | +| Search | `search:docs:read` | — | +| Calendar | `calendar:calendar` | `calendar:calendar:readonly` | +| Email | `mail:message` | `mail:message:readonly` | +| Contacts | `contact:user.base:readonly` | `contact:department:readonly` | +| Meetings | `vc:meeting:readonly` | — | +| Minutes | `minutes:minute:readonly` | — | +| Tasks | `task:task` | `task:task:readonly` | +| Events | 按需订阅事件类型 | — | + +飞书权限配置地址:`https://open.feishu.cn/app/{APP_ID}/security` + +重定向 URL 配置: +- CLI: `http://localhost:3000/callback` +- 社区 MCP: `http://localhost:3333/callback` + +--- + +## Official MCP (Optional) — 官方 MCP(可选) + +官方 MCP(`@larksuiteoapi/lark-mcp`,Beta)作为高级可选项。默认安装不包含。 + +如果安装了官方 MCP,以下路由可能变化: + +| Capability | Default (CLI) | With Official MCP | +|---|---|---| +| 多维表格操作 | `lark-cli base` | 可用 `bitable_v1_*` 工具 | +| 文档搜索 | `lark-cli doc +search` | 可用 `docx_builtin_search` | +| Wiki 搜索 | `lark-cli wiki +list` | 可用 `wiki_v1_node_search` | + +官方 MCP 提供的主要工具:`bitable_v1_app_create`、`bitable_v1_appTableRecord_create`、`bitable_v1_appTableRecord_search`、`docx_builtin_search`、`docx_v1_document_rawContent`、`wiki_v1_node_search`、`wiki_v2_space_getNode`。 + +如果未安装官方 MCP,决策矩阵正常工作,所有功能通过 CLI + 社区 MCP 覆盖。 + +--- -飞书开放平台开通: -- `docx:document` - 读写文档 -- `drive:drive` - 云空间 -- `wiki:wiki` - 知识库 -- `bitable:app` - 多维表格 -- `search:docs:read` - 搜索 +## MCP-Only Mode — 仅 MCP 模式 -重定向 URL: -- `http://localhost:3000/callback` -- `http://localhost:3333/callback` +如果 CLI 未安装(`setup-v2.sh --mcp-only`),以下能力可用: -## 详细文档 +**可用(MCP):** 文档创建/编辑/读取、Block 操作、文件夹管理、文档搜索、Wiki 节点查询、画板内容读取。 -https://github.com/AlexAnys/feishu-mcp +**不可用(CLI only):** 消息、日历、邮件、任务、通讯录、会议、妙记、电子表格、多维表格、事件订阅、画板编辑、Mermaid 图表。 diff --git a/TROUBLESHOOT-AGENT.md b/TROUBLESHOOT-AGENT.md new file mode 100644 index 0000000..a04a509 --- /dev/null +++ b/TROUBLESHOOT-AGENT.md @@ -0,0 +1,452 @@ +# TROUBLESHOOT-AGENT.md — Feishu Integration Error Recovery Guide + +**Audience**: AI agents diagnosing and recovering from Feishu integration errors. +**Purpose**: Structured error patterns, diagnostic commands, and automated recovery steps. + +When an error occurs, find the matching error pattern below and execute the recovery steps in order. If no pattern matches, run Quick Diagnostics first. + +--- + +## Quick Diagnostics + +Run these commands first to assess system health. Execute all 6 in sequence. + +### Diagnostic 1: CLI installation status + +```bash +which lark-cli && lark-cli --version +``` +- **Healthy**: Returns a path and version number. +- **Unhealthy**: "command not found" → CLI not installed. See E-001. + +### Diagnostic 2: CLI auth status + +```bash +lark-cli auth status +``` +- **Healthy**: Shows App ID, user identity, valid token with future expiry. +- **Unhealthy**: "Not logged in" → See E-002. "Token expired" → See E-001. + +### Diagnostic 3: CLI skills loaded + +```bash +lark-cli skills list 2>/dev/null | head -20 +``` +- **Healthy**: Lists installed skills (e.g., lark-calendar, lark-im, lark-doc). +- **Unhealthy**: Empty list or error → See E-011. + +### Diagnostic 4: MCP environment variables + +```bash +echo "APP_ID: ${FEISHU_APP_ID:-NOT SET}" && echo "SECRET: $([ -n "$FEISHU_APP_SECRET" ] && echo SET || echo NOT SET)" +``` +- **Healthy**: APP_ID shows `cli_xxx`, SECRET shows `SET`. +- **Unhealthy**: Either shows `NOT SET` → See E-010. + +### Diagnostic 5: mcporter configuration + +```bash +which mcporter && mcporter list 2>/dev/null +``` +- **Healthy**: Returns mcporter path and lists configured MCP servers. +- **Unhealthy**: "command not found" → See E-012. No servers listed → See E-010. + +### Diagnostic 6: Network connectivity to Feishu API + +```bash +curl -s -o /dev/null -w "%{http_code}" https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal 2>/dev/null || echo "NETWORK_ERROR" +``` +- **Healthy**: Returns HTTP status code (e.g., `400` for missing body is normal — means API is reachable). +- **Unhealthy**: Returns `NETWORK_ERROR` or no output → See E-006. + +--- + +## Auth Errors + +### E-001: Token expired + +**Pattern**: `token expired` | `token_expired` | `access token is expired` +**Layer**: CLI +**Cause**: OAuth access token has expired (typically after ~2 hours). +**Diagnosis**: +```bash +lark-cli auth status +``` +Confirm output mentions "expired" or shows a past expiry time. +**Recovery**: +1. Run `lark-cli auth login --recommend`. +2. Wait for user to complete OAuth in browser. +3. Run `lark-cli auth status` to verify new token. +**If recovery fails**: Ask the user: "飞书授权页面是否正常打开?请确认浏览器中完成了授权操作。如果页面无法加载,请检查端口 3000 是否被占用(运行 `lsof -i :3000`)。" + +--- + +### E-002: Token missing / not logged in + +**Pattern**: `not logged in` | `no token` | `please login first` | `unauthorized` +**Layer**: CLI +**Cause**: User has never authenticated or auth state was cleared. +**Diagnosis**: +```bash +lark-cli auth status +``` +Confirm output shows "Not logged in" or similar. +**Recovery**: +1. Run `lark-cli config init --new` if no app configuration exists. +2. Run `lark-cli auth login --recommend`. +3. Wait for user to complete OAuth. +4. Run `lark-cli auth status` to confirm. +**If recovery fails**: Ask the user: "请确认你的飞书应用 App ID 和 App Secret 是否正确。可以在 https://open.feishu.cn/app 查看。" + +--- + +### E-003: Invalid App ID or App Secret + +**Pattern**: `invalid app_id` | `invalid app_secret` | `app not found` | `10003` +**Layer**: Both +**Cause**: The App ID or App Secret provided does not match any Feishu application. +**Diagnosis**: +```bash +echo "Current APP_ID: $FEISHU_APP_ID" +lark-cli auth status +``` +Check if APP_ID starts with `cli_` and has the correct format. +**Recovery**: +1. Ask the user to verify their App ID at https://open.feishu.cn/app. +2. If incorrect, re-run `lark-cli config init --new` with the correct credentials. +3. Re-set `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars. +4. Re-authenticate: `lark-cli auth login --recommend`. +**If recovery fails**: Ask the user: "请确认应用已发布(不是草稿状态),并且 App ID 以 cli_ 开头。" + +--- + +### E-004: Insufficient permissions (scope missing) + +**Pattern**: `permission denied` | `scope.*not.*authorized` | `insufficient.*scope` | `10012` | `99991672` +**Layer**: Both +**Cause**: The Feishu application lacks the required permission scope for the requested operation. +**Diagnosis**: +1. Identify the missing scope from the error message. The error usually contains the required scope name. +2. Cross-reference with the permissions table in SKILL.md. +**Recovery**: +1. Identify the required scope from the error message or from this mapping: + - Documents → `docx:document` + - Cloud Storage → `drive:drive` + - Wiki → `wiki:wiki` + - Bitable → `bitable:app` + - Messaging → `im:message` + - Search → `search:docs:read` + - Calendar → `calendar:calendar` + - Email → `mail:message` + - Contacts → `contact:user.base:readonly` + - Meetings → `vc:meeting:readonly` + - Minutes → `minutes:minute:readonly` + - Tasks → `task:task` +2. Direct the user to add the scope: `https://open.feishu.cn/app/{APP_ID}/security`. +3. After adding the scope, the user must re-publish the app version. +4. Re-authenticate: `lark-cli auth login --recommend`. +5. Retry the original command. +**If recovery fails**: Ask the user: "权限已添加但仍报错?请检查是否已重新发布应用版本。在开放平台点击「创建版本」→「发布」。" + +--- + +## Network Errors + +### E-005: Connection refused / timeout + +**Pattern**: `ECONNREFUSED` | `ETIMEDOUT` | `connect ECONNREFUSED` | `request timeout` +**Layer**: Both +**Cause**: Cannot reach Feishu API servers. Network issue, firewall, or proxy. +**Diagnosis**: +```bash +curl -s -o /dev/null -w "%{http_code}" https://open.feishu.cn 2>/dev/null || echo "UNREACHABLE" +``` +If output is "UNREACHABLE", the network cannot reach Feishu. +**Recovery**: +1. Check internet connectivity: `ping -c 3 open.feishu.cn`. +2. If behind a proxy, set HTTP_PROXY and HTTPS_PROXY env vars. +3. If DNS fails, try `curl -s https://223.5.5.5` to test basic connectivity. +4. Retry the original command after network is restored. +**If recovery fails**: Ask the user: "你的网络能否访问 https://open.feishu.cn ?如果在公司网络,可能需要配置代理。" + +--- + +### E-006: Proxy configuration needed + +**Pattern**: `ENOTFOUND` | `getaddrinfo ENOTFOUND` | `proxy.*error` +**Layer**: Both +**Cause**: DNS resolution fails, typically in corporate networks requiring proxy. +**Diagnosis**: +```bash +echo "HTTP_PROXY: ${HTTP_PROXY:-NOT SET}" && echo "HTTPS_PROXY: ${HTTPS_PROXY:-NOT SET}" +curl -s -o /dev/null -w "%{http_code}" https://open.feishu.cn 2>/dev/null || echo "DNS_FAIL" +``` +**Recovery**: +1. If proxy vars are not set and user is on corporate network, ask for proxy URL. +2. Set proxy: `export HTTPS_PROXY="http://proxy.company.com:8080"`. +3. Retry the original command. +4. For npm operations, also set: `npm config set proxy $HTTP_PROXY`. +**If recovery fails**: Ask the user: "请提供公司网络的代理服务器地址(如 http://proxy.company.com:8080)。" + +--- + +## Tool-Specific Errors + +### E-007: Document not found (invalid document_id) + +**Pattern**: `document not found` | `invalid document_id` | `doc.*not.*exist` | `10001` +**Layer**: Both +**Cause**: The document_id does not exist or the user has no access to it. +**Diagnosis**: +1. Verify the document_id format. Feishu document IDs typically start with `doxcn`. +2. If user provided a URL, extract the ID using the pattern: `/docx/([A-Za-z0-9]+)`. +**Recovery**: +1. Confirm the document_id with the user. +2. If a URL was provided, extract the correct token: `https://*.feishu.cn/docx/{document_id}`. +3. Check if the user has access to the document (shared with them or in their drive). +4. Retry with the correct document_id. +**If recovery fails**: Ask the user: "请确认这个文档链接是否正确,以及你是否有权限访问该文档。" + +--- + +### E-008: Block not found (invalid block_id) + +**Pattern**: `block not found` | `invalid block_id` | `block.*not.*exist` +**Layer**: MCP +**Cause**: The block_id does not exist in the specified document, or the document structure changed. +**Diagnosis**: +```bash +mcporter call feishu.get_feishu_document_blocks --args '{"document_id":"THE_DOC_ID"}' +``` +List all blocks and verify the target block_id exists. +**Recovery**: +1. Fetch the current block structure: `get_feishu_document_blocks`. +2. Find the correct block_id from the returned structure. +3. Retry the operation with the correct block_id. +**If recovery fails**: Retry after 5 seconds — the document may have been concurrently edited and block IDs may have changed. + +--- + +### E-009: Folder access denied + +**Pattern**: `folder.*denied` | `no permission.*folder` | `folder.*forbidden` +**Layer**: Both +**Cause**: The user does not have permission to access the specified folder. +**Diagnosis**: +1. Check if `drive:drive` scope is authorized. +2. Check if the folder is shared with the user. +**Recovery**: +1. Verify `drive:drive` scope is enabled at `https://open.feishu.cn/app/{APP_ID}/security`. +2. Ask the user to check if the folder is shared with their account. +3. If using tenant auth, the app may not have folder access — switch to user auth. +4. Retry the operation. +**If recovery fails**: Ask the user: "请确认你是否有权限访问此文件夹。可以在飞书云空间中查看文件夹的共享设置。" + +--- + +### E-010: Rate limiting / throttle + +**Pattern**: `rate limit` | `too many requests` | `429` | `frequency limit` +**Layer**: Both +**Cause**: Too many API calls in a short time. Feishu enforces per-app rate limits. +**Diagnosis**: Check if the error includes a retry-after header or time. +**Recovery**: +1. Wait 60 seconds. +2. Retry the original command. +3. If rate-limited again, wait 5 minutes and retry. +4. If still failing, reduce request frequency. Batch operations where possible (use `batch_create_feishu_blocks` instead of individual block calls). +**If recovery fails**: Wait 15 minutes and retry. Rate limits typically reset within this window. + +--- + +## Setup Errors + +### E-011: CLI not installed + +**Pattern**: `command not found: lark-cli` | `lark-cli.*not found` +**Layer**: CLI +**Cause**: The Feishu CLI package is not installed globally. +**Diagnosis**: +```bash +which lark-cli || echo "NOT INSTALLED" +npm list -g @larksuite/cli 2>/dev/null || echo "NOT IN NPM" +``` +**Recovery**: +1. Run `npm install -g @larksuite/cli`. +2. Run `npx skills add larksuite/cli -y -g`. +3. Verify: `lark-cli --version`. +**If recovery fails**: Check npm global directory permissions. Run `npm config get prefix` to find the global dir. If permissions are wrong, fix with `sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}`. + +--- + +### E-012: MCP not configured (mcporter config missing) + +**Pattern**: `mcporter.*not found` | `no.*mcp.*configured` | `ENOENT.*mcporter` +**Layer**: MCP +**Cause**: mcporter is not installed or MCP server configuration is missing. +**Diagnosis**: +```bash +which mcporter || echo "NOT INSTALLED" +mcporter list 2>/dev/null || echo "NO CONFIG" +``` +**Recovery**: +1. Install mcporter: `npm install -g mcporter`. +2. Check if `FEISHU_APP_ID` and `FEISHU_APP_SECRET` are set. +3. If not set, ask the user for their App ID and App Secret. +4. Configure mcporter with the community MCP server. +5. Verify: `mcporter list`. +**If recovery fails**: Fall back to direct npx invocation: `npx -y feishu-mcp@latest --stdio`. + +--- + +### E-013: Skills not loaded + +**Pattern**: `skill not found` | `unknown skill` | `no such command` +**Layer**: CLI +**Cause**: CLI skills have not been installed or loaded. +**Diagnosis**: +```bash +lark-cli skills list 2>/dev/null | head -10 +``` +If output is empty or missing expected skills. +**Recovery**: +1. Run `npx skills add larksuite/cli -y -g`. +2. Wait for installation to complete. +3. Verify: `lark-cli skills list`. +4. Retry the original command. +**If recovery fails**: Retry once more. If still failing, ask the user: "CLI 技能安装失败。请检查网络连接后手动运行:`npx skills add larksuite/cli -y -g`。" + +--- + +### E-014: Port already in use (OAuth) + +**Pattern**: `EADDRINUSE` | `port.*in use` | `address already in use` +**Layer**: Both +**Cause**: Port 3000 (CLI OAuth) or 3333 (MCP OAuth) is occupied by another process. +**Diagnosis**: +```bash +lsof -i :3000 2>/dev/null | head -5 +lsof -i :3333 2>/dev/null | head -5 +``` +**Recovery**: +1. Identify the process using the port from the `lsof` output. +2. If the process is not critical, kill it: `kill -9 {PID}`. +3. Retry the auth command. +**If recovery fails**: Ask the user: "端口 3000 或 3333 被其他程序占用。请关闭占用端口的程序后重试。" + +--- + +## Data Errors + +### E-015: Invalid JSON in request + +**Pattern**: `invalid json` | `JSON.*parse.*error` | `unexpected token` | `SyntaxError.*JSON` +**Layer**: MCP +**Cause**: The request body contains malformed JSON. +**Diagnosis**: Review the JSON string passed to the MCP tool call. Check for unescaped quotes, missing commas, or trailing commas. +**Recovery**: +1. Validate the JSON with `echo '...' | python3 -m json.tool` or `echo '...' | node -e "JSON.parse(require('fs').readFileSync(0))"`. +2. Fix the JSON syntax error. +3. Retry with corrected JSON. +**If recovery fails**: Simplify the request to minimal parameters and add fields incrementally. + +--- + +### E-016: Required parameter missing + +**Pattern**: `required.*parameter` | `missing.*field` | `field.*required` | `parameter.*missing` +**Layer**: MCP +**Cause**: A required parameter was not provided in the tool call. +**Diagnosis**: Read the error message to identify which parameter is missing. Cross-reference with the tool parameter list in AGENTS.md. +**Recovery**: +1. Identify the missing parameter from the error message. +2. Check AGENTS.md for the tool's required parameters. +3. Add the missing parameter to the request. +4. Retry. +**If recovery fails**: Consult AGENTS.md tool inventory for the complete parameter list of the tool. + +--- + +### E-017: Document ID format error + +**Pattern**: `invalid.*token` | `malformed.*id` | `document_id.*format` +**Layer**: Both +**Cause**: The document/folder/wiki token does not match the expected format. +**Diagnosis**: Feishu tokens have specific prefixes: +- Document: typically `doxcn...` +- Spreadsheet: typically contains alphanumeric chars +- Wiki: typically `wikcn...` +- Folder: typically `fldcn...` +**Recovery**: +1. If the user provided a full URL, extract the token using patterns from AGENTS.md "Extracting IDs from Feishu URLs" section. +2. Verify the extracted token format. +3. Retry with the correct token. +**If recovery fails**: Ask the user: "请提供完整的飞书文档链接,我来提取正确的 token。" + +--- + +## Permission Error Handling — Scope Reference + +When a permission error occurs, use this section to identify and resolve the missing scope. + +### Identifying the missing scope + +1. Read the error message. Feishu permission errors typically include the required scope name or an error code. +2. Common error codes for permission issues: `10012`, `99991672`, `99991663`. +3. Map the operation domain to the required scope: + +| Domain | Required Scope | Error Hint | +|---|---|---| +| Documents | `docx:document` | "docx" in error | +| Cloud Storage | `drive:drive` | "drive" in error | +| Wiki | `wiki:wiki` | "wiki" in error | +| Bitable | `bitable:app` | "bitable" in error | +| Messaging | `im:message` | "im" or "message" in error | +| Search | `search:docs:read` | "search" in error | +| Calendar | `calendar:calendar` | "calendar" in error | +| Email | `mail:message` | "mail" in error | +| Contacts | `contact:user.base:readonly` | "contact" in error | +| Meetings | `vc:meeting:readonly` | "vc" or "meeting" in error | +| Minutes | `minutes:minute:readonly` | "minutes" in error | +| Tasks | `task:task` | "task" in error | + +### Resolution procedure + +1. Identify the missing scope from the table above. +2. Direct the user to the permissions page: `https://open.feishu.cn/app/{APP_ID}/security`. +3. Instruct the user to search for and enable the required scope. +4. After adding the scope, the user must create a new app version and publish it. +5. Re-authenticate: `lark-cli auth login --recommend`. +6. Retry the original operation. + +### Scope activation check + +Some scopes require admin approval. If the user adds a scope but still gets permission errors: + +1. Check if the scope status is "已开通" (activated) vs "审核中" (pending approval). +2. If pending, the user must wait for admin approval or ask their Feishu workspace admin to approve. +3. Direct the user to contact their admin with the specific scope name. + +--- + +## Escalation Summary + +| Error | Can Auto-Recover? | Human Action Required | +|---|---|---| +| E-001 Token expired | Yes (re-login) | User approves OAuth in browser | +| E-002 Not logged in | Yes (login) | User approves OAuth in browser | +| E-003 Invalid credentials | No | User verifies App ID/Secret | +| E-004 Missing scope | No | User adds scope in Feishu console | +| E-005 Network timeout | Yes (retry) | None if network recovers | +| E-006 Proxy needed | No | User provides proxy URL | +| E-007 Doc not found | Partial (URL extraction) | User confirms doc access | +| E-008 Block not found | Yes (re-fetch blocks) | None | +| E-009 Folder denied | No | User checks folder sharing | +| E-010 Rate limited | Yes (wait + retry) | None | +| E-011 CLI not installed | Yes (npm install) | None | +| E-012 MCP not configured | Yes (install + configure) | User provides credentials if missing | +| E-013 Skills not loaded | Yes (npx skills add) | None | +| E-014 Port in use | Partial (kill process) | User closes conflicting app | +| E-015 Invalid JSON | Yes (fix JSON) | None | +| E-016 Missing parameter | Yes (add parameter) | None | +| E-017 ID format error | Yes (extract from URL) | User provides URL if ID unknown | diff --git a/configs/claude-code.json b/configs/claude-code.json new file mode 100644 index 0000000..4144cc8 --- /dev/null +++ b/configs/claude-code.json @@ -0,0 +1,18 @@ +{ + "_comment": "Claude Code MCP 配置 — 飞书全能集成套件 (feishu-mcp v2)", + "_comment_usage": "将此文件放置到 ~/.claude/ 目录,或通过 Claude Code 的 MCP 设置导入", + "_comment_credentials": "FEISHU_APP_ID 和 FEISHU_APP_SECRET 请在 open.feishu.cn 创建应用后获取", + "_comment_auth_type": "user 表示用户身份授权,首次使用时会自动引导 OAuth 登录", + "mcpServers": { + "feishu": { + "_comment": "社区版 feishu-mcp — 文档创建/编辑/图表/图片,17 个精细化文档编辑工具", + "command": "npx", + "args": ["-y", "feishu-mcp@latest", "--stdio"], + "env": { + "FEISHU_APP_ID": "", + "FEISHU_APP_SECRET": "", + "FEISHU_AUTH_TYPE": "user" + } + } + } +} diff --git a/configs/cursor.json b/configs/cursor.json new file mode 100644 index 0000000..0d26058 --- /dev/null +++ b/configs/cursor.json @@ -0,0 +1,18 @@ +{ + "_comment": "Cursor MCP 配置 — 飞书全能集成套件 (feishu-mcp v2)", + "_comment_usage": "将此文件放置到 ~/.cursor/mcp.json,Cursor 会自动加载 MCP 服务", + "_comment_credentials": "FEISHU_APP_ID 和 FEISHU_APP_SECRET 请在 open.feishu.cn 创建应用后获取", + "_comment_auth_type": "user 表示用户身份授权,首次使用时会自动引导 OAuth 登录", + "mcpServers": { + "feishu": { + "_comment": "社区版 feishu-mcp — 文档创建/编辑/图表/图片,17 个精细化文档编辑工具", + "command": "npx", + "args": ["-y", "feishu-mcp@latest", "--stdio"], + "env": { + "FEISHU_APP_ID": "", + "FEISHU_APP_SECRET": "", + "FEISHU_AUTH_TYPE": "user" + } + } + } +} diff --git a/configs/openclaw.json b/configs/openclaw.json new file mode 100644 index 0000000..be8cf8b --- /dev/null +++ b/configs/openclaw.json @@ -0,0 +1,18 @@ +{ + "_comment": "OpenClaw MCP 配置 — 飞书全能集成套件 (feishu-mcp v2)", + "_comment_usage": "将此文件内容导入 OpenClaw 的 MCP 配置,或放置到 OpenClaw 配置目录中", + "_comment_credentials": "FEISHU_APP_ID 和 FEISHU_APP_SECRET 请在 open.feishu.cn 创建应用后获取", + "_comment_auth_type": "user 表示用户身份授权,首次使用时会自动引导 OAuth 登录", + "mcpServers": { + "feishu": { + "_comment": "社区版 feishu-mcp — 文档创建/编辑/图表/图片,17 个精细化文档编辑工具", + "command": "npx", + "args": ["-y", "feishu-mcp@latest", "--stdio"], + "env": { + "FEISHU_APP_ID": "", + "FEISHU_APP_SECRET": "", + "FEISHU_AUTH_TYPE": "user" + } + } + } +} diff --git a/setup-v2.sh b/setup-v2.sh new file mode 100755 index 0000000..87699d1 --- /dev/null +++ b/setup-v2.sh @@ -0,0 +1,1022 @@ +#!/usr/bin/env bash +# setup-v2.sh — Feishu MCP v2 smart setup script +# Installs and configures Feishu CLI + community MCP + optional official MCP. +# Detects AI platforms (OpenClaw, Claude Code, Cursor) and generates configs. +# All user-facing output is in Chinese. Code comments in English. + +set -euo pipefail + +# ============================================================ +# Constants +# ============================================================ + +SETUP_VERSION="2.0.0" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +MIN_NODE_VERSION=16 + +# Flags (defaults) +FLAG_FORCE=false +FLAG_MCP_ONLY=false +FLAG_NO_INTERACTIVE=false +FLAG_HELP=false +FLAG_VERSION=false +FLAG_PLATFORM="" + +# State tracking +CLI_INSTALLED=false +CLI_VERSION="" +MCPORTER_CONFIGURED=false +OFFICIAL_MCP_CONFIGURED=false +DETECTED_PLATFORMS="" + +# Credentials (will be set during execution) +APP_ID="" +APP_SECRET="" + +# ============================================================ +# Trap: friendly error handler on unexpected failures +# ============================================================ + +cleanup_on_error() { + local exit_code=$? + # Exit code 130 = Ctrl+C — trap_ctrlc already printed a message + if [ "$exit_code" -ne 0 ] && [ "$exit_code" -ne 130 ]; then + echo "" + echo "❌ 脚本遇到意外错误 (退出码: $exit_code)" + echo " 请检查上方的错误信息,或重新运行脚本" + echo " 如需帮助: ./setup-v2.sh --help" + fi +} +trap cleanup_on_error EXIT + +# Trap Ctrl+C during auth to give a helpful message +trap_ctrlc() { + echo "" + echo "⚠️ 操作已中断" + echo " 可稍后手动完成认证:" + echo " lark-cli auth login --recommend" + exit 130 +} + +# ============================================================ +# Helper functions +# ============================================================ + +# Print usage/help in Chinese +print_help() { + cat <<'HELPEOF' +飞书 MCP v2 安装脚本 + +用法: + ./setup-v2.sh [App_ID] [App_Secret] [选项] + +参数: + App_ID 飞书应用 App ID (可选,不提供则交互式输入) + App_Secret 飞书应用 App Secret (可选,不提供则交互式输入) + +选项: + -h, --help 显示此帮助信息 + -v, --version 显示脚本版本 + --force 强制重新执行所有步骤(忽略已有配置) + --mcp-only 仅安装社区 MCP,跳过 CLI 安装 + --no-interactive 非交互模式(需通过参数提供凭证,CI/自动化使用) + --platform 手动指定目标平台 (openclaw / claude-code / cursor) + +示例: + # 交互式安装(推荐) + ./setup-v2.sh + + # 非交互式安装 + ./setup-v2.sh cli_abcd1234 your_secret_here + + # 仅安装社区 MCP(不安装 CLI) + ./setup-v2.sh --mcp-only + + # 强制重新配置 + ./setup-v2.sh --force + +获取凭证: https://open.feishu.cn +项目文档: https://github.com/AlexAnys/feishu-mcp +HELPEOF +} + +# Trim leading/trailing whitespace (Bash 3.2 compatible) +trim() { + local var="$1" + # Remove leading whitespace + var="${var#"${var%%[![:space:]]*}"}" + # Remove trailing whitespace + var="${var%"${var##*[![:space:]]}"}" + printf '%s' "$var" +} + +# Get mcporter config path following XDG convention +get_mcporter_config_path() { + if [ -n "${XDG_CONFIG_HOME:-}" ]; then + echo "${XDG_CONFIG_HOME}/mcporter/config.json" + else + echo "${HOME}/.config/mcporter/config.json" + fi +} + +# Check if a previous successful setup exists (for idempotency) +has_existing_config() { + local config_path + config_path="$(get_mcporter_config_path)" + if [ -f "$config_path" ]; then + # Check if the file contains a feishu entry with non-empty credentials + FEISHU_CONFIG_PATH="$config_path" node -e " + var fs = require('fs'); + try { + var c = JSON.parse(fs.readFileSync(process.env.FEISHU_CONFIG_PATH, 'utf8')); + if (c.mcpServers && c.mcpServers.feishu && + c.mcpServers.feishu.env && + c.mcpServers.feishu.env.FEISHU_APP_ID && + c.mcpServers.feishu.env.FEISHU_APP_ID !== '') { + process.exit(0); + } + } catch(e) {} + process.exit(1); + " 2>/dev/null + return $? + fi + return 1 +} + +# Read existing credentials from mcporter config +read_existing_credentials() { + local config_path + config_path="$(get_mcporter_config_path)" + if [ -f "$config_path" ]; then + FEISHU_CONFIG_PATH="$config_path" node -e " + var fs = require('fs'); + try { + var c = JSON.parse(fs.readFileSync(process.env.FEISHU_CONFIG_PATH, 'utf8')); + if (c.mcpServers && c.mcpServers.feishu && c.mcpServers.feishu.env) { + console.log(c.mcpServers.feishu.env.FEISHU_APP_ID || ''); + console.log(c.mcpServers.feishu.env.FEISHU_APP_SECRET || ''); + } else { + console.log(''); + console.log(''); + } + } catch(e) { + console.log(''); + console.log(''); + } + " 2>/dev/null + fi +} + +# ============================================================ +# Parse command-line arguments (Bash 3.2 compatible) +# ============================================================ + +POSITIONAL_ARGS="" +POSITIONAL_COUNT=0 + +while [ $# -gt 0 ]; do + case "$1" in + -h|--help) + FLAG_HELP=true + shift + ;; + -v|--version) + FLAG_VERSION=true + shift + ;; + --force) + FLAG_FORCE=true + shift + ;; + --mcp-only) + FLAG_MCP_ONLY=true + shift + ;; + --no-interactive) + FLAG_NO_INTERACTIVE=true + shift + ;; + --platform) + if [ -n "${2:-}" ]; then + FLAG_PLATFORM="$2" + shift 2 + else + echo "❌ --platform 需要指定平台名称 (openclaw / claude-code / cursor)" + exit 1 + fi + ;; + -*) + echo "❌ 未知选项: $1" + echo " 使用 --help 查看所有选项" + exit 1 + ;; + *) + # Positional argument + POSITIONAL_COUNT=$((POSITIONAL_COUNT + 1)) + if [ "$POSITIONAL_COUNT" -eq 1 ]; then + APP_ID="$1" + elif [ "$POSITIONAL_COUNT" -eq 2 ]; then + APP_SECRET="$1" + fi + shift + ;; + esac +done + +# Handle --help and --version early exits +if [ "$FLAG_HELP" = true ]; then + print_help + exit 0 +fi + +if [ "$FLAG_VERSION" = true ]; then + echo "feishu-mcp setup v${SETUP_VERSION}" + exit 0 +fi + +# ============================================================ +# Banner +# ============================================================ + +echo "" +echo "🚀 飞书 MCP v2 智能配置向导 (v${SETUP_VERSION})" +echo " CLI 全能管理 + 社区 MCP 精细文档编辑" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "" + +# ============================================================ +# Step 1: Prerequisites check (AC-1.1.1, E-5) +# ============================================================ + +echo "📋 [1/7] 检查环境..." +echo "" + +# Detect OS and architecture +DETECTED_OS="$(uname -s | tr '[:upper:]' '[:lower:]')" +DETECTED_ARCH="$(uname -m)" + +case "$DETECTED_OS" in + darwin) + OS_DISPLAY="macOS" + ;; + linux) + OS_DISPLAY="Linux" + ;; + mingw*|msys*|cygwin*) + echo "❌ 不支持 Windows 原生环境" + echo " 请使用 WSL (Windows Subsystem for Linux) 运行此脚本" + echo " 安装 WSL: https://learn.microsoft.com/zh-cn/windows/wsl/install" + exit 1 + ;; + *) + echo "❌ 不支持的操作系统: ${DETECTED_OS}" + echo " 此脚本支持 macOS 和 Linux" + exit 1 + ;; +esac + +case "$DETECTED_ARCH" in + x86_64|amd64) + ARCH_DISPLAY="x64" + ;; + arm64|aarch64) + ARCH_DISPLAY="arm64" + ;; + *) + ARCH_DISPLAY="$DETECTED_ARCH" + ;; +esac + +echo " 系统: ${OS_DISPLAY} (${ARCH_DISPLAY})" + +# Check Node.js +if ! command -v node >/dev/null 2>&1; then + echo "" + echo "❌ 未检测到 Node.js" + echo " 请先安装 Node.js (>= ${MIN_NODE_VERSION}):" + echo " 下载地址: https://nodejs.org" + echo "" + echo " macOS 推荐: brew install node" + echo " Linux 推荐: https://github.com/nodesource/distributions" + exit 1 +fi + +NODE_VERSION_FULL="$(node --version 2>/dev/null)" +# Extract major version number (strip 'v' prefix, get first segment) +NODE_MAJOR="$(echo "$NODE_VERSION_FULL" | sed 's/^v//' | cut -d. -f1)" + +if [ "$NODE_MAJOR" -lt "$MIN_NODE_VERSION" ] 2>/dev/null; then + echo "" + echo "❌ Node.js 版本过低: ${NODE_VERSION_FULL}" + echo " 最低要求: v${MIN_NODE_VERSION}.0.0" + echo " 请升级 Node.js: https://nodejs.org" + echo "" + echo " macOS: brew upgrade node" + echo " nvm 用户: nvm install --lts" + exit 1 +fi + +echo " Node.js: ${NODE_VERSION_FULL}" + +# Check npm +if ! command -v npm >/dev/null 2>&1; then + echo "" + echo "❌ 未检测到 npm" + echo " Node.js 已安装但缺少 npm,请重新安装 Node.js:" + echo " https://nodejs.org" + exit 1 +fi + +NPM_VERSION="$(npm --version 2>/dev/null)" +echo " npm: v${NPM_VERSION}" +echo "" + +# ============================================================ +# Step 2: Credentials (AC-1.1.2, E-6) +# ============================================================ + +echo "📋 [2/7] 获取应用凭证..." +echo "" + +# Idempotency: if config exists and not --force, reuse credentials +if [ "$FLAG_FORCE" = false ] && has_existing_config 2>/dev/null; then + echo " ✅ 检测到已有配置,使用现有凭证" + EXISTING_CREDS="$(read_existing_credentials)" + EXISTING_ID="$(echo "$EXISTING_CREDS" | head -1)" + EXISTING_SECRET="$(echo "$EXISTING_CREDS" | tail -1)" + + # If positional args provided, use them instead + if [ -n "$APP_ID" ] && [ -n "$APP_SECRET" ]; then + echo " 📝 使用命令行提供的新凭证" + elif [ -n "$EXISTING_ID" ] && [ -n "$EXISTING_SECRET" ]; then + APP_ID="$EXISTING_ID" + APP_SECRET="$EXISTING_SECRET" + echo " App ID: ${APP_ID}" + echo "" + fi +else + # Need credentials + if [ -z "$APP_ID" ] || [ -z "$APP_SECRET" ]; then + if [ "$FLAG_NO_INTERACTIVE" = true ]; then + echo "❌ 非交互模式下必须提供 App ID 和 App Secret" + echo " 用法: ./setup-v2.sh --no-interactive" + exit 1 + fi + + echo " 请输入飞书应用凭证(在 open.feishu.cn 创建应用后获取)" + echo "" + + if [ -z "$APP_ID" ]; then + printf " App ID (cli_xxx): " + read -r APP_ID + fi + if [ -z "$APP_SECRET" ]; then + printf " App Secret (输入不显示): " + # Suppress echo for secret input; handle terminals that don't support -s + if stty -echo 2>/dev/null; then + read -r APP_SECRET + stty echo + echo "" + else + read -r APP_SECRET + fi + fi + fi +fi + +# Trim whitespace from credentials +APP_ID="$(trim "$APP_ID")" +APP_SECRET="$(trim "$APP_SECRET")" + +# Validate credentials are non-empty +if [ -z "$APP_ID" ] || [ -z "$APP_SECRET" ]; then + echo "" + echo "❌ App ID 或 App Secret 不能为空" + echo " 请在飞书开放平台获取: https://open.feishu.cn" + exit 1 +fi + +# Warn if App ID doesn't start with cli_ (don't block -- format may change) +case "$APP_ID" in + cli_*) + ;; + *) + echo " ⚠️ App ID 通常以 'cli_' 开头,当前值: ${APP_ID}" + echo " 如果确认无误请继续,否则请检查" + echo "" + ;; +esac + +# ============================================================ +# Step 3: Feishu CLI installation (AC-1.1.3, E-3) +# ============================================================ + +echo "📋 [3/7] 安装飞书 CLI..." +echo "" + +if [ "$FLAG_MCP_ONLY" = true ]; then + echo " ⏭️ 已跳过 CLI 安装 (--mcp-only 模式)" + echo "" + CLI_INSTALLED=false +else + # Check if CLI is already installed + if command -v lark-cli >/dev/null 2>&1; then + CLI_VERSION="$(lark-cli --version 2>/dev/null || echo "unknown")" + echo " ✅ 飞书 CLI 已安装: ${CLI_VERSION}" + CLI_INSTALLED=true + if [ "$FLAG_FORCE" = false ]; then + echo " ⏭️ 跳过重新安装(使用 --force 强制重新安装)" + else + echo " 🔄 强制重新安装..." + if npm install -g @larksuite/cli 2>/tmp/feishu-cli-install-err.log; then + CLI_VERSION="$(lark-cli --version 2>/dev/null || echo "unknown")" + echo " ✅ 飞书 CLI 已更新: ${CLI_VERSION}" + else + echo " ⚠️ CLI 更新失败,继续使用现有版本" + fi + fi + else + echo " 📦 正在安装 @larksuite/cli..." + if npm install -g @larksuite/cli 2>/tmp/feishu-cli-install-err.log; then + CLI_VERSION="$(lark-cli --version 2>/dev/null || echo "unknown")" + echo " ✅ 飞书 CLI 安装成功: ${CLI_VERSION}" + CLI_INSTALLED=true + else + # Graceful degradation: CLI install failed, continue with MCP-only + CLI_INSTALLED=false + INSTALL_ERR="$(cat /tmp/feishu-cli-install-err.log 2>/dev/null || echo "")" + + echo " ⚠️ 飞书 CLI 安装失败,将以 MCP-only 模式继续" + echo "" + + # Detect specific error types and provide targeted advice + case "$INSTALL_ERR" in + *EACCES*|*permission*) + echo " 💡 权限不足。请运行以下命令修复 npm 全局安装路径:" + echo " npm config set prefix '~/.npm-global'" + echo " export PATH=~/.npm-global/bin:\$PATH" + echo " # 添加到 ~/.bashrc 或 ~/.zshrc 以永久生效" + ;; + *ENOTFOUND*|*EAI_AGAIN*|*network*|*ETIMEDOUT*) + echo " 💡 网络连接失败。请检查:" + echo " - 网络连接是否正常" + echo " - 是否需要配置代理: npm config set proxy " + if [ -z "${HTTP_PROXY:-}${HTTPS_PROXY:-}${http_proxy:-}${https_proxy:-}" ]; then + echo " - 未检测到代理环境变量,如需代理请设置 HTTPS_PROXY" + fi + ;; + *404*|*E404*) + echo " 💡 npm 包可能尚未发布或名称已变更" + echo " 飞书 CLI 是新发布的工具,如遇此问题请稍后重试" + ;; + *) + echo " 💡 安装失败原因:" + echo " $(echo "$INSTALL_ERR" | head -3)" + ;; + esac + echo "" + echo " 📝 MCP-only 模式仍可使用文档编辑等核心功能" + echo "" + fi + fi + + # Install CLI skills (only if CLI was successfully installed) + if [ "$CLI_INSTALLED" = true ]; then + echo " 📦 安装 CLI 技能包..." + if npx skills add larksuite/cli -y -g 2>/dev/null; then + echo " ✅ CLI 技能包安装成功" + else + echo " ⚠️ CLI 技能包安装失败(非关键,可稍后手动安装)" + echo " 手动安装: npx skills add larksuite/cli -y -g" + fi + fi + echo "" +fi + +# ============================================================ +# Step 4: Community MCP via mcporter (AC-1.1.4, E-7) +# ============================================================ + +echo "📋 [4/7] 配置社区 MCP (feishu-mcp)..." +echo "" + +# Install mcporter if not present +if ! command -v mcporter >/dev/null 2>&1; then + echo " 📦 安装 mcporter..." + if npm install -g mcporter 2>/tmp/feishu-mcporter-err.log; then + echo " ✅ mcporter 安装成功" + else + MCPORTER_ERR="$(cat /tmp/feishu-mcporter-err.log 2>/dev/null || echo "")" + case "$MCPORTER_ERR" in + *EACCES*|*permission*) + echo " ❌ mcporter 安装失败 — 权限不足" + echo " 请运行: npm config set prefix '~/.npm-global'" + echo " 然后重新运行此脚本" + ;; + *ENOTFOUND*|*EAI_AGAIN*|*ETIMEDOUT*) + echo " ❌ mcporter 安装失败 — 网络错误" + echo " 请检查网络连接后重试" + if [ -z "${HTTP_PROXY:-}${HTTPS_PROXY:-}${http_proxy:-}${https_proxy:-}" ]; then + echo " 如需代理请设置: export HTTPS_PROXY=" + fi + ;; + *) + echo " ❌ mcporter 安装失败" + echo " $(echo "$MCPORTER_ERR" | head -3)" + ;; + esac + echo "" + echo " 手动安装: npm install -g mcporter" + exit 1 + fi +else + echo " ✅ mcporter 已安装" +fi + +# Generate/merge mcporter config +MCPORTER_CONFIG="$(get_mcporter_config_path)" +MCPORTER_CONFIG_DIR="$(dirname "$MCPORTER_CONFIG")" + +# Ensure config directory exists +mkdir -p "$MCPORTER_CONFIG_DIR" + +# Use inline Node.js to safely read/merge/write JSON config (v1 pattern) +# Credentials passed via environment variables to avoid injection (HIGH-1) +NODE_ERR_FILE="$(mktemp /tmp/feishu-node-err.XXXXXX)" +if FEISHU_APP_ID="$APP_ID" FEISHU_APP_SECRET="$APP_SECRET" \ + FEISHU_CONFIG_PATH="$MCPORTER_CONFIG" node -e " +var fs = require('fs'); +var configPath = process.env.FEISHU_CONFIG_PATH; +var appId = process.env.FEISHU_APP_ID; +var appSecret = process.env.FEISHU_APP_SECRET; + +var config = {}; + +// Read existing config if present +if (fs.existsSync(configPath)) { + try { + config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + } catch(e) { + // E-7: Malformed JSON — back up and start fresh + var timestamp = Date.now(); + var backupPath = configPath + '.bak.' + timestamp; + fs.renameSync(configPath, backupPath); + console.log(' ⚠️ 现有配置文件格式错误,已备份到: ' + backupPath); + config = {}; + } +} + +if (!config.mcpServers) config.mcpServers = {}; + +// Add/update community MCP entry (preserves other entries) +config.mcpServers.feishu = { + command: 'npx', + args: ['-y', 'feishu-mcp@latest', '--stdio'], + env: { + FEISHU_APP_ID: appId, + FEISHU_APP_SECRET: appSecret, + FEISHU_AUTH_TYPE: 'user' + } +}; + +fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); +console.log(' ✅ 社区 MCP 配置已写入: ' + configPath); +" 2>"$NODE_ERR_FILE"; then + : +else + echo " ❌ 社区 MCP 配置写入失败" + if [ -s "$NODE_ERR_FILE" ]; then + echo " 错误详情: $(head -3 "$NODE_ERR_FILE")" + fi + echo " 请检查文件权限后重试: ${MCPORTER_CONFIG}" + rm -f "$NODE_ERR_FILE" + exit 1 +fi +rm -f "$NODE_ERR_FILE" + +MCPORTER_CONFIGURED=true +echo "" + +# ============================================================ +# Step 5: Official MCP (optional) (AC-1.1.5) +# ============================================================ + +echo "📋 [5/7] 官方 MCP (可选)..." +echo "" + +INSTALL_OFFICIAL=false + +if [ "$FLAG_NO_INTERACTIVE" = true ]; then + echo " ⏭️ 非交互模式,跳过官方 MCP" + echo " 稍后安装: npx -y @larksuiteoapi/lark-mcp login -a -s " +else + printf " 是否安装官方 lark-mcp?(多维表格/搜索/知识库能力) [y/N]: " + read -r OFFICIAL_ANSWER || true + OFFICIAL_ANSWER="$(trim "${OFFICIAL_ANSWER:-N}")" + + case "$OFFICIAL_ANSWER" in + y|Y|yes|YES|是) + INSTALL_OFFICIAL=true + ;; + *) + INSTALL_OFFICIAL=false + ;; + esac +fi + +if [ "$INSTALL_OFFICIAL" = true ]; then + echo "" + echo " 📦 添加官方 MCP 配置..." + + # Add official MCP entries to mcporter config + # Credentials passed via environment variables to avoid injection (HIGH-1) + NODE_ERR_FILE="$(mktemp /tmp/feishu-node-err.XXXXXX)" + if FEISHU_APP_ID="$APP_ID" FEISHU_APP_SECRET="$APP_SECRET" \ + FEISHU_CONFIG_PATH="$MCPORTER_CONFIG" node -e " + var fs = require('fs'); + var configPath = process.env.FEISHU_CONFIG_PATH; + var appId = process.env.FEISHU_APP_ID; + var appSecret = process.env.FEISHU_APP_SECRET; + + var config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + if (!config.mcpServers) config.mcpServers = {}; + + // Official lark-mcp — app identity (bitable, messaging) + config.mcpServers.lark = { + command: 'npx', + args: ['-y', '@larksuiteoapi/lark-mcp', 'mcp', '-a', appId, '-s', appSecret] + }; + + // Official lark-mcp — user identity (search, wiki) + config.mcpServers['lark-user'] = { + command: 'npx', + args: ['-y', '@larksuiteoapi/lark-mcp', 'mcp', '-a', appId, '-s', appSecret, + '--oauth', '--token-mode', 'user_access_token'] + }; + + fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); + console.log(' ✅ 官方 MCP 配置已添加'); + " 2>"$NODE_ERR_FILE"; then + : + else + echo " ❌ 官方 MCP 配置写入失败" + if [ -s "$NODE_ERR_FILE" ]; then + echo " 错误详情: $(head -3 "$NODE_ERR_FILE")" + fi + echo " 请手动添加: npx -y @larksuiteoapi/lark-mcp login -a -s " + fi + rm -f "$NODE_ERR_FILE" + + echo " 🔑 正在进行官方 MCP 授权..." + npx -y @larksuiteoapi/lark-mcp login -a "$APP_ID" -s "$APP_SECRET" || echo " ⚠️ 官方 MCP 授权跳过(可稍后手动完成: npx -y @larksuiteoapi/lark-mcp login)" + + OFFICIAL_MCP_CONFIGURED=true +else + echo " ⏭️ 跳过官方 MCP" + echo " 稍后安装: 重新运行此脚本,或手动添加到 mcporter 配置" +fi + +echo "" + +# ============================================================ +# Step 6: Auth configuration (AC-1.1.6, E-10) +# ============================================================ + +echo "📋 [6/7] 认证配置..." +echo "" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "🔐 请在飞书开放平台配置重定向 URL" +echo "" +echo " 打开: https://open.feishu.cn/app/${APP_ID}/safe" +echo "" +echo " 添加以下重定向 URL:" + +if [ "$CLI_INSTALLED" = true ]; then + echo " • http://localhost:3000/callback (飞书 CLI)" +fi +echo " • http://localhost:3333/callback (社区 MCP)" + +if [ "$OFFICIAL_MCP_CONFIGURED" = true ]; then + echo " • http://localhost:3000/callback (官方 MCP)" +fi + +echo "" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +if [ "$FLAG_NO_INTERACTIVE" = false ]; then + printf " 配置完成后按 Enter 继续..." + read -r _PAUSE || true +fi + +echo "" + +# CLI auth (only if CLI was installed) +if [ "$CLI_INSTALLED" = true ]; then + if [ "$FLAG_NO_INTERACTIVE" = false ]; then + echo " 🔑 初始化 CLI 配置..." + if lark-cli config init --new 2>/dev/null; then + echo " ✅ CLI 配置初始化成功" + else + echo " ⚠️ CLI 配置初始化失败" + echo " 手动执行: lark-cli config init --new" + fi + + echo "" + echo " 🔑 CLI OAuth 登录(浏览器将自动打开)..." + echo " 如果 10 秒内浏览器未打开,请手动访问终端中显示的 URL" + echo "" + + # Trap Ctrl+C to provide friendly skip message + trap trap_ctrlc INT + if lark-cli auth login --recommend 2>/dev/null; then + echo " ✅ CLI 认证成功" + else + echo " ⚠️ CLI 认证未完成" + echo " 手动执行: lark-cli auth login --recommend" + fi + # Restore default trap + trap cleanup_on_error EXIT + trap - INT + else + echo " ⏭️ 非交互模式,跳过 CLI 认证" + echo " 请稍后手动执行认证:" + echo " lark-cli config init --new" + echo " lark-cli auth login --recommend" + fi +fi + +echo "" +echo " 📝 社区 MCP 会在首次使用时自动引导 OAuth 授权" +echo "" + +# ============================================================ +# Step 7: Platform detection and config generation (AC-1.1.7, E-9) +# ============================================================ + +echo "📋 [7/7] 检测 AI 平台并生成配置..." +echo "" + +# Ensure configs/ directory in project exists for portable templates +mkdir -p "${SCRIPT_DIR}/configs" + +# Platform detection functions +detect_openclaw() { + if command -v openclaw >/dev/null 2>&1; then + return 0 + fi + if [ -d "${HOME}/.openclaw" ] || [ -d "${HOME}/.config/openclaw" ]; then + return 0 + fi + return 1 +} + +detect_claude_code() { + if command -v claude >/dev/null 2>&1; then + return 0 + fi + if [ -d "${HOME}/.claude" ]; then + return 0 + fi + return 1 +} + +detect_cursor() { + if [ -d "${HOME}/.cursor" ]; then + return 0 + fi + # macOS app check + if [ "$DETECTED_OS" = "darwin" ] && [ -d "/Applications/Cursor.app" ]; then + return 0 + fi + # Linux common locations + if [ "$DETECTED_OS" = "linux" ]; then + if command -v cursor >/dev/null 2>&1; then + return 0 + fi + fi + return 1 +} + +# Generate personalized config for a platform using Node.js +# Args: $1=platform_name, $2=output_path, $3=template_path +generate_platform_config() { + local platform="$1" + local output_path="$2" + local template_path="$3" + + # Check if output already exists (and not --force) + if [ -f "$output_path" ] && [ "$FLAG_FORCE" = false ]; then + if [ "$FLAG_NO_INTERACTIVE" = true ]; then + echo " ⏭️ ${platform} 配置已存在,跳过: ${output_path}" + return 0 + fi + printf " ${platform} 配置已存在,是否覆盖? [y/N]: " + read -r OVERWRITE_ANSWER || true + OVERWRITE_ANSWER="$(trim "${OVERWRITE_ANSWER:-N}")" + case "$OVERWRITE_ANSWER" in + y|Y|yes|YES|是) ;; + *) + echo " ⏭️ 跳过 ${platform} 配置" + return 0 + ;; + esac + fi + + # Ensure output directory exists + mkdir -p "$(dirname "$output_path")" + + # Generate config by MERGING feishu entry into existing file (BLOCKER-1 fix) + # Credentials passed via environment variables to avoid injection (HIGH-1) + NODE_ERR_FILE="$(mktemp /tmp/feishu-node-err.XXXXXX)" + if FEISHU_APP_ID="$APP_ID" FEISHU_APP_SECRET="$APP_SECRET" \ + FEISHU_TEMPLATE_PATH="$template_path" FEISHU_OUTPUT_PATH="$output_path" node -e " + var fs = require('fs'); + var templatePath = process.env.FEISHU_TEMPLATE_PATH; + var outputPath = process.env.FEISHU_OUTPUT_PATH; + var appId = process.env.FEISHU_APP_ID; + var appSecret = process.env.FEISHU_APP_SECRET; + + // Read template to get the feishu entry structure + var template = JSON.parse(fs.readFileSync(templatePath, 'utf8')); + + // Read existing output file if present — preserve other entries + var config = {}; + if (fs.existsSync(outputPath)) { + try { + config = JSON.parse(fs.readFileSync(outputPath, 'utf8')); + } catch(e) { + // Malformed JSON — back up and start fresh + var timestamp = Date.now(); + var backupPath = outputPath + '.bak.' + timestamp; + fs.renameSync(outputPath, backupPath); + console.log(' ⚠️ 现有配置文件格式错误,已备份到: ' + backupPath); + config = {}; + } + } + + if (!config.mcpServers) config.mcpServers = {}; + + // Merge feishu entry from template (with credentials filled in) + if (template.mcpServers && template.mcpServers.feishu) { + var feishuEntry = JSON.parse(JSON.stringify(template.mcpServers.feishu)); + if (feishuEntry.env) { + feishuEntry.env.FEISHU_APP_ID = appId; + feishuEntry.env.FEISHU_APP_SECRET = appSecret; + } + config.mcpServers.feishu = feishuEntry; + } + + fs.writeFileSync(outputPath, JSON.stringify(config, null, 2)); + " 2>"$NODE_ERR_FILE"; then + echo " ✅ ${platform} 配置已生成: ${output_path}" + else + echo " ❌ ${platform} 配置生成失败" + if [ -s "$NODE_ERR_FILE" ]; then + echo " 错误详情: $(head -3 "$NODE_ERR_FILE")" + fi + echo " 请检查文件权限后重试: ${output_path}" + fi + rm -f "$NODE_ERR_FILE" +} + +# Determine which platforms to configure +PLATFORM_LIST="" + +if [ -n "$FLAG_PLATFORM" ]; then + # Manual platform specification + PLATFORM_LIST="$FLAG_PLATFORM" + echo " 📋 手动指定平台: ${FLAG_PLATFORM}" +else + # Auto-detect platforms + if detect_openclaw; then + PLATFORM_LIST="${PLATFORM_LIST} openclaw" + DETECTED_PLATFORMS="${DETECTED_PLATFORMS}OpenClaw " + echo " 🔍 检测到 OpenClaw" + fi + if detect_claude_code; then + PLATFORM_LIST="${PLATFORM_LIST} claude-code" + DETECTED_PLATFORMS="${DETECTED_PLATFORMS}Claude-Code " + echo " 🔍 检测到 Claude Code" + fi + if detect_cursor; then + PLATFORM_LIST="${PLATFORM_LIST} cursor" + DETECTED_PLATFORMS="${DETECTED_PLATFORMS}Cursor " + echo " 🔍 检测到 Cursor" + fi + + if [ -z "$PLATFORM_LIST" ]; then + echo " 📋 未检测到已安装的 AI 平台" + fi +fi + +echo "" + +# Generate configs for detected/specified platforms +for platform in $PLATFORM_LIST; do + case "$platform" in + openclaw) + # OpenClaw: generate in project configs/ and inform user + generate_platform_config "OpenClaw" \ + "${SCRIPT_DIR}/configs/openclaw-configured.json" \ + "${SCRIPT_DIR}/configs/openclaw.json" + echo " 💡 请将配置导入 OpenClaw 或复制到 OpenClaw 配置目录" + ;; + claude-code) + # Claude Code: generate to ~/.claude/ + CLAUDE_MCP_DIR="${HOME}/.claude" + mkdir -p "$CLAUDE_MCP_DIR" + generate_platform_config "Claude Code" \ + "${CLAUDE_MCP_DIR}/mcp.json" \ + "${SCRIPT_DIR}/configs/claude-code.json" + ;; + cursor) + # Cursor: generate to ~/.cursor/mcp.json + CURSOR_DIR="${HOME}/.cursor" + mkdir -p "$CURSOR_DIR" + generate_platform_config "Cursor" \ + "${CURSOR_DIR}/mcp.json" \ + "${SCRIPT_DIR}/configs/cursor.json" + ;; + *) + echo " ⚠️ 未知平台: ${platform}" + echo " 支持的平台: openclaw, claude-code, cursor" + ;; + esac +done + +# Always generate portable templates in project configs/ directory +echo "" +echo " 📁 便携配置模板已保存在: ${SCRIPT_DIR}/configs/" +echo " openclaw.json, claude-code.json, cursor.json" +echo "" + +# ============================================================ +# Validation and summary (AC-1.1.9) +# ============================================================ + +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "📊 安装摘要" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "" + +# CLI auth status check +if [ "$CLI_INSTALLED" = true ]; then + AUTH_STATUS="$(lark-cli auth status 2>/dev/null || echo "未认证")" + echo " 飞书 CLI: ✅ 已安装 (${CLI_VERSION})" + echo " CLI 认证: ${AUTH_STATUS}" +else + echo " 飞书 CLI: ❌ 未安装" + if [ "$FLAG_MCP_ONLY" = true ]; then + echo " (--mcp-only 模式,已跳过)" + else + echo " 安装方法: npm install -g @larksuite/cli" + fi +fi + +if [ "$MCPORTER_CONFIGURED" = true ]; then + echo " 社区 MCP: ✅ 已配置" +else + echo " 社区 MCP: ❌ 未配置" +fi + +if [ "$INSTALL_OFFICIAL" = true ] && [ "$OFFICIAL_MCP_CONFIGURED" = true ]; then + echo " 官方 MCP: ✅ 已配置" +elif [ "$INSTALL_OFFICIAL" = true ]; then + echo " 官方 MCP: ⚠️ 配置不完整" +else + echo " 官方 MCP: ⏭️ 已跳过" +fi + +echo " 配置文件: ${MCPORTER_CONFIG}" + +if [ -n "$DETECTED_PLATFORMS" ]; then + echo " 平台配置: ${DETECTED_PLATFORMS}" +else + echo " 平台配置: 便携模板 (${SCRIPT_DIR}/configs/)" +fi + +echo "" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "🎉 配置完成!" +echo "" +echo "试试以下命令:" +echo "" + +if [ "$CLI_INSTALLED" = true ]; then + echo " # 搜索文档" + echo " lark-cli doc +search --keyword '会议纪要'" + echo "" +fi + +echo " # 创建文档(社区 MCP)" +echo " mcporter call feishu.create_feishu_document --args '{\"title\":\"测试文档\"}'" +echo "" + +if [ "$CLI_INSTALLED" = true ]; then + echo " # 查看日历" + echo " lark-cli calendar +agenda" + echo "" +fi + +echo "📚 完整文档: https://github.com/AlexAnys/feishu-mcp" +echo "" diff --git a/skills/data-to-doc.md b/skills/data-to-doc.md new file mode 100644 index 0000000..9b1b18f --- /dev/null +++ b/skills/data-to-doc.md @@ -0,0 +1,191 @@ +--- +name: data-to-doc +description: 数据报告生成工作流 — 从多维表格查询数据(CLI),处理汇总后创建格式化文档(CLI+MCP),支持样式化关键指标。 +metadata: + bins: + - lark-cli + - mcporter +--- + +# 数据报告生成工作流 + +组合 CLI 和 MCP,从多维表格查询数据,自动生成带格式的飞书文档报告。 + +--- + +## When to Use This Skill + +- User asks to generate a report from bitable/multidimensional table data ("用多维表格数据生成报告") +- User wants to create a formatted document from structured data ("把数据整理成文档") +- User needs a periodic data summary document ("帮我出一份数据周报") +- User wants to visualize key metrics in a Feishu document + +--- + +## Prerequisites + +1. Confirm CLI auth: `lark-cli auth status` — must show valid token. +2. Confirm MCP auth: `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars set. +3. Obtain bitable identifiers from the user: + - `app_token`: the bitable app token (from URL `https://xxx.feishu.cn/base/`) + - `table_id`: the specific table within the bitable (ask user if multiple tables exist) +4. Determine report scope: date range, filters, grouping criteria. + +--- + +## Step-by-Step Workflow + +### Step 1: Query Data from Multidimensional Table + +**Tool**: CLI `lark-cli base +query` + +```bash +lark-cli base +query +``` + +The CLI will prompt for: +- app_token and table_id +- Filter conditions (e.g., date range, status) +- Sort order +- Fields to return + +**Error handling**: +- If "skill not found" → run `npx skills add larksuite/cli -y -g` and retry. +- If "permission denied" → ask user to add `bitable:app` scope at `https://open.feishu.cn/app/{APP_ID}/security`. +- If "app_token invalid" → verify the bitable URL with the user. +- If no records returned → inform user the query returned empty results. Adjust filters and retry. + +### Step 2: Process and Summarize Data + +**Tool**: AI analysis (no external tool needed) + +Process the raw records from Step 1: + +1. **Aggregate**: Calculate totals, averages, counts, percentages as appropriate. +2. **Group**: Organize data by categories (e.g., by status, by person, by date). +3. **Highlight**: Identify key metrics — highest/lowest values, trends, anomalies. +4. **Structure**: Plan the document layout: + - Title with date range + - Executive summary (2-3 sentences) + - Key metrics section (highlighted numbers) + - Detailed data breakdown (grouped tables or lists) + - Conclusion / next steps + +### Step 3: Create a New Document + +**Tool**: CLI `lark-cli doc +create` + +```bash +lark-cli doc +create +``` + +Provide a Markdown template with the report title and basic structure. The CLI will create the document and return a document URL and document_id. + +Extract the document_id from the returned URL for subsequent MCP operations. + +**Error handling**: +- If "permission denied" → ask user to add `docx:document` scope. +- If creation fails → retry once. If still failing, check `lark-cli auth status`. + +### Step 4: Add Formatted Blocks with Data + +**Tool**: MCP `batch_create_feishu_blocks` + +Use `batch_create_feishu_blocks` to add structured content. Build the blocks array dynamically from Step 2's processed data. Recommended document structure: +- `heading2` "数据概览" with report period +- `heading3` "关键指标" with aggregated metrics +- `heading3` "分类明细" with per-category breakdowns +- `heading2` "总结与下一步" with conclusions + +Use appropriate block types: +- `heading2` for major sections +- `heading3` for subsections +- `text` for paragraphs and data +- `list` for bullet points (ordered or unordered) +- `code` for raw data or formulas + +**Error handling**: +- If "document not found" → verify document_id from Step 3. +- If batch creation partially fails → retry failed blocks individually. +- If block limit exceeded → split into multiple batch calls (max ~50 blocks per call). + +### Step 5: Apply Styling to Key Metrics + +**Tool**: MCP `update_feishu_block_text` + +After creating blocks, apply visual emphasis to key metrics. First, identify the block_ids of key metric blocks from Step 4's response. + +For each key metric block, apply styling: + +``` +MCP tool: update_feishu_block_text +Parameters: { + "document_id": "", + "block_id": "", + "content": "完成率: 95%", + "text_color": "green", + "align": "center" +} +``` + +Color guidelines: +- **green**: positive metrics (targets met, growth) +- **red**: negative metrics (decline, missed targets) +- **blue**: neutral highlights (totals, key numbers) +- **orange**: warnings (approaching threshold) + +Available colors: `red`, `orange`, `yellow`, `green`, `blue`, `purple`, `grey`, `default`. + +**Error handling**: +- If "block not found" → re-fetch block list with `get_feishu_document_blocks` and find correct block_id. +- If styling fails → the content is still readable without styling. Log warning and continue. + +--- + +## Output Format + +The generated document will have this structure: + +``` +# [报告标题] — YYYY-MM-DD + +## 数据概览 +报告期间: ... 至 ... + +## 关键指标 +总计: XXX 完成率: XX% 增长: XX% +(green) (green/red) (green/red) + +## 分类明细 +### 类别 A +- 记录数: XX (XX%) +- 关键数据: ... + +### 类别 B +- 记录数: XX (XX%) +- 关键数据: ... + +## 总结与下一步 +- 总结要点 1 +- 总结要点 2 +- 下一步行动 +``` + +Return the document URL to the user upon completion. + +--- + +## Example Prompts + +- "用项目跟踪表的数据生成一份周报" +- "从 Bug 多维表格生成本月 Bug 统计报告" +- "把销售数据表整理成一份格式化的文档报告" +- "用这个多维表格 https://xxx.feishu.cn/base/appXXX 生成数据报告" + +--- + +## Partial Execution + +- "只查数据不生成文档" → Execute Step 1-2 only, present summary to user. +- "文档已经有了,帮我填入数据" → Skip Step 3, execute Steps 1-2 and 4-5 on existing document. +- "不需要样式,纯文本就行" → Execute Steps 1-4, skip Step 5. diff --git a/skills/doc-review.md b/skills/doc-review.md new file mode 100644 index 0000000..85939ef --- /dev/null +++ b/skills/doc-review.md @@ -0,0 +1,164 @@ +--- +name: doc-review +description: 文档审阅工作流 — 读取文档内容(MCP),分析质量和结构,创建待办任务(CLI),发送审阅总结到群聊(CLI)。 +metadata: + bins: + - lark-cli + - mcporter +--- + +# 文档审阅工作流 + +组合 CLI 和 MCP 完成文档审阅闭环:读取文档 → 分析内容 → 创建任务 → 发送总结。 + +--- + +## When to Use This Skill + +- User asks to review a Feishu document ("帮我审阅这个文档", "看看这篇文档写得怎么样") +- User wants to check document quality, structure, or completeness +- User needs to create action items from a document review +- User wants to send review feedback to a group chat + +--- + +## Prerequisites + +1. Confirm CLI auth: `lark-cli auth status` — must show valid token. +2. Confirm MCP auth: `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars set. +3. Obtain the document_id from the user. If user provides a URL like `https://xxx.feishu.cn/docx/doxcnXXX`, extract `doxcnXXX` as the document_id. + +--- + +## Step-by-Step Workflow + +### Step 1: Read Document Content + +**Tool**: MCP `get_feishu_document_blocks` + `get_feishu_document_text` + +First, get the block structure to understand the document layout: + +``` +MCP tool: get_feishu_document_blocks +Parameters: { "document_id": "" } +``` + +Then, get the plain text for content analysis: + +``` +MCP tool: get_feishu_document_text +Parameters: { "document_id": "" } +``` + +**Error handling**: +- If "document not found" → verify the document_id with the user. +- If "permission denied" → ask user to add `docx:document:readonly` scope at `https://open.feishu.cn/app/{APP_ID}/security`. +- If "unauthorized" → run `lark-cli auth login --recommend` to refresh token. + +### Step 2: Analyze Content Quality + +**Tool**: AI analysis (no external tool needed) + +Analyze the document on these dimensions: + +1. **Structure** — Does the document have clear headings, sections, and logical flow? Count heading blocks from Step 1's block structure. +2. **Completeness** — Are there TODO markers, empty sections, placeholder text, or missing content? +3. **Clarity** — Is the language clear? Are key terms defined? Are there ambiguous statements? +4. **Formatting** — Are lists, tables, and code blocks used appropriately? Is formatting consistent? +5. **Action items** — Identify any items that require follow-up (TODOs, decisions needed, open questions). + +Produce a structured review summary with: +- Overall quality score (1-10) +- Strengths (bullet list) +- Issues found (bullet list with severity: high/medium/low) +- Action items (numbered list) + +### Step 3: Create Tasks for Action Items + +**Tool**: CLI `lark-cli task +create` + +For each action item identified in Step 2, create a task: + +```bash +lark-cli task +create +``` + +The CLI will prompt for task details interactively. Provide: +- Task title: the action item description +- Due date: based on urgency (high = 3 days, medium = 7 days, low = 14 days) +- Assignee: if mentioned in the document or specified by user + +**Error handling**: +- If "skill not found" → run `npx skills add larksuite/cli -y -g` and retry. +- If "permission denied" → ask user to add `task:task` scope. + +### Step 4: Send Review Summary to Group Chat + +**Tool**: CLI `lark-cli im +send` + +Send the review summary to the specified group chat: + +```bash +lark-cli im +send +``` + +The message should include: +- Document title and link +- Overall quality score +- Key issues found (top 3) +- Number of tasks created +- Brief recommendation (approve / needs revision / major rework) + +**Error handling**: +- If "chat not found" → ask user for the correct chat ID or group name. +- If "permission denied" → ask user to add `im:message` scope. +- If user doesn't specify a chat → ask which group to send to, or skip this step. + +--- + +## Output Format + +Present the review to the user in this structure: + +``` +## 文档审阅报告 + +**文档**: [标题](链接) +**审阅时间**: YYYY-MM-DD +**综合评分**: X/10 + +### 优点 +- ... + +### 问题 +- [高] ... +- [中] ... +- [低] ... + +### 待办任务(已创建) +1. ...(截止日期: YYYY-MM-DD) +2. ... + +### 建议 +通过 / 需修改 / 需重写 +``` + +--- + +## Example Prompts + +- "帮我审阅一下这个文档 https://xxx.feishu.cn/docx/doxcnXXX" +- "检查这篇文档的质量,找出需要改进的地方" +- "审阅文档并把问题发到项目群里" +- "看看这个文档有没有遗漏的内容,创建待办任务跟进" + +--- + +## Partial Execution + +If the user only needs part of the workflow: +- "只看看文档内容" → Execute Steps 1-2 only. +- "审阅完帮我建任务" → Execute Steps 1-3, skip Step 4. +- "审阅完发到群里就行" → Execute Steps 1-2 and 4, skip Step 3. + +Adapt to the user's request. Do not force all steps if not needed. diff --git a/skills/feishu-overview.md b/skills/feishu-overview.md new file mode 100644 index 0000000..55fbd7a --- /dev/null +++ b/skills/feishu-overview.md @@ -0,0 +1,135 @@ +--- +name: feishu-overview +description: 飞书全能集成套件总览 — 所有 CLI 技能和 MCP 工具的中文索引,快速路由指南,当用户笼统提及"飞书"时加载此技能。 +metadata: + bins: + - lark-cli + - mcporter +--- + +# 飞书能力总览 + +当用户笼统提及"飞书"、"帮我用飞书"、"飞书能做什么"时,加载此技能作为入口。根据用户意图路由到具体技能或工具。 + +--- + +## When to Use This Skill + +- User mentions "飞书" without specifying a domain +- User asks "飞书能做什么" or "有哪些飞书功能" +- User needs help choosing the right tool for a Feishu task +- First interaction involving Feishu — orient the user before diving in + +--- + +## CLI 技能一览(19 个技能,11 业务域) + +| 技能 | 中文名称 | 一句话说明 | +|---|---|---| +| `lark-shared` | 认证与配置 | 应用初始化、OAuth 登录、身份切换、权限管理 | +| `lark-calendar` | 日历管理 | 查看日程、创建会议、查询忙闲、推荐空闲时段 | +| `lark-im` | 即时通讯 | 发送/回复消息、搜索聊天记录、管理群聊 | +| `lark-doc` | 云文档 | 从 Markdown 创建文档、搜索文档、更新内容、插入图片 | +| `lark-drive` | 云空间 | 上传/下载文件、管理文件夹、管理权限和评论 | +| `lark-sheets` | 电子表格 | 创建表格、读写单元格、追加行、导出文件 | +| `lark-base` | 多维表格 | 建表、字段管理、记录查询、视图配置、仪表盘 | +| `lark-task` | 任务管理 | 创建待办、查看任务列表、子任务拆分、分配成员 | +| `lark-mail` | 邮件 | 起草/发送/回复/转发/搜索邮件 | +| `lark-contact` | 通讯录 | 搜索员工、查看组织架构、查询部门结构 | +| `lark-wiki` | 知识库 | 管理知识空间、创建文档节点、组织层级结构 | +| `lark-vc` | 视频会议 | 查询已结束的会议记录、获取会议纪要 | +| `lark-minutes` | 妙记 | 获取妙记基础信息、AI 总结、待办、章节 | +| `lark-whiteboard` | 画板 | 创建画板、Mermaid 图表、流程图、思维导图 | +| `lark-event` | 事件订阅 | WebSocket 实时监听飞书事件,输出 NDJSON | +| `lark-openapi-explorer` | API 探索 | 从官方文档库挖掘未封装的 OpenAPI 接口 | +| `lark-skill-maker` | 技能创建 | 创建自定义 lark-cli Skill | +| `lark-workflow-meeting-summary` | 会议纪要工作流 | 汇总会议纪要并生成结构化报告 | +| `lark-workflow-standup-report` | 站会报告工作流 | 生成日程 + 未完成任务摘要 | + +--- + +## 社区 MCP 工具一览(17 个工具) + +| 工具名称 | 中文名称 | 一句话说明 | +|---|---|---| +| `create_feishu_document` | 创建文档 | 在指定文件夹创建新文档 | +| `get_feishu_document_info` | 获取文档信息 | 返回标题、修改时间等元数据 | +| `get_feishu_document_blocks` | 获取 Block 结构 | 返回文档完整 Block 树 | +| `get_feishu_document_text` | 提取纯文本 | 提取文档的纯文本内容 | +| `batch_create_feishu_blocks` | 批量创建 Block | 原子操作,支持 text/code/heading/list | +| `update_feishu_block_text` | 更新 Block 样式 | 修改文本内容、8 色彩、对齐方式 | +| `delete_feishu_document_blocks` | 删除 Block | 按 block_id 精确删除 | +| `upload_and_bind_image_to_block` | 上传图片 | 上传图片并绑定到 Block 一步完成 | +| `create_feishu_table` | 创建表格 | 在文档中创建指定行列数的表格 | +| `create_feishu_folder` | 创建文件夹 | 在云空间创建文件夹 | +| `list_feishu_folder_contents` | 列出文件夹内容 | 浏览文件夹中的文件和子文件夹 | +| `get_feishu_folder_files` | 获取文件列表 | 获取文件夹内的文件清单 | +| `search_feishu_documents` | 搜索文档 | 按关键词搜索文档 | +| `get_feishu_wiki_node_info` | Wiki 节点信息 | 获取知识库节点元数据 | +| `get_feishu_whiteboard_content` | 读取画板 | 读取画板内容(只读) | + +--- + +## 快速路由指南 + +**想要做 X?用 Y:** + +| 想要做什么 | 用什么 | 具体命令/工具 | +|---|---|---| +| 想看今天有什么会 | CLI | `lark-cli calendar +agenda` | +| 想约个会议 | CLI | `lark-cli calendar +create` | +| 想发条消息给同事 | CLI | `lark-cli im +send` | +| 想搜聊天记录 | CLI | `lark-cli im +search` | +| 想写个新文档 | CLI | `lark-cli doc +create` | +| 想给文档加格式化内容 | MCP | `batch_create_feishu_blocks` | +| 想改文字颜色/对齐 | MCP | `update_feishu_block_text` | +| 想查多维表格数据 | CLI | `lark-cli base +query` | +| 想创建待办任务 | CLI | `lark-cli task +create` | +| 想发邮件 | CLI | `lark-cli mail +compose` | +| 想找个人的联系方式 | CLI | `lark-cli contact +search` | +| 想查知识库 | CLI | `lark-cli wiki +list` | +| 想看会议纪要 | CLI | `lark-cli minutes` | +| 想画流程图 | CLI | `lark-cli docs +whiteboard-update` | +| 想读文档全文 | MCP | `get_feishu_document_text` | +| 想分析文档结构 | MCP | `get_feishu_document_blocks` | +| 想上传文件 | CLI | `lark-cli drive upload` | +| 想生成格式化报告 | CLI+MCP | 先查数据(CLI),再写格式化文档(MCP) | + +--- + +## 组合工作流技能 + +以下技能组合 CLI 和 MCP,完成多步操作: + +| 工作流 | 说明 | 技能文件 | +|---|---|---| +| 文档审阅 | 读取文档 → 分析内容 → 创建任务 → 发送总结 | `skills/doc-review.md` | +| 数据报告生成 | 查询数据 → 生成格式化文档 | `skills/data-to-doc.md` | +| 知识同步 | Wiki 与文档之间双向同步 | `skills/knowledge-sync.md` | +| 增强版会议纪要 | 会议纪要 + 格式化文档 + 任务创建 | `skills/meeting-summary-plus.md` | + +--- + +## 操作前检查 + +执行任何飞书操作前,按顺序验证: + +1. CLI 已安装:`which lark-cli` +2. CLI 已认证:`lark-cli auth status` +3. CLI 技能已加载:`lark-cli skills list` +4. MCP 环境变量已设置:`FEISHU_APP_ID` 和 `FEISHU_APP_SECRET` 非空 +5. mcporter 已安装:`which mcporter` + +如果任何检查失败,参考 `TROUBLESHOOT-AGENT.md` 进行修复。 + +--- + +## 决策原则(简版) + +1. 非文档域一律用 CLI(消息、日历、邮件、任务等) +2. 精确 Block 编辑用 MCP(颜色、对齐、批量格式化) +3. CLI 和 MCP 都能做时优先 CLI +4. 图表和画板编辑用 CLI +5. 多步工作流可组合两层 + +完整决策矩阵参见 `SKILL.md`。 diff --git a/skills/knowledge-sync.md b/skills/knowledge-sync.md new file mode 100644 index 0000000..667e4ea --- /dev/null +++ b/skills/knowledge-sync.md @@ -0,0 +1,186 @@ +--- +name: knowledge-sync +description: 知识同步工作流 — Wiki 与文档之间的双向同步:从 Wiki 读取内容更新到文档(CLI→MCP),或从文档内容创建/更新 Wiki 节点(MCP→CLI)。 +metadata: + bins: + - lark-cli + - mcporter +--- + +# 知识同步工作流 + +组合 CLI 和 MCP,在飞书 Wiki 知识库和云文档之间实现双向内容同步。 + +--- + +## When to Use This Skill + +- User wants to sync Wiki content to a document ("把知识库里的内容同步到文档") +- User wants to update Wiki from document content ("把文档内容更新到知识库") +- User needs to consolidate information from Wiki into a summary doc ("把几篇 Wiki 整理成一份文档") +- User needs to keep Wiki and standalone documents in sync + +--- + +## Prerequisites + +1. Confirm CLI auth: `lark-cli auth status` — must show valid token. +2. Confirm MCP auth: `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars set. +3. Required scopes: `wiki:wiki`, `docx:document`. Verify at `https://open.feishu.cn/app/{APP_ID}/security`. +4. Determine sync direction: + - **Direction A**: Wiki → Document (read Wiki, write to doc) + - **Direction B**: Document → Wiki (read doc, write to Wiki) + +--- + +## Direction A: Wiki to Document + +Use this when: extracting Wiki content and writing it into a standalone document or consolidating multiple Wiki pages into one document. + +### Step A1: Read Wiki Content + +**Tool**: CLI `lark-cli wiki` + +First, list available knowledge spaces to find the target: + +```bash +lark-cli wiki +list +``` + +Browse the Wiki structure to locate the target node(s). Note the wiki_token(s) for the pages to sync. + +To get detailed metadata about a specific node: + +``` +MCP tool: get_feishu_wiki_node_info +Parameters: { "token": "" } +``` + +This returns the node's title, type, parent, and the associated document_id (obj_token). + +**Error handling**: +- If "space not found" → ask user for the correct knowledge space name or ID. +- If "permission denied" → ask user to add `wiki:wiki` or `wiki:wiki:readonly` scope. + +### Step A2: Extract Key Information + +**Tool**: MCP `get_feishu_document_text` + `get_feishu_document_blocks` + +Wiki nodes are backed by documents. Use the obj_token (document_id) from Step A1 to read content: + +``` +MCP tool: get_feishu_document_text +Parameters: { "document_id": "" } +``` + +For structured extraction (headings, lists, code blocks): + +``` +MCP tool: get_feishu_document_blocks +Parameters: { "document_id": "" } +``` + +Process the content: +1. Extract key sections by heading structure. +2. Identify content that has changed since last sync (compare with target doc if it exists). +3. Organize extracted content into a coherent structure for the target document. + +If syncing multiple Wiki pages, repeat for each page and merge content logically. + +**Error handling**: +- If "document not found" → the wiki node may not have an associated document. Ask user to verify the Wiki page exists and has content. + +### Step A3: Update Target Document + +**Tool**: CLI `lark-cli doc +create` (if new) + MCP `batch_create_feishu_blocks` + `update_feishu_block_text` + +If the target document does not exist, create it first with `lark-cli doc +create`. + +Then add extracted content as formatted blocks via `batch_create_feishu_blocks`: +- Use `heading2` for source page titles, `heading3` for sections, `text` for content. +- Include a "同步时间: YYYY-MM-DD HH:MM" block at the top. + +To update existing blocks (rather than append), use `update_feishu_block_text` with the target block_id. To remove outdated blocks, use `delete_feishu_document_blocks`. + +**Error handling**: +- If "block not found" → re-fetch block list with `get_feishu_document_blocks`. +- If batch creation fails → split into smaller batches and retry. + +--- + +## Direction B: Document to Wiki + +Use this when: publishing document content into a Wiki knowledge base for team access, or keeping a Wiki page updated from a source document. + +### Step B1: Read Document Content + +**Tool**: MCP `get_feishu_document_text` + `get_feishu_document_blocks` + +Read the source document with `get_feishu_document_text` for plain text and `get_feishu_document_blocks` for structure. + +**Error handling**: +- If "document not found" → verify document_id with user. +- If "permission denied" → check `docx:document:readonly` scope. + +### Step B2: Extract and Transform Content + +**Tool**: AI analysis (no external tool needed) + +Process the document content: +1. Identify the main sections and their hierarchy. +2. Extract key content to sync to Wiki. +3. If the target Wiki node already exists, determine what has changed. +4. Format the content appropriately for the Wiki target. + +### Step B3: Create or Update Wiki Node + +**Tool**: CLI `lark-cli wiki +create` (new node) or MCP `batch_create_feishu_blocks` + `update_feishu_block_text` (existing node) + +For new Wiki nodes, use `lark-cli wiki +create`. The CLI prompts for target knowledge space, parent node, title, and content (Markdown). + +For existing Wiki nodes, use the node's associated document_id (from `get_feishu_wiki_node_info`) and update via MCP: `batch_create_feishu_blocks` to add blocks, `update_feishu_block_text` to modify existing blocks. + +**Error handling**: +- If "space not found" → ask user which knowledge space to use. +- If "permission denied" → ask user to add `wiki:wiki` scope (write, not readonly). +- If "parent node not found" → list nodes with `lark-cli wiki +list` and let user choose parent. + +--- + +## Output Format + +Report sync results to the user: + +``` +## 知识同步完成 + +**方向**: Wiki → 文档 / 文档 → Wiki +**来源**: [来源标题](来源链接) +**目标**: [目标标题](目标链接) +**同步时间**: YYYY-MM-DD HH:MM + +### 同步内容 +- 新增: X 个内容块 +- 更新: X 个内容块 +- 删除: X 个内容块 + +### 注意事项 +- (如有冲突或需手动检查的内容列出) +``` + +--- + +## Example Prompts + +- "把技术文档知识库里的 API 指南同步到这个文档" +- "把这篇文档发布到产品知识库里" +- "把三篇 Wiki 整理成一份汇总文档" +- "更新知识库里的部署文档,用这个文档的最新内容" + +--- + +## Partial Execution + +- "只读取 Wiki 内容" → Execute Step A1-A2 only. +- "只把文档内容推到 Wiki" → Execute Direction B. +- "看看两边有什么不同" → Execute A1-A2 and B1-B2, compare and report differences. diff --git a/skills/meeting-summary-plus.md b/skills/meeting-summary-plus.md new file mode 100644 index 0000000..5684665 --- /dev/null +++ b/skills/meeting-summary-plus.md @@ -0,0 +1,186 @@ +--- +name: meeting-summary-plus +description: 增强版会议纪要 — 在 CLI 内置会议纪要工作流基础上,用 MCP 生成格式化文档,创建待办任务,并发送通知到群聊。 +metadata: + bins: + - lark-cli + - mcporter +--- + +# 增强版会议纪要 + +在 CLI 内置的 `workflow-meeting-summary` 基础上增强:生成格式化的会议纪要文档,高亮关键决策,创建待办任务,并通知相关群组。 + +--- + +## When to Use This Skill + +- User wants a formatted meeting summary document ("帮我整理会议纪要并生成文档") +- User wants action items from meetings converted to tasks ("把会议待办变成任务") +- User needs to send meeting summary to a group ("整理完会议纪要发到群里") +- User wants more than the basic CLI meeting summary — needs styling, tasks, and notifications +- User mentions "增强版会议纪要" or "会议纪要 plus" + +--- + +## Prerequisites + +1. Confirm CLI auth: `lark-cli auth status` — must show valid token. +2. Confirm MCP auth: `FEISHU_APP_ID` and `FEISHU_APP_SECRET` env vars set. +3. Required scopes: `vc:meeting:readonly`, `minutes:minute:readonly`, `docx:document`, `task:task`, `im:message`. +4. Determine the time range or specific meeting to summarize. + +--- + +## Step-by-Step Workflow + +### Step 1: Retrieve Meeting Data via CLI + +**Tool**: CLI `lark-cli workflow meeting-summary` or `lark-cli minutes` + `lark-cli vc` + +**Option A** — Use the built-in workflow (recommended for time-range summaries): + +```bash +lark-cli workflow meeting-summary +``` + +This aggregates meetings within a time range and produces a structured summary including: +- Meeting list with titles, times, attendees +- AI-generated summaries per meeting +- Action items / todos +- Key discussion chapters + +**Option B** — Manual approach for a single meeting: + +First, find the meeting record: + +```bash +lark-cli vc +``` + +Then get the detailed minutes: + +```bash +lark-cli minutes +``` + +This returns: title, duration, AI summary, todos, chapters, and transcript. + +**Error handling**: +- If "skill not found" → run `npx skills add larksuite/cli -y -g` and retry. +- If "no meetings found" → widen the time range or verify the date. +- If "permission denied" → ask user to add `vc:meeting:readonly` and `minutes:minute:readonly` scopes. + +### Step 2: Create Formatted Summary Document + +**Tool**: CLI `lark-cli doc +create` + MCP `batch_create_feishu_blocks` + +First, create the document: + +```bash +lark-cli doc +create +``` + +Provide a brief Markdown title like "会议纪要 — YYYY-MM-DD". Extract the document_id from the returned URL. + +Then, add formatted content blocks via `batch_create_feishu_blocks`. Build the blocks array dynamically from Step 1's data using this structure: +- `heading1`: document title with date +- `heading2`: major sections (会议概览, AI 摘要, 关键决策, 待办事项, 讨论要点) +- `heading3`: individual topics/agenda items +- `text`: content paragraphs (meeting info, summaries, discussion details) +- `list`: decisions and action items + +For multiple meetings, add a `heading2` section per meeting. + +**Error handling**: +- If document creation fails → check auth with `lark-cli auth status`. +- If batch creation fails → split into smaller batches (max ~50 blocks per call). + +### Step 3: Style Key Decisions and Action Items + +**Tool**: MCP `update_feishu_block_text` + +Get the block_ids from Step 2's response and apply styling with `update_feishu_block_text`: + +- **blue** (`text_color: "blue"`): key decisions +- **red** (`text_color: "red"`): urgent or overdue action items +- **green** (`text_color: "green"`): completed items +- **purple** (`text_color: "purple"`): important notes or reminders + +**Error handling**: +- If "block not found" → re-fetch blocks with `get_feishu_document_blocks` and find correct block_id. +- If styling fails → content is still readable. Log warning and continue. + +### Step 4: Create Tasks from Action Items + +**Tool**: CLI `lark-cli task +create` + +For each action item extracted in Step 1, create a task: + +```bash +lark-cli task +create +``` + +Provide for each task: +- **Title**: the action item description +- **Assignee**: the person mentioned (if identifiable) +- **Due date**: extracted from the meeting notes, or default based on urgency +- **Description**: include the meeting title and date for context + +**Error handling**: +- If "permission denied" → ask user to add `task:task` scope. +- If assignee not found → create the task without assignee and note it in the output. +- If no action items found → skip this step and inform user. + +### Step 5: Send Notification to Group + +**Tool**: CLI `lark-cli im +send` + +Send a notification via `lark-cli im +send`. Include: meeting title, date, document link, count of decisions and tasks created, and a 2-3 sentence summary. + +**Error handling**: +- If user doesn't specify a chat → ask which group to notify, or skip this step. +- If "chat not found" → ask user for the correct chat ID or group name. +- If "permission denied" → ask user to add `im:message` scope. + +--- + +## Output Format + +Present the result to the user: + +``` +## 会议纪要整理完成 + +**文档**: [会议纪要 — YYYY-MM-DD](文档链接) +**会议数**: X 场 +**关键决策**: X 条 +**待办任务**: X 条(已创建) +**通知**: 已发送到 [群组名称] + +### 关键决策 +1. ... +2. ... + +### 已创建的任务 +1. [负责人] 任务描述 — 截止 YYYY-MM-DD +2. [负责人] 任务描述 — 截止 YYYY-MM-DD +``` + +--- + +## Example Prompts + +- "帮我整理今天的会议纪要,生成文档并发到项目群" +- "把昨天的会议内容整理成文档,待办事项帮我建成任务" +- "整理本周所有会议纪要,生成一份格式化的汇总文档" +- "增强版会议纪要:上午的产品评审会" + +--- + +## Partial Execution + +- "只整理会议内容,不建任务" → Execute Steps 1-3, skip Steps 4-5. +- "整理完帮我发群里就行" → Execute Steps 1-2 and 5, skip Steps 3-4. +- "只看看有哪些会议和待办" → Execute Step 1 only, present raw data. +- "会议纪要已有文档了,帮我建任务和发通知" → Skip Steps 1-3, execute Steps 4-5 from provided doc.