feishu-mcp 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,394 +0,0 @@
1
- import { z } from 'zod';
2
- import { formatErrorMessage } from '../../utils/error.js';
3
- import { Logger } from '../../utils/logger.js';
4
- import { detectMimeType } from '../../utils/document.js';
5
- import { DocumentIdSchema, ParentBlockIdSchema, BlockIdSchema, IndexSchema, StartIndexSchema, EndIndexSchema, AlignSchema, AlignSchemaWithValidation, TextElementsArraySchema, CodeLanguageSchema, CodeWrapSchema, BlockConfigSchema, MediaIdSchema, MediaExtraSchema } from '../../types/feishuSchema.js';
6
- /**
7
- * 注册飞书块相关的MCP工具
8
- * @param server MCP服务器实例
9
- * @param feishuService 飞书API服务实例
10
- */
11
- export function registerFeishuBlockTools(server, feishuService) {
12
- // 添加更新块文本内容工具
13
- server.tool('update_feishu_block_text', 'Updates the text content and styling of a specific block in a Feishu document. Can be used to modify content in existing text, code, or heading blocks while preserving the block type and other properties. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
14
- documentId: DocumentIdSchema,
15
- blockId: BlockIdSchema,
16
- textElements: TextElementsArraySchema,
17
- }, async ({ documentId, blockId, textElements }) => {
18
- try {
19
- if (!feishuService) {
20
- return {
21
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
22
- };
23
- }
24
- Logger.info(`开始更新飞书块文本内容,文档ID: ${documentId},块ID: ${blockId}`);
25
- const result = await feishuService.updateBlockTextContent(documentId, blockId, textElements);
26
- Logger.info(`飞书块文本内容更新成功`);
27
- return {
28
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
29
- };
30
- }
31
- catch (error) {
32
- Logger.error(`更新飞书块文本内容失败:`, error);
33
- const errorMessage = formatErrorMessage(error);
34
- return {
35
- content: [{ type: 'text', text: `更新飞书块文本内容失败: ${errorMessage}` }],
36
- };
37
- }
38
- });
39
- // 添加通用飞书块创建工具(支持文本、代码、标题)
40
- server.tool('batch_create_feishu_blocks', 'PREFERRED: Efficiently creates multiple blocks (text, code, heading, list) in a single API call. USE THIS TOOL when creating multiple consecutive blocks at the same position - reduces API calls by up to 90%. KEY FEATURES: (1) Handles any number of blocks by auto-batching large requests (>50 blocks), (2) Creates blocks at consecutive positions in a document. CORRECT FORMAT: mcp_feishu_batch_create_feishu_blocks({documentId:"doc123",parentBlockId:"para123",startIndex:0,blocks:[{blockType:"text",options:{...}},{blockType:"heading",options:{...}}]}). For separate positions, use individual block creation tools instead. For wiki links (https://xxx.feishu.cn/wiki/xxx), first convert with convert_feishu_wiki_to_document_id tool.', {
41
- documentId: DocumentIdSchema,
42
- parentBlockId: ParentBlockIdSchema,
43
- startIndex: StartIndexSchema,
44
- blocks: z.array(BlockConfigSchema).describe('Array of block configurations. CRITICAL: Must be a JSON array object, NOT a string. CORRECT: blocks:[{...}] - WITHOUT quotes around array. INCORRECT: blocks:"[{...}]". Example: [{blockType:"text",options:{text:{textStyles:[{text:"Hello",style:{bold:true}}]}}},{blockType:"code",options:{code:{code:"console.log()",language:30}}}]. Auto-batches requests when exceeding 50 blocks.'),
45
- }, async ({ documentId, parentBlockId, startIndex = 0, blocks }) => {
46
- try {
47
- if (!feishuService) {
48
- return {
49
- content: [
50
- {
51
- type: 'text',
52
- text: 'Feishu service is not initialized. Please check the configuration',
53
- },
54
- ],
55
- };
56
- }
57
- // 类型检查:确保blocks是数组而不是字符串
58
- if (typeof blocks === 'string') {
59
- return {
60
- content: [
61
- {
62
- type: 'text',
63
- text: 'ERROR: The "blocks" parameter was passed as a string instead of an array. Please provide a proper JSON array without quotes. Example: {blocks:[{blockType:"text",options:{...}}]} instead of {blocks:"[{...}]"}',
64
- },
65
- ],
66
- };
67
- }
68
- // 如果块数量不超过50,直接调用一次API
69
- if (blocks.length <= 50) {
70
- Logger.info(`开始批量创建飞书块,文档ID: ${documentId},父块ID: ${parentBlockId},块数量: ${blocks.length},起始插入位置: ${startIndex}`);
71
- // 准备要创建的块内容数组
72
- const blockContents = [];
73
- // 处理每个块配置
74
- for (const blockConfig of blocks) {
75
- const { blockType, options = {} } = blockConfig;
76
- // 创建块内容
77
- const blockContent = feishuService.createBlockContent(blockType, options);
78
- if (blockContent) {
79
- blockContents.push(blockContent);
80
- Logger.info(`已准备${blockType}块,内容: ${JSON.stringify(blockContent).substring(0, 100)}...`);
81
- }
82
- }
83
- // 批量创建所有块
84
- const result = await feishuService.createDocumentBlocks(documentId, parentBlockId, blockContents, startIndex);
85
- Logger.info(`飞书块批量创建成功,共创建 ${blockContents.length} 个块`);
86
- return {
87
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
88
- };
89
- }
90
- else {
91
- // 如果块数量超过50,需要分批处理
92
- Logger.info(`块数量(${blocks.length})超过50,将分批创建`);
93
- const batchSize = 50; // 每批最大50个
94
- const totalBatches = Math.ceil(blocks.length / batchSize);
95
- const results = [];
96
- let currentStartIndex = startIndex;
97
- let createdBlocksCount = 0;
98
- let allBatchesSuccess = true;
99
- // 分批创建块
100
- for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
101
- const batchStart = batchNum * batchSize;
102
- const batchEnd = Math.min((batchNum + 1) * batchSize, blocks.length);
103
- const currentBatch = blocks.slice(batchStart, batchEnd);
104
- Logger.info(`处理第 ${batchNum + 1}/${totalBatches} 批,起始位置: ${currentStartIndex},块数量: ${currentBatch.length}`);
105
- try {
106
- // 准备当前批次的块内容
107
- const batchBlockContents = [];
108
- for (const blockConfig of currentBatch) {
109
- const { blockType, options = {} } = blockConfig;
110
- const blockContent = feishuService.createBlockContent(blockType, options);
111
- if (blockContent) {
112
- batchBlockContents.push(blockContent);
113
- }
114
- }
115
- // 批量创建当前批次的块
116
- const batchResult = await feishuService.createDocumentBlocks(documentId, parentBlockId, batchBlockContents, currentStartIndex);
117
- results.push(batchResult);
118
- // 计算下一批的起始位置(当前位置+已创建块数量)
119
- // 注意:每批成功创建后,需要将起始索引更新为当前索引 + 已创建块数量
120
- createdBlocksCount += batchBlockContents.length;
121
- currentStartIndex = startIndex + createdBlocksCount;
122
- Logger.info(`第 ${batchNum + 1}/${totalBatches} 批创建成功,当前已创建 ${createdBlocksCount} 个块`);
123
- }
124
- catch (error) {
125
- Logger.error(`第 ${batchNum + 1}/${totalBatches} 批创建失败:`, error);
126
- allBatchesSuccess = false;
127
- // 如果有批次失败,返回详细错误信息
128
- const errorMessage = formatErrorMessage(error);
129
- return {
130
- content: [
131
- {
132
- type: 'text',
133
- text: `批量创建飞书块部分失败:第 ${batchNum + 1}/${totalBatches} 批处理时出错。\n\n` +
134
- `已成功创建 ${createdBlocksCount} 个块,但还有 ${blocks.length - createdBlocksCount} 个块未能创建。\n\n` +
135
- `错误信息: ${errorMessage}\n\n` +
136
- `建议使用 get_feishu_document_blocks 工具获取文档最新状态,确认已创建的内容,然后从索引位置 ${currentStartIndex} 继续创建剩余块。`
137
- }
138
- ],
139
- };
140
- }
141
- }
142
- if (allBatchesSuccess) {
143
- Logger.info(`所有批次创建成功,共创建 ${createdBlocksCount} 个块`);
144
- return {
145
- content: [
146
- {
147
- type: 'text',
148
- text: `所有飞书块创建成功,共分 ${totalBatches} 批创建了 ${createdBlocksCount} 个块。\n\n` +
149
- `最后一批结果: ${JSON.stringify(results[results.length - 1], null, 2)}`
150
- }
151
- ],
152
- };
153
- }
154
- }
155
- // 这个return语句是为了避免TypeScript错误,实际上代码永远不会执行到这里
156
- return {
157
- content: [{ type: 'text', text: '操作完成' }],
158
- };
159
- }
160
- catch (error) {
161
- Logger.error(`批量创建飞书块失败:`, error);
162
- const errorMessage = formatErrorMessage(error);
163
- return {
164
- content: [
165
- {
166
- type: 'text',
167
- text: `批量创建飞书块失败: ${errorMessage}\n\n` +
168
- `建议使用 get_feishu_document_blocks 工具获取文档当前状态,确认是否有部分内容已创建成功。`
169
- }
170
- ],
171
- };
172
- }
173
- });
174
- // 添加创建飞书文本块工具
175
- server.tool("create_feishu_text_block", "Creates a new text block with precise style control. Unlike markdown-based formatting, this tool lets you explicitly set text styles for each text segment. Ideal for formatted documents where exact styling control is needed. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
176
- documentId: DocumentIdSchema,
177
- parentBlockId: ParentBlockIdSchema,
178
- textContents: TextElementsArraySchema,
179
- align: AlignSchema,
180
- index: IndexSchema
181
- }, async ({ documentId, parentBlockId, textContents, align = 1, index }) => {
182
- try {
183
- if (!feishuService) {
184
- return {
185
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
186
- };
187
- }
188
- Logger.info(`开始创建飞书文本块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
189
- const result = await feishuService.createTextBlock(documentId, parentBlockId, textContents, align, index);
190
- Logger.info(`飞书文本块创建成功`);
191
- return {
192
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
193
- };
194
- }
195
- catch (error) {
196
- Logger.error(`创建飞书文本块失败:`, error);
197
- const errorMessage = formatErrorMessage(error);
198
- return {
199
- content: [{ type: "text", text: `创建飞书文本块失败: ${errorMessage}` }],
200
- };
201
- }
202
- });
203
- // 添加创建飞书代码块工具
204
- server.tool("create_feishu_code_block", "Creates a new code block with syntax highlighting and formatting options. Ideal for technical documentation, tutorials, or displaying code examples with proper formatting and language-specific highlighting. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
205
- documentId: DocumentIdSchema,
206
- parentBlockId: ParentBlockIdSchema,
207
- code: z.string().describe("Code content (required). The complete code text to display."),
208
- language: CodeLanguageSchema,
209
- wrap: CodeWrapSchema,
210
- index: IndexSchema
211
- }, async ({ documentId, parentBlockId, code, language = 1, wrap = false, index = 0 }) => {
212
- try {
213
- if (!feishuService) {
214
- return {
215
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
216
- };
217
- }
218
- Logger.info(`开始创建飞书代码块,文档ID: ${documentId},父块ID: ${parentBlockId},语言: ${language},自动换行: ${wrap},插入位置: ${index}`);
219
- const result = await feishuService.createCodeBlock(documentId, parentBlockId, code, language, wrap, index);
220
- Logger.info(`飞书代码块创建成功`);
221
- return {
222
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
223
- };
224
- }
225
- catch (error) {
226
- Logger.error(`创建飞书代码块失败:`, error);
227
- const errorMessage = formatErrorMessage(error);
228
- return {
229
- content: [{ type: "text", text: `创建飞书代码块失败: ${errorMessage}` }],
230
- };
231
- }
232
- });
233
- // 添加创建飞书标题块工具
234
- server.tool("create_feishu_heading_block", "Creates a heading block with customizable level and alignment. Use this tool to add section titles, chapter headings, or any hierarchical structure elements to your document. Supports nine heading levels for different emphasis needs. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
235
- documentId: DocumentIdSchema,
236
- parentBlockId: ParentBlockIdSchema,
237
- level: z.number().min(1).max(9).describe("Heading level (required). Integer between 1 and 9, where 1 is the largest heading (h1) and 9 is the smallest (h9)."),
238
- content: z.string().describe("Heading text content (required). The actual text of the heading."),
239
- align: AlignSchemaWithValidation,
240
- index: IndexSchema
241
- }, async ({ documentId, parentBlockId, level, content, align = 1, index = 0 }) => {
242
- try {
243
- if (!feishuService) {
244
- return {
245
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
246
- };
247
- }
248
- // 确保align值在合法范围内(1-3)
249
- if (align !== 1 && align !== 2 && align !== 3) {
250
- return {
251
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
252
- };
253
- }
254
- Logger.info(`开始创建飞书标题块,文档ID: ${documentId},父块ID: ${parentBlockId},标题级别: ${level},对齐方式: ${align},插入位置: ${index}`);
255
- const result = await feishuService.createHeadingBlock(documentId, parentBlockId, content, level, index, align);
256
- Logger.info(`飞书标题块创建成功`);
257
- return {
258
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
259
- };
260
- }
261
- catch (error) {
262
- Logger.error(`创建飞书标题块失败:`, error);
263
- const errorMessage = formatErrorMessage(error);
264
- return {
265
- content: [{ type: "text", text: `创建飞书标题块失败: ${errorMessage}` }],
266
- };
267
- }
268
- });
269
- // 添加创建飞书列表块工具
270
- server.tool("create_feishu_list_block", "Creates a list item block (either ordered or unordered). Perfect for creating hierarchical and structured content with bullet points or numbered lists. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
271
- documentId: DocumentIdSchema,
272
- parentBlockId: ParentBlockIdSchema,
273
- content: z.string().describe("List item content (required). The actual text of the list item."),
274
- isOrdered: z.boolean().optional().default(false).describe("Whether this is an ordered (numbered) list item. Default is false (bullet point/unordered)."),
275
- align: AlignSchemaWithValidation,
276
- index: IndexSchema
277
- }, async ({ documentId, parentBlockId, content, isOrdered = false, align = 1, index = 0 }) => {
278
- try {
279
- if (!feishuService) {
280
- return {
281
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
282
- };
283
- }
284
- // 确保align值在合法范围内(1-3)
285
- if (align !== 1 && align !== 2 && align !== 3) {
286
- return {
287
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
288
- };
289
- }
290
- const listType = isOrdered ? "有序" : "无序";
291
- Logger.info(`开始创建飞书${listType}列表块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
292
- const result = await feishuService.createListBlock(documentId, parentBlockId, content, isOrdered, index, align);
293
- Logger.info(`飞书${listType}列表块创建成功`);
294
- return {
295
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
296
- };
297
- }
298
- catch (error) {
299
- Logger.error(`创建飞书列表块失败:`, error);
300
- const errorMessage = formatErrorMessage(error);
301
- return {
302
- content: [{ type: "text", text: `创建飞书列表块失败: ${errorMessage}` }],
303
- };
304
- }
305
- });
306
- // 添加飞书Wiki文档ID转换工具
307
- server.tool('convert_feishu_wiki_to_document_id', 'Converts a Feishu Wiki document link to a compatible document ID. This conversion is required before using wiki links with any other Feishu document tools.', {
308
- wikiUrl: z.string().describe('Wiki URL or Token (required). Supports complete URL formats like https://xxx.feishu.cn/wiki/xxxxx or direct use of the Token portion'),
309
- }, async ({ wikiUrl }) => {
310
- try {
311
- if (!feishuService) {
312
- return {
313
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
314
- };
315
- }
316
- Logger.info(`开始转换Wiki文档链接,输入: ${wikiUrl}`);
317
- const documentId = await feishuService.convertWikiToDocumentId(wikiUrl);
318
- Logger.info(`Wiki文档转换成功,可用的文档ID为: ${documentId}`);
319
- return {
320
- content: [
321
- { type: 'text', text: `Converted Wiki link to Document ID: ${documentId}\n\nUse this Document ID with other Feishu document tools.` }
322
- ],
323
- };
324
- }
325
- catch (error) {
326
- Logger.error(`转换Wiki文档链接失败:`, error);
327
- const errorMessage = formatErrorMessage(error);
328
- return {
329
- content: [{ type: 'text', text: `转换Wiki文档链接失败: ${errorMessage}` }],
330
- };
331
- }
332
- });
333
- // 添加删除文档块工具
334
- server.tool('delete_feishu_document_blocks', 'Deletes one or more consecutive blocks from a Feishu document. Use this tool to remove unwanted content, clean up document structure, or clear space before inserting new content. Supports batch deletion for efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
335
- documentId: DocumentIdSchema,
336
- parentBlockId: ParentBlockIdSchema,
337
- startIndex: StartIndexSchema,
338
- endIndex: EndIndexSchema,
339
- }, async ({ documentId, parentBlockId, startIndex, endIndex }) => {
340
- try {
341
- if (!feishuService) {
342
- return {
343
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
344
- };
345
- }
346
- Logger.info(`开始删除飞书文档块,文档ID: ${documentId},父块ID: ${parentBlockId},索引范围: ${startIndex}-${endIndex}`);
347
- const result = await feishuService.deleteDocumentBlocks(documentId, parentBlockId, startIndex, endIndex);
348
- Logger.info(`飞书文档块删除成功,文档修订ID: ${result.document_revision_id}`);
349
- return {
350
- content: [{ type: 'text', text: `Successfully deleted blocks from index ${startIndex} to ${endIndex - 1}` }],
351
- };
352
- }
353
- catch (error) {
354
- Logger.error(`删除飞书文档块失败:`, error);
355
- const errorMessage = formatErrorMessage(error);
356
- return {
357
- content: [{ type: 'text', text: `Failed to delete document blocks: ${errorMessage}` }],
358
- };
359
- }
360
- });
361
- // 添加获取图片资源工具
362
- server.tool('get_feishu_image_resource', 'Downloads an image resource from Feishu by its media ID. Use this to retrieve images referenced in document blocks or other Feishu resources. Returns the binary image data that can be saved or processed further. For example, extract the media_id from an image block in a document, then use this tool to download the actual image.', {
363
- mediaId: MediaIdSchema,
364
- extra: MediaExtraSchema,
365
- }, async ({ mediaId, extra = '' }) => {
366
- try {
367
- if (!feishuService) {
368
- return {
369
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
370
- };
371
- }
372
- Logger.info(`开始获取飞书图片资源,媒体ID: ${mediaId}`);
373
- const imageBuffer = await feishuService.getImageResource(mediaId, extra);
374
- Logger.info(`飞书图片资源获取成功,大小: ${imageBuffer.length} 字节`);
375
- // 将图片数据转为Base64编码,以便在MCP协议中传输
376
- const base64Image = imageBuffer.toString('base64');
377
- const mimeType = detectMimeType(imageBuffer);
378
- return {
379
- content: [{
380
- type: 'image',
381
- mimeType: mimeType,
382
- data: base64Image
383
- }],
384
- };
385
- }
386
- catch (error) {
387
- Logger.error(`获取飞书图片资源失败:`, error);
388
- const errorMessage = formatErrorMessage(error);
389
- return {
390
- content: [{ type: 'text', text: `Failed to get image resource: ${errorMessage}` }],
391
- };
392
- }
393
- });
394
- }
@@ -1,86 +0,0 @@
1
- import { formatErrorMessage } from '../../utils/error.js';
2
- import { Logger } from '../../utils/logger.js';
3
- import { FolderTokenSchema, FolderNameSchema, OrderBySchema, DirectionSchema } from '../../types/feishuSchema.js';
4
- /**
5
- * 注册飞书文件夹相关的MCP工具
6
- * @param server MCP服务器实例
7
- * @param feishuService 飞书API服务实例
8
- */
9
- export function registerFeishuFolderTools(server, feishuService) {
10
- // 添加获取根文件夹信息工具
11
- server.tool('get_feishu_root_folder_info', 'Retrieves basic information about the root folder in Feishu Drive. Returns the token, ID and user ID of the root folder, which can be used for subsequent folder operations.', {}, async () => {
12
- try {
13
- if (!feishuService) {
14
- return {
15
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
16
- };
17
- }
18
- Logger.info(`开始获取飞书根文件夹信息`);
19
- const folderInfo = await feishuService.getRootFolderInfo();
20
- Logger.info(`飞书根文件夹信息获取成功,token: ${folderInfo.token}`);
21
- return {
22
- content: [{ type: 'text', text: JSON.stringify(folderInfo, null, 2) }],
23
- };
24
- }
25
- catch (error) {
26
- Logger.error(`获取飞书根文件夹信息失败:`, error);
27
- const errorMessage = formatErrorMessage(error, '获取飞书根文件夹信息失败');
28
- return {
29
- content: [{ type: 'text', text: errorMessage }],
30
- };
31
- }
32
- });
33
- // 添加获取文件夹中的文件清单工具
34
- server.tool('get_feishu_folder_files', 'Retrieves a list of files and subfolders in a specified folder. Use this to explore folder contents, view file metadata, and get URLs and tokens for further operations.', {
35
- folderToken: FolderTokenSchema,
36
- orderBy: OrderBySchema,
37
- direction: DirectionSchema
38
- }, async ({ folderToken, orderBy = 'EditedTime', direction = 'DESC' }) => {
39
- try {
40
- if (!feishuService) {
41
- return {
42
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
43
- };
44
- }
45
- Logger.info(`开始获取飞书文件夹中的文件清单,文件夹Token: ${folderToken},排序方式: ${orderBy},排序方向: ${direction}`);
46
- const fileList = await feishuService.getFolderFileList(folderToken, orderBy, direction);
47
- Logger.info(`飞书文件夹中的文件清单获取成功,共 ${fileList.files?.length || 0} 个文件`);
48
- return {
49
- content: [{ type: 'text', text: JSON.stringify(fileList, null, 2) }],
50
- };
51
- }
52
- catch (error) {
53
- Logger.error(`获取飞书文件夹中的文件清单失败:`, error);
54
- const errorMessage = formatErrorMessage(error);
55
- return {
56
- content: [{ type: 'text', text: `获取飞书文件夹中的文件清单失败: ${errorMessage}` }],
57
- };
58
- }
59
- });
60
- // 添加创建文件夹工具
61
- server.tool('create_feishu_folder', 'Creates a new folder in a specified parent folder. Use this to organize documents and files within your Feishu Drive structure. Returns the token and URL of the newly created folder.', {
62
- folderToken: FolderTokenSchema,
63
- folderName: FolderNameSchema,
64
- }, async ({ folderToken, folderName }) => {
65
- try {
66
- if (!feishuService) {
67
- return {
68
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
69
- };
70
- }
71
- Logger.info(`开始创建飞书文件夹,父文件夹Token: ${folderToken},文件夹名称: ${folderName}`);
72
- const result = await feishuService.createFolder(folderToken, folderName);
73
- Logger.info(`飞书文件夹创建成功,token: ${result.token},URL: ${result.url}`);
74
- return {
75
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
76
- };
77
- }
78
- catch (error) {
79
- Logger.error(`创建飞书文件夹失败:`, error);
80
- const errorMessage = formatErrorMessage(error);
81
- return {
82
- content: [{ type: 'text', text: `创建飞书文件夹失败: ${errorMessage}` }],
83
- };
84
- }
85
- });
86
- }
@@ -1,138 +0,0 @@
1
- import { z } from 'zod';
2
- import { formatErrorMessage } from '../../utils/error.js';
3
- import { Logger } from '../../utils/logger.js';
4
- import { DocumentIdSchema, BlockIdSchema, } from '../../types/feishuSchema.js';
5
- /**
6
- * 注册飞书相关的MCP工具
7
- * @param server MCP服务器实例
8
- * @param feishuService 飞书API服务实例
9
- */
10
- export function registerFeishuTools(server, feishuService) {
11
- // 添加创建飞书文档工具
12
- server.tool('create_feishu_document', 'Creates a new Feishu document and returns its information. Use this tool when you need to create a document from scratch with a specific title and folder location.', {
13
- title: z.string().describe('Document title (required). This will be displayed in the Feishu document list and document header.'),
14
- folderToken: z.string().describe('Folder token (required). Specifies where to create the document. Format is an alphanumeric string like "doxcnOu1ZKYH4RtX1Y5XwL5WGRh".'),
15
- }, async ({ title, folderToken }) => {
16
- try {
17
- Logger.info(`开始创建飞书文档,标题: ${title}${folderToken ? `,文件夹Token: ${folderToken}` : ',使用默认文件夹'}`);
18
- const newDoc = await feishuService?.createDocument(title, folderToken);
19
- if (!newDoc) {
20
- throw new Error('创建文档失败,未返回文档信息');
21
- }
22
- Logger.info(`飞书文档创建成功,文档ID: ${newDoc.objToken || newDoc.document_id}`);
23
- return {
24
- content: [{ type: 'text', text: JSON.stringify(newDoc, null, 2) }],
25
- };
26
- }
27
- catch (error) {
28
- Logger.error(`创建飞书文档失败:`, error);
29
- const errorMessage = formatErrorMessage(error);
30
- return {
31
- content: [{ type: 'text', text: `创建飞书文档失败: ${errorMessage}` }],
32
- };
33
- }
34
- });
35
- // 添加获取飞书文档信息工具
36
- server.tool('get_feishu_document_info', 'Retrieves basic information about a Feishu document. Use this to verify a document exists, check access permissions, or get metadata like title, type, and creation information.', {
37
- documentId: DocumentIdSchema,
38
- }, async ({ documentId }) => {
39
- try {
40
- if (!feishuService) {
41
- return {
42
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
43
- };
44
- }
45
- Logger.info(`开始获取飞书文档信息,文档ID: ${documentId}`);
46
- const docInfo = await feishuService.getDocumentInfo(documentId);
47
- Logger.info(`飞书文档信息获取成功,标题: ${docInfo.title}`);
48
- return {
49
- content: [{ type: 'text', text: JSON.stringify(docInfo, null, 2) }],
50
- };
51
- }
52
- catch (error) {
53
- Logger.error(`获取飞书文档信息失败:`, error);
54
- const errorMessage = formatErrorMessage(error, '获取飞书文档信息失败');
55
- return {
56
- content: [{ type: 'text', text: errorMessage }],
57
- };
58
- }
59
- });
60
- // 添加获取飞书文档内容工具
61
- server.tool('get_feishu_document_content', 'Retrieves the plain text content of a Feishu document. Ideal for content analysis, processing, or when you need to extract text without formatting. The content maintains the document structure but without styling. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
62
- documentId: DocumentIdSchema,
63
- lang: z.number().optional().default(0).describe('Language code (optional). Default is 0 (Chinese). Use 1 for English if available.'),
64
- }, async ({ documentId, lang }) => {
65
- try {
66
- if (!feishuService) {
67
- return {
68
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
69
- };
70
- }
71
- Logger.info(`开始获取飞书文档内容,文档ID: ${documentId},语言: ${lang}`);
72
- const content = await feishuService.getDocumentContent(documentId, lang);
73
- Logger.info(`飞书文档内容获取成功,内容长度: ${content.length}字符`);
74
- return {
75
- content: [{ type: 'text', text: content }],
76
- };
77
- }
78
- catch (error) {
79
- Logger.error(`获取飞书文档内容失败:`, error);
80
- const errorMessage = formatErrorMessage(error);
81
- return {
82
- content: [{ type: 'text', text: `获取飞书文档内容失败: ${errorMessage}` }],
83
- };
84
- }
85
- });
86
- // 添加获取飞书文档块工具
87
- server.tool('get_feishu_document_blocks', 'Retrieves the block structure information of a Feishu document. Essential to use before inserting content to understand document structure and determine correct insertion positions. Returns a detailed hierarchy of blocks with their IDs, types, and content. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
88
- documentId: DocumentIdSchema,
89
- pageSize: z.number().optional().default(500).describe('Number of blocks per page (optional). Default is 500. Used for paginating large documents. Increase for more blocks at once, decrease for faster response with fewer blocks.'),
90
- }, async ({ documentId, pageSize }) => {
91
- try {
92
- if (!feishuService) {
93
- return {
94
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
95
- };
96
- }
97
- Logger.info(`开始获取飞书文档块,文档ID: ${documentId},页大小: ${pageSize}`);
98
- const blocks = await feishuService.getDocumentBlocks(documentId, pageSize);
99
- Logger.info(`飞书文档块获取成功,共 ${blocks.length} 个块`);
100
- return {
101
- content: [{ type: 'text', text: JSON.stringify(blocks, null, 2) }],
102
- };
103
- }
104
- catch (error) {
105
- Logger.error(`获取飞书文档块失败:`, error);
106
- const errorMessage = formatErrorMessage(error);
107
- return {
108
- content: [{ type: 'text', text: `获取飞书文档块失败: ${errorMessage}` }],
109
- };
110
- }
111
- });
112
- // 添加获取块内容工具
113
- server.tool('get_feishu_block_content', 'Retrieves the detailed content and structure of a specific block in a Feishu document. Useful for inspecting block properties, formatting, and content, especially before making updates or for debugging purposes. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
114
- documentId: DocumentIdSchema,
115
- blockId: BlockIdSchema,
116
- }, async ({ documentId, blockId }) => {
117
- try {
118
- if (!feishuService) {
119
- return {
120
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
121
- };
122
- }
123
- Logger.info(`开始获取飞书块内容,文档ID: ${documentId},块ID: ${blockId}`);
124
- const blockContent = await feishuService.getBlockContent(documentId, blockId);
125
- Logger.info(`飞书块内容获取成功,块类型: ${blockContent.block_type}`);
126
- return {
127
- content: [{ type: 'text', text: JSON.stringify(blockContent, null, 2) }],
128
- };
129
- }
130
- catch (error) {
131
- Logger.error(`获取飞书块内容失败:`, error);
132
- const errorMessage = formatErrorMessage(error);
133
- return {
134
- content: [{ type: 'text', text: `获取飞书块内容失败: ${errorMessage}` }],
135
- };
136
- }
137
- });
138
- }