feishu-mcp 0.0.5 → 0.0.6

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.
package/dist/server.js CHANGED
@@ -11,126 +11,6 @@ export const Logger = {
11
11
  console.error(...args);
12
12
  },
13
13
  };
14
- // 添加一个工具类方法,用于格式化错误信息
15
- function formatErrorMessage(error) {
16
- if (error instanceof Error) {
17
- return error.message;
18
- }
19
- else if (typeof error === 'string') {
20
- return error;
21
- }
22
- else if (error && typeof error === 'object') {
23
- try {
24
- // 处理包含apiError字段的FeishuError对象
25
- if (error.apiError) {
26
- const apiError = error.apiError;
27
- let errorMsg = '';
28
- // 处理标准飞书API错误格式
29
- if (apiError.code && apiError.msg) {
30
- errorMsg = `${apiError.msg} (错误码: ${apiError.code})`;
31
- // 添加字段验证错误信息
32
- if (apiError.error && apiError.error.field_violations && apiError.error.field_violations.length > 0) {
33
- const violations = apiError.error.field_violations;
34
- errorMsg += '\n字段验证错误:';
35
- violations.forEach((violation) => {
36
- let detail = `\n - ${violation.field}`;
37
- if (violation.description) {
38
- detail += `: ${violation.description}`;
39
- }
40
- if (violation.value) {
41
- detail += `,提供的值: ${violation.value}`;
42
- }
43
- errorMsg += detail;
44
- });
45
- // 添加排查建议链接
46
- if (apiError.error.troubleshooter) {
47
- errorMsg += `\n\n${apiError.error.troubleshooter}`;
48
- }
49
- }
50
- return errorMsg;
51
- }
52
- // 如果apiError没有标准结构,尝试序列化
53
- return `API错误: ${JSON.stringify(apiError)}`;
54
- }
55
- // 处理飞书API特定的错误格式
56
- if (error.code && error.msg) {
57
- // 基本错误信息
58
- let errorMsg = `${error.msg} (错误码: ${error.code})`;
59
- // 如果有详细的验证错误信息
60
- if (error.error && error.error.field_violations && error.error.field_violations.length > 0) {
61
- const violations = error.error.field_violations;
62
- errorMsg += '\n字段验证错误:';
63
- violations.forEach((violation) => {
64
- let detail = `\n - ${violation.field}`;
65
- if (violation.description) {
66
- detail += `: ${violation.description}`;
67
- }
68
- if (violation.value) {
69
- detail += `,提供的值: ${violation.value}`;
70
- }
71
- errorMsg += detail;
72
- });
73
- // 添加排查建议链接(如果有)
74
- if (error.error.troubleshooter) {
75
- errorMsg += `\n\n${error.error.troubleshooter}`;
76
- }
77
- }
78
- return errorMsg;
79
- }
80
- // 处理 {status, err} 格式的错误
81
- if (error.status && error.err) {
82
- return `操作失败 (状态码: ${error.status}): ${error.err}`;
83
- }
84
- // 尝试提取API错误信息,通常在错误对象的message或error字段中
85
- if (error.message) {
86
- return error.message;
87
- }
88
- else if (error.error) {
89
- if (typeof error.error === 'string') {
90
- return error.error;
91
- }
92
- else if (error.error.message) {
93
- return error.error.message;
94
- }
95
- else if (error.error.field_violations) {
96
- // 处理错误嵌套在error对象中的情况
97
- const violations = error.error.field_violations;
98
- let errorMsg = '字段验证错误:';
99
- violations.forEach((violation) => {
100
- let detail = `\n - ${violation.field}`;
101
- if (violation.description) {
102
- detail += `: ${violation.description}`;
103
- }
104
- if (violation.value) {
105
- detail += `,提供的值: ${violation.value}`;
106
- }
107
- errorMsg += detail;
108
- });
109
- return errorMsg;
110
- }
111
- }
112
- else if (error.code || error.status) {
113
- // 处理HTTP错误或API错误码
114
- const code = error.code || error.status;
115
- const msg = error.statusText || error.msg || 'Unknown error';
116
- return `操作失败 (错误码: ${code}): ${msg}`;
117
- }
118
- // 如果上述都不符合,尝试将整个对象序列化(但移除敏感信息)
119
- const safeError = { ...error };
120
- // 移除可能的敏感信息
121
- ['token', 'secret', 'password', 'key', 'credentials'].forEach(key => {
122
- if (key in safeError)
123
- delete safeError[key];
124
- });
125
- return `发生错误: ${JSON.stringify(safeError)}`;
126
- }
127
- catch (e) {
128
- console.error("Error formatting error message:", e);
129
- return '发生未知错误';
130
- }
131
- }
132
- return '发生未知错误';
133
- }
134
14
  export class FeishuMcpServer {
135
15
  constructor(feishuConfig) {
136
16
  Object.defineProperty(this, "server", {
@@ -174,63 +54,77 @@ export class FeishuMcpServer {
174
54
  }
175
55
  registerTools() {
176
56
  // 添加创建飞书文档工具
177
- this.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.', {
178
- title: z.string().describe('Document title (required). This will be displayed in the Feishu document list and document header.'),
179
- folderToken: z.string().describe('Folder token (required). Specifies where to create the document. Format is an alphanumeric string like "doxcnOu1ZKYH4RtX1Y5XwL5WGRh".'),
57
+ this.server.tool('create_feishu_doc', 'Create a new Feishu document', {
58
+ title: z.string().describe('Document title'),
59
+ folderToken: z
60
+ .string()
61
+ .optional()
62
+ .describe('Folder token where the document will be created. If not provided, the document will be created in the root directory'),
180
63
  }, async ({ title, folderToken }) => {
181
64
  try {
182
- Logger.log(`开始创建飞书文档,标题: ${title}${folderToken ? `,文件夹Token: ${folderToken}` : ',使用默认文件夹'}`);
183
- const newDoc = await this.feishuService?.createDocument(title, folderToken);
184
- if (!newDoc) {
185
- throw new Error('创建文档失败,未返回文档信息');
186
- }
187
- Logger.log(`飞书文档创建成功,文档ID: ${newDoc.objToken || newDoc.document_id}`);
65
+ Logger.log(`开始创建飞书文档,标题: ${title}${folderToken ? `,文件夹Token: ${folderToken}` : ''}`);
66
+ // @ts-ignore
67
+ const newDoc = await this.feishuService.createDocument(title, folderToken);
68
+ Logger.log(`飞书文档创建成功,文档ID: ${newDoc?.objToken || newDoc?.document_id}`);
188
69
  return {
189
70
  content: [{ type: 'text', text: JSON.stringify(newDoc, null, 2) }],
190
71
  };
191
72
  }
192
73
  catch (error) {
193
74
  Logger.error(`创建飞书文档失败:`, error);
194
- const errorMessage = formatErrorMessage(error);
195
75
  return {
196
- content: [{ type: 'text', text: `创建飞书文档失败: ${errorMessage}` }],
76
+ content: [{ type: 'text', text: `创建飞书文档失败: ${error}` }],
197
77
  };
198
78
  }
199
79
  });
200
80
  // 添加获取飞书文档信息工具
201
- this.server.tool("get_feishu_doc_info", "Retrieves basic information about a Feishu document. Use this to verify if a document exists, check access permissions, or get metadata like title, type, and creation information.", {
202
- documentId: z.string().describe("Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf"),
203
- }, async ({ documentId }) => {
204
- try {
205
- if (!this.feishuService) {
206
- return {
207
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
208
- };
209
- }
210
- Logger.log(`开始获取飞书文档信息,文档ID: ${documentId}`);
211
- const docInfo = await this.feishuService.getDocumentInfo(documentId);
212
- Logger.log(`飞书文档信息获取成功,标题: ${docInfo.title}`);
213
- return {
214
- content: [{ type: "text", text: JSON.stringify(docInfo, null, 2) }],
215
- };
216
- }
217
- catch (error) {
218
- Logger.error(`获取飞书文档信息失败:`, error);
219
- const errorMessage = formatErrorMessage(error);
220
- return {
221
- content: [{ type: "text", text: `获取飞书文档信息失败: ${errorMessage}` }],
222
- };
223
- }
224
- });
81
+ // this.server.tool(
82
+ // "get_feishu_doc_info",
83
+ // "Get basic information about a Feishu document",
84
+ // {
85
+ // documentId: z.string().describe("Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)"),
86
+ // },
87
+ // async ({ documentId }) => {
88
+ // try {
89
+ // if (!this.feishuService) {
90
+ // return {
91
+ // content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
92
+ // };
93
+ // }
94
+ // Logger.log(`开始获取飞书文档信息,文档ID: ${documentId}`);
95
+ // const docInfo = await this.feishuService.getDocumentInfo(documentId);
96
+ // Logger.log(`飞书文档信息获取成功,标题: ${docInfo.title}`);
97
+ // return {
98
+ // content: [{ type: "text", text: JSON.stringify(docInfo, null, 2) }],
99
+ // };
100
+ // } catch (error) {
101
+ // Logger.error(`获取飞书文档信息失败:`, error);
102
+ // return {
103
+ // content: [{ type: "text", text: `获取飞书文档信息失败: ${error}` }],
104
+ // };
105
+ // }
106
+ // },
107
+ // );
225
108
  // 添加获取飞书文档内容工具
226
- this.server.tool('get_feishu_doc_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.', {
227
- documentId: z.string().describe('Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf'),
228
- lang: z.number().optional().default(0).describe('Language code (optional). Default is 0 (Chinese). Use 1 for English if available.'),
109
+ this.server.tool('get_feishu_doc_content', 'Get the plain text content of a Feishu document', {
110
+ documentId: z
111
+ .string()
112
+ .describe('Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)'),
113
+ lang: z
114
+ .number()
115
+ .optional()
116
+ .default(0)
117
+ .describe('Language code. Default is 0 (Chinese)'),
229
118
  }, async ({ documentId, lang }) => {
230
119
  try {
231
120
  if (!this.feishuService) {
232
121
  return {
233
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
122
+ content: [
123
+ {
124
+ type: 'text',
125
+ text: 'Feishu service is not initialized. Please check the configuration',
126
+ },
127
+ ],
234
128
  };
235
129
  }
236
130
  Logger.log(`开始获取飞书文档内容,文档ID: ${documentId},语言: ${lang}`);
@@ -242,21 +136,31 @@ export class FeishuMcpServer {
242
136
  }
243
137
  catch (error) {
244
138
  Logger.error(`获取飞书文档内容失败:`, error);
245
- const errorMessage = formatErrorMessage(error);
246
139
  return {
247
- content: [{ type: 'text', text: `获取飞书文档内容失败: ${errorMessage}` }],
140
+ content: [{ type: 'text', text: `获取飞书文档内容失败: ${error}` }],
248
141
  };
249
142
  }
250
143
  });
251
144
  // 添加获取飞书文档块工具
252
- this.server.tool('get_feishu_doc_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.', {
253
- documentId: z.string().describe('Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf'),
254
- 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.'),
145
+ this.server.tool('get_feishu_doc_blocks', 'When document structure is needed, obtain the block information about the Feishu document for content analysis or block insertion', {
146
+ documentId: z
147
+ .string()
148
+ .describe('Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)'),
149
+ pageSize: z
150
+ .number()
151
+ .optional()
152
+ .default(500)
153
+ .describe('Number of blocks per page. Default is 500'),
255
154
  }, async ({ documentId, pageSize }) => {
256
155
  try {
257
156
  if (!this.feishuService) {
258
157
  return {
259
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
158
+ content: [
159
+ {
160
+ type: 'text',
161
+ text: 'Feishu service is not initialized. Please check the configuration',
162
+ },
163
+ ],
260
164
  };
261
165
  }
262
166
  Logger.log(`开始获取飞书文档块,文档ID: ${documentId},页大小: ${pageSize}`);
@@ -268,136 +172,281 @@ export class FeishuMcpServer {
268
172
  }
269
173
  catch (error) {
270
174
  Logger.error(`获取飞书文档块失败:`, error);
271
- const errorMessage = formatErrorMessage(error);
272
175
  return {
273
- content: [{ type: 'text', text: `获取飞书文档块失败: ${errorMessage}` }],
176
+ content: [{ type: 'text', text: `获取飞书文档块失败: ${error}` }],
274
177
  };
275
178
  }
276
179
  });
277
- // 添加获取块内容工具
278
- this.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.', {
279
- documentId: z.string().describe('Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf'),
280
- blockId: z.string().describe('Block ID (required). The ID of the specific block to get content from. You can obtain block IDs using the get_feishu_doc_blocks tool.'),
281
- }, async ({ documentId, blockId }) => {
282
- try {
283
- if (!this.feishuService) {
284
- return {
285
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
286
- };
287
- }
288
- Logger.log(`开始获取飞书块内容,文档ID: ${documentId},块ID: ${blockId}`);
289
- const blockContent = await this.feishuService.getBlockContent(documentId, blockId);
290
- Logger.log(`飞书块内容获取成功,块类型: ${blockContent.block_type}`);
291
- return {
292
- content: [{ type: 'text', text: JSON.stringify(blockContent, null, 2) }],
293
- };
294
- }
295
- catch (error) {
296
- Logger.error(`获取飞书块内容失败:`, error);
297
- const errorMessage = formatErrorMessage(error);
298
- return {
299
- content: [{ type: 'text', text: `获取飞书块内容失败: ${errorMessage}` }],
300
- };
301
- }
302
- });
303
- // 添加更新块文本内容工具
304
- this.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.', {
305
- documentId: z.string().describe('Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf'),
306
- blockId: z.string().describe('Block ID (required). The ID of the specific block to update content. You can obtain block IDs using the get_feishu_doc_blocks tool.'),
307
- textElements: z.array(z.object({
308
- text: z.string().describe('Text content. Provide plain text without markdown syntax; use the style object for formatting.'),
309
- style: z.object({
310
- bold: z.boolean().optional().describe('Whether to make text bold. Default is false, equivalent to **text** in Markdown.'),
311
- italic: z.boolean().optional().describe('Whether to make text italic. Default is false, equivalent to *text* in Markdown.'),
312
- underline: z.boolean().optional().describe('Whether to add underline. Default is false.'),
313
- strikethrough: z.boolean().optional().describe('Whether to add strikethrough. Default is false, equivalent to ~~text~~ in Markdown.'),
314
- inline_code: z.boolean().optional().describe('Whether to format as inline code. Default is false, equivalent to `code` in Markdown.'),
315
- text_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
316
- message: "Text color must be between 1 and 7 inclusive"
317
- }).describe('Text color value. Default is 0 (black). Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error.'),
318
- background_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
319
- message: "Background color must be between 1 and 7 inclusive"
320
- }).describe('Background color value. Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error.')
321
- }).optional().describe('Text style settings. Explicitly set style properties instead of relying on Markdown syntax conversion.')
322
- })).describe('Array of text content objects. A block can contain multiple text segments with different styles. Example: [{text:"Hello",style:{bold:true}},{text:" World",style:{italic:true}}]'),
323
- }, async ({ documentId, blockId, textElements }) => {
180
+ // 添加创建飞书文档块工具
181
+ // this.server.tool(
182
+ // "create_feishu_text_block",
183
+ // "Create a new text block in a Feishu document (AI will automatically convert Markdown syntax to corresponding style attributes: **bold** bold:true, *italic* italic:true, ~~strikethrough~~ strikethrough:true, `code` → inline_code:true)",
184
+ // {
185
+ // documentId: z.string().describe("Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)"),
186
+ // parentBlockId: z.string().describe("Parent block ID (NOT URL) where the new block will be added as a child. This should be the raw block ID without any URL prefix. When adding blocks at the page level (root level), use the extracted document ID from documentId parameter"),
187
+ // textContents: z.array(
188
+ // z.object({
189
+ // text: z.string().describe("Text content"),
190
+ // style: z.object({
191
+ // bold: z.boolean().optional().describe("Whether to make text bold. Default is false"),
192
+ // italic: z.boolean().optional().describe("Whether to make text italic. Default is false"),
193
+ // underline: z.boolean().optional().describe("Whether to add underline. Default is false"),
194
+ // strikethrough: z.boolean().optional().describe("Whether to add strikethrough. Default is false"),
195
+ // inline_code: z.boolean().optional().describe("Whether to format as inline code. Default is false"),
196
+ // text_color: z.number().optional().describe("Text color as a number. Default is 0")
197
+ // }).optional().describe("Text style settings")
198
+ // })
199
+ // ).describe("Array of text content objects. A block can contain multiple text segments with different styles"),
200
+ // align: z.number().optional().default(1).describe("Text alignment: 1 for left, 2 for center, 3 for right. Default is 1"),
201
+ // index: z.number().optional().default(0).describe("Insertion position index. Default is 0 (insert at the beginning). If unsure about the position, use the get_feishu_doc_blocks tool first to understand the document structure. For consecutive insertions, calculate the next position as previous_index + 1 to avoid querying document structure repeatedly")
202
+ // },
203
+ // async ({ documentId, parentBlockId, textContents, align = 1, index }) => {
204
+ // try {
205
+ // if (!this.feishuService) {
206
+ // return {
207
+ // content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
208
+ // };
209
+ // }
210
+ //
211
+ // // 处理Markdown语法转换
212
+ // const processedTextContents = textContents.map(content => {
213
+ // let { text, style = {} } = content;
214
+ //
215
+ // // 创建一个新的style对象,避免修改原始对象
216
+ // const newStyle = { ...style };
217
+ //
218
+ // // 处理粗体 **text**
219
+ // if (text.match(/\*\*([^*]+)\*\*/g)) {
220
+ // text = text.replace(/\*\*([^*]+)\*\*/g, "$1");
221
+ // newStyle.bold = true;
222
+ // }
223
+ //
224
+ // // 处理斜体 *text*
225
+ // if (text.match(/(?<!\*)\*([^*]+)\*(?!\*)/g)) {
226
+ // text = text.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, "$1");
227
+ // newStyle.italic = true;
228
+ // }
229
+ //
230
+ // // 处理删除线 ~~text~~
231
+ // if (text.match(/~~([^~]+)~~/g)) {
232
+ // text = text.replace(/~~([^~]+)~~/g, "$1");
233
+ // newStyle.strikethrough = true;
234
+ // }
235
+ //
236
+ // // 处理行内代码 `code`
237
+ // if (text.match(/`([^`]+)`/g)) {
238
+ // text = text.replace(/`([^`]+)`/g, "$1");
239
+ // newStyle.inline_code = true;
240
+ // }
241
+ //
242
+ // return { text, style: newStyle };
243
+ // });
244
+ //
245
+ // Logger.log(`开始创建飞书文本块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
246
+ // const result = await this.feishuService.createTextBlock(documentId, parentBlockId, processedTextContents, align, index);
247
+ // Logger.log(`飞书文本块创建成功`);
248
+ //
249
+ // return {
250
+ // content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
251
+ // };
252
+ // } catch (error) {
253
+ // Logger.error(`创建飞书文本块失败:`, error);
254
+ // return {
255
+ // content: [{ type: "text", text: `创建飞书文本块失败: ${error}` }],
256
+ // };
257
+ // }
258
+ // },
259
+ // );
260
+ // 添加创建飞书代码块工具
261
+ // this.server.tool(
262
+ // "create_feishu_code_block",
263
+ // "Create a new code block in a Feishu document",
264
+ // {
265
+ // documentId: z.string().describe("Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)"),
266
+ // parentBlockId: z.string().describe("Parent block ID (NOT URL) where the new block will be added as a child. This should be the raw block ID without any URL prefix. When adding blocks at the page level (root level), use the extracted document ID from documentId parameter"),
267
+ // code: z.string().describe("Code content"),
268
+ // language: z.number().optional().default(0).describe("Programming language code as a number. Examples: 1: PlainText; 7: Bash; 8: CSharp; 9: C++; 10: C; 12: CSS; 22: Go; 24: HTML; 29: Java; 30: JavaScript; 32: Kotlin; 43: PHP; 49: Python; 52: Ruby; 53: Rust; 56: SQL; 60: Shell; 61: Swift; 63: TypeScript. Default is 0"),
269
+ // wrap: z.boolean().optional().default(false).describe("Whether to enable automatic line wrapping. Default is false"),
270
+ // index: z.number().optional().default(0).describe("Insertion position index. Default is 0 (insert at the beginning). If unsure about the position, use the get_feishu_doc_blocks tool first to understand the document structure. For consecutive insertions, calculate the next position as previous_index + 1 to avoid querying document structure repeatedly")
271
+ // },
272
+ // async ({ documentId, parentBlockId, code, language = 0, wrap = false, index = 0 }) => {
273
+ // try {
274
+ // if (!this.feishuService) {
275
+ // return {
276
+ // content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
277
+ // };
278
+ // }
279
+ //
280
+ // Logger.log(`开始创建飞书代码块,文档ID: ${documentId},父块ID: ${parentBlockId},语言: ${language},自动换行: ${wrap},插入位置: ${index}`);
281
+ // const result = await this.feishuService.createCodeBlock(documentId, parentBlockId, code, language, wrap, index);
282
+ // Logger.log(`飞书代码块创建成功`);
283
+ //
284
+ // return {
285
+ // content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
286
+ // };
287
+ // } catch (error) {
288
+ // Logger.error(`创建飞书代码块失败:`, error);
289
+ // return {
290
+ // content: [{ type: "text", text: `创建飞书代码块失败: ${error}` }],
291
+ // };
292
+ // }
293
+ // },
294
+ // );
295
+ // 添加批量创建飞书块工具
296
+ this.server.tool('create_feishu_blocks', 'Create multiple blocks in a Feishu document at once with a single API call', {
297
+ documentId: z
298
+ .string()
299
+ .describe('Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)'),
300
+ parentBlockId: z
301
+ .string()
302
+ .describe('Parent block ID (NOT URL) where the new blocks will be added as children. This should be the raw block ID without any URL prefix. When adding blocks at the page level (root level), use the extracted document ID from documentId parameter'),
303
+ children: z
304
+ .array(z.object({
305
+ block_type: z
306
+ .number()
307
+ .describe('Block type number: 2 for text, 3-11 for headings (level+2), 14 for code'),
308
+ content: z
309
+ .any()
310
+ .describe('Block content object that follows Feishu API format'),
311
+ }))
312
+ .describe('Array of block objects to create in a single API call'),
313
+ index: z
314
+ .number()
315
+ .optional()
316
+ .default(0)
317
+ .describe('Insertion position index. Default is 0 (insert at the beginning)'),
318
+ }, async ({ documentId, parentBlockId, children, index = 0 }) => {
324
319
  try {
325
320
  if (!this.feishuService) {
326
321
  return {
327
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
322
+ content: [
323
+ {
324
+ type: 'text',
325
+ text: 'Feishu service is not initialized. Please check the configuration',
326
+ },
327
+ ],
328
328
  };
329
329
  }
330
- Logger.log(`开始更新飞书块文本内容,文档ID: ${documentId},块ID: ${blockId}`);
331
- const result = await this.feishuService.updateBlockTextContent(documentId, blockId, textElements);
332
- Logger.log(`飞书块文本内容更新成功`);
330
+ Logger.log(`开始批量创建飞书块,文档ID: ${documentId},父块ID: ${parentBlockId},块数量: ${children.length},插入位置: ${index}`);
331
+ const result = await this.feishuService.createDocumentBlocks(documentId, parentBlockId, children, index);
332
+ Logger.log(`飞书块批量创建成功`);
333
333
  return {
334
334
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
335
335
  };
336
336
  }
337
337
  catch (error) {
338
- Logger.error(`更新飞书块文本内容失败:`, error);
339
- const errorMessage = formatErrorMessage(error);
338
+ Logger.error(`批量创建飞书块失败:`, error);
340
339
  return {
341
- content: [{ type: 'text', text: `更新飞书块文本内容失败: ${errorMessage}` }],
340
+ content: [{ type: 'text', text: `批量创建飞书块失败: ${error}` }],
342
341
  };
343
342
  }
344
343
  });
345
344
  // 添加通用飞书块创建工具(支持文本、代码、标题)
346
- this.server.tool('create_feishu_multiple_blocks', 'Creates multiple blocks of different types (text, code, heading, list) in a single API call and at the same position. Significantly improves efficiency compared to creating individual blocks separately. ONLY use this when you need to insert multiple blocks CONSECUTIVELY at the SAME position. If blocks need to be inserted at different positions, use individual block creation tools instead. NOTE: Due to API limitations, you can create a maximum of 50 blocks in a single call. PREFER THIS TOOL OVER INDIVIDUAL BLOCK CREATION TOOLS when creating multiple consecutive blocks, as it is much more efficient and reduces API calls.', {
347
- documentId: z.string().describe('Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf'),
348
- parentBlockId: z.string().describe('Parent block ID (required). Target block ID where content will be added, without any URL prefix. For page-level (root level) insertion, extract and use only the document ID portion (not the full URL) as parentBlockId. Obtain existing block IDs using the get_feishu_doc_blocks tool.'),
349
- startIndex: z.number().describe('Starting insertion position index (required). Specifies where the first block should be inserted. Use 0 to insert at the beginning. Use get_feishu_doc_blocks tool to understand document structure if unsure.'),
350
- blocks: z.array(z.object({
351
- blockType: z.enum(['text', 'code', 'heading', 'list']).describe("Block type (required): 'text', 'code', 'heading', or 'list'. Choose based on the content type you need to create."),
352
- options: z.union([
353
- z.object({
354
- text: z.object({
355
- textStyles: z.array(z.object({
356
- text: z.string().describe('Text segment content. The actual text to display.'),
357
- style: z.object({
358
- bold: z.boolean().optional().describe('Whether to make text bold. Default is false, equivalent to **text** in Markdown.'),
359
- italic: z.boolean().optional().describe('Whether to make text italic. Default is false, equivalent to *text* in Markdown.'),
360
- underline: z.boolean().optional().describe('Whether to add underline. Default is false.'),
361
- strikethrough: z.boolean().optional().describe('Whether to add strikethrough. Default is false, equivalent to ~~text~~ in Markdown.'),
362
- inline_code: z.boolean().optional().describe('Whether to format as inline code. Default is false, equivalent to `code` in Markdown.'),
363
- text_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
364
- message: "Text color must be between 1 and 7 inclusive"
365
- }).describe('Text color value. Default is 0 (black). Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error.'),
366
- background_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
367
- message: "Background color must be between 1 and 7 inclusive"
368
- }).describe('Background color value. Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error.')
369
- }).optional().describe('Text style settings. Explicitly set style properties instead of relying on Markdown syntax conversion.'),
370
- })).describe('Array of text content objects with styles. A block can contain multiple text segments with different styles. Example: [{text:"Hello",style:{bold:true}},{text:" World",style:{italic:true}}]'),
371
- align: z.number().optional().default(1).describe('Text alignment: 1 for left (default), 2 for center, 3 for right.'),
372
- }).describe("Text block options. Only used when blockType is 'text'."),
373
- }),
374
- z.object({
375
- code: z.object({
376
- code: z.string().describe('Code content. The complete code text to display.'),
377
- language: z.number().optional().default(0).describe('Programming language code. Default is 0 (auto-detect). See documentation for full list of language codes.'),
378
- wrap: z.boolean().optional().default(false).describe('Whether to enable automatic line wrapping. Default is false.'),
379
- }).describe("Code block options. Only used when blockType is 'code'."),
380
- }),
381
- z.object({
382
- heading: z.object({
383
- level: z.number().min(1).max(9).describe('Heading level from 1 to 9, where 1 is the largest (h1) and 9 is the smallest (h9).'),
384
- content: z.string().describe('Heading text content. The actual text of the heading.'),
385
- align: z.number().optional().default(1).refine(val => val === 1 || val === 2 || val === 3, {
386
- message: "Alignment must be one of: 1 (left), 2 (center), or 3 (right)"
387
- }).describe('Text alignment: 1 for left (default), 2 for center, 3 for right. Only these three values are allowed.'),
388
- }).describe("Heading block options. Only used when blockType is 'heading'."),
389
- }),
390
- z.object({
391
- list: z.object({
392
- content: z.string().describe('List item content. The actual text of the list item.'),
393
- isOrdered: z.boolean().optional().default(false).describe('Whether this is an ordered (numbered) list item. Default is false (bullet point/unordered).'),
394
- align: z.number().optional().default(1).refine(val => val === 1 || val === 2 || val === 3, {
395
- message: "Alignment must be one of: 1 (left), 2 (center), or 3 (right)"
396
- }).describe('Text alignment: 1 for left (default), 2 for center, 3 for right. Only these three values are allowed.'),
397
- }).describe("List block options. Only used when blockType is 'list'."),
398
- }),
399
- ]).describe('Options for the specific block type. Must provide the corresponding options object based on blockType.'),
400
- })).max(50).describe('Array of block configurations (required). Each element contains blockType and options properties. Example: [{blockType:"text",options:{text:{textStyles:[{text:"Hello",style:{bold:true}}]}}},{blockType:"code",options:{code:{code:"console.log(\'Hello\')",language:30}}}]. Maximum 50 blocks per call.'),
345
+ this.server.tool('create_feishu_common_block', 'Create common blocks in a Feishu document (supports text, code, and heading blocks)', {
346
+ documentId: z
347
+ .string()
348
+ .describe('Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)'),
349
+ parentBlockId: z
350
+ .string()
351
+ .describe('Parent block ID (NOT URL) where the new blocks will be added as children. This should be the raw block ID without any URL prefix. When adding blocks at the page level (root level), use the extracted document ID from documentId parameter'),
352
+ startIndex: z
353
+ .number()
354
+ .optional()
355
+ .default(0)
356
+ .describe('Starting insertion position index. Default is 0 (insert at the beginning). If individual blocks have their own index specified, those will take precedence'),
357
+ blocks: z
358
+ .array(z.object({
359
+ blockType: z
360
+ .enum(['text', 'code', 'heading'])
361
+ .describe("Type of block to create: 'text', 'code', or 'heading'"),
362
+ options: z
363
+ .object({
364
+ // 文本块选项 - 当blockType为'text'时使用
365
+ text: z
366
+ .object({
367
+ // 文本内容数组,每个元素包含文本内容和样式
368
+ textStyles: z
369
+ .array(z.object({
370
+ text: z.string().describe('Text segment content'),
371
+ style: z
372
+ .object({
373
+ bold: z
374
+ .boolean()
375
+ .optional()
376
+ .describe('Whether to make text bold. Default is false'),
377
+ italic: z
378
+ .boolean()
379
+ .optional()
380
+ .describe('Whether to make text italic. Default is false'),
381
+ underline: z
382
+ .boolean()
383
+ .optional()
384
+ .describe('Whether to add underline. Default is false'),
385
+ strikethrough: z
386
+ .boolean()
387
+ .optional()
388
+ .describe('Whether to add strikethrough. Default is false'),
389
+ inline_code: z
390
+ .boolean()
391
+ .optional()
392
+ .describe('Whether to format as inline code. Default is false'),
393
+ text_color: z
394
+ .number()
395
+ .optional()
396
+ .describe('Text color as a number. Default is 0'),
397
+ })
398
+ .optional()
399
+ .describe('Text style settings'),
400
+ }))
401
+ .optional()
402
+ .describe('Array of text content objects with styles. If not provided, content will be used as plain text'),
403
+ align: z
404
+ .number()
405
+ .optional()
406
+ .default(1)
407
+ .describe('Text alignment: 1 for left, 2 for center, 3 for right. Default is 1'),
408
+ })
409
+ .optional()
410
+ .describe("Text block options. Only used when blockType is 'text'"),
411
+ // 代码块选项 - 当blockType为'code'时使用
412
+ code: z
413
+ .object({
414
+ code: z.string().describe('Code content'),
415
+ language: z
416
+ .number()
417
+ .optional()
418
+ .default(0)
419
+ .describe('Programming language code as a number. Available options:\n1: PlainText, 2: ABAP, 3: Ada, 4: Apache, 5: Apex, 6: Assembly Language, 7: Bash, 8: CSharp, 9: C++, 10: C, 11: COBOL, 12: CSS, 13: CoffeeScript, 14: D, 15: Dart, 16: Delphi, 17: Django, 18: Dockerfile, 19: Erlang, 20: Fortran, 22: Go, 23: Groovy, 24: HTML, 25: HTMLBars, 26: HTTP, 27: Haskell, 28: JSON, 29: Java, 30: JavaScript, 31: Julia, 32: Kotlin, 33: LateX, 34: Lisp, 36: Lua, 37: MATLAB, 38: Makefile, 39: Markdown, 40: Nginx, 41: Objective-C, 43: PHP, 44: Perl, 46: Power Shell, 47: Prolog, 48: ProtoBuf, 49: Python, 50: R, 52: Ruby, 53: Rust, 54: SAS, 55: SCSS, 56: SQL, 57: Scala, 58: Scheme, 60: Shell, 61: Swift, 62: Thrift, 63: TypeScript, 64: VBScript, 65: Visual Basic, 66: XML, 67: YAML, 68: CMake, 69: Diff, 70: Gherkin, 71: GraphQL, 72: OpenGL Shading Language, 73: Properties, 74: Solidity, 75: TOML'),
420
+ wrap: z
421
+ .boolean()
422
+ .optional()
423
+ .default(false)
424
+ .describe('Whether to enable automatic line wrapping for code blocks. Default is false'),
425
+ })
426
+ .optional()
427
+ .describe("Code block options. Only used when blockType is 'code'"),
428
+ // 标题块选项 - 当blockType为'heading'时使用
429
+ heading: z
430
+ .object({
431
+ level: z
432
+ .number()
433
+ .min(1)
434
+ .max(9)
435
+ .describe('Heading level from 1 to 9, where 1 is the largest heading (h1) and 9 is the smallest (h9)'),
436
+ content: z.string().describe('Heading text content'),
437
+ align: z
438
+ .number()
439
+ .optional()
440
+ .default(1)
441
+ .describe('Text alignment: 1 for left, 2 for center, 3 for right. Default is 1'),
442
+ })
443
+ .optional()
444
+ .describe("Heading block options. Only used when blockType is 'heading'"),
445
+ })
446
+ .optional()
447
+ .default({}),
448
+ }))
449
+ .describe('Array of block configurations to create in a single API call'),
401
450
  }, async ({ documentId, parentBlockId, startIndex = 0, blocks }) => {
402
451
  try {
403
452
  if (!this.feishuService) {
@@ -410,14 +459,6 @@ export class FeishuMcpServer {
410
459
  ],
411
460
  };
412
461
  }
413
- if (blocks.length > 50) {
414
- return {
415
- content: [{
416
- type: 'text',
417
- text: '错误: 每次调用最多只能创建50个块。请分批次创建或减少块数量。'
418
- }],
419
- };
420
- }
421
462
  Logger.log(`开始批量创建飞书块,文档ID: ${documentId},父块ID: ${parentBlockId},块数量: ${blocks.length},起始插入位置: ${startIndex}`);
422
463
  // 准备要创建的块内容数组
423
464
  const blockContents = [];
@@ -429,66 +470,45 @@ export class FeishuMcpServer {
429
470
  switch (blockType) {
430
471
  case 'text':
431
472
  // 处理文本块
432
- {
433
- // 类型检查,确保options包含text属性
434
- if ('text' in options && options.text) {
435
- const textOptions = options.text;
436
- const textStyles = textOptions.textStyles || [];
437
- if (textStyles.length === 0) {
438
- textStyles.push({ text: '', style: {} });
439
- }
440
- const align = textOptions.align || 1;
441
- blockContent = this.feishuService.createTextBlockContent(textStyles, align);
442
- }
443
- break;
473
+ const textOptions = options.text || {
474
+ textStyles: [],
475
+ align: 1,
476
+ };
477
+ // 确保textStyles是一个有效的数组
478
+ const textStyles = textOptions.textStyles || [];
479
+ // 如果textStyles为空,添加一个默认的空文本
480
+ if (textStyles.length === 0) {
481
+ textStyles.push({
482
+ text: '',
483
+ style: {}, // 添加空的style对象作为默认值
484
+ });
444
485
  }
486
+ const align = textOptions.align || 1;
487
+ blockContent = this.feishuService.createTextBlockContent(textStyles, align);
488
+ break;
445
489
  case 'code':
446
490
  // 处理代码块
447
- {
448
- // 类型检查,确保options包含code属性
449
- if ('code' in options && options.code) {
450
- const codeOptions = options.code;
451
- const codeContent = codeOptions.code || '';
452
- const language = codeOptions.language || 0;
453
- const wrap = codeOptions.wrap || false;
454
- blockContent = this.feishuService.createCodeBlockContent(codeContent, language, wrap);
455
- }
491
+ const codeOptions = options.code;
492
+ if (codeOptions == null) {
456
493
  break;
457
494
  }
495
+ const codeContent = codeOptions.code || '';
496
+ const language = codeOptions.language || 0;
497
+ const wrap = codeOptions.wrap || false;
498
+ blockContent = this.feishuService.createCodeBlockContent(codeContent, language, wrap);
499
+ break;
458
500
  case 'heading':
459
501
  // 处理标题块
460
- {
461
- // 类型检查,确保options包含heading属性
462
- if ('heading' in options && options.heading) {
463
- const headingOptions = options.heading;
464
- if (headingOptions.content) {
465
- const headingContent = headingOptions.content;
466
- const level = headingOptions.level || 1;
467
- // 确保对齐方式值在合法范围内
468
- const headingAlign = (headingOptions.align === 1 || headingOptions.align === 2 || headingOptions.align === 3)
469
- ? headingOptions.align : 1;
470
- blockContent = this.feishuService.createHeadingBlockContent(headingContent, level, headingAlign);
471
- }
472
- }
473
- break;
474
- }
475
- case 'list':
476
- // 处理列表块
477
- {
478
- // 类型检查,确保options包含list属性
479
- if ('list' in options && options.list) {
480
- const listOptions = options.list;
481
- if (listOptions.content) {
482
- const content = listOptions.content;
483
- const isOrdered = listOptions.isOrdered || false;
484
- // 确保对齐方式值在合法范围内
485
- const align = (listOptions.align === 1 || listOptions.align === 2 || listOptions.align === 3)
486
- ? listOptions.align : 1;
487
- blockContent = this.feishuService.createListBlockContent(content, isOrdered, align);
488
- }
489
- }
502
+ if (options.heading == null ||
503
+ options.heading.content == null) {
490
504
  break;
491
505
  }
506
+ const headingOptions = options.heading || {};
507
+ const headingContent = headingOptions.content || '';
508
+ const level = headingOptions.level || 1;
509
+ const headingAlign = headingOptions.align || 1;
510
+ blockContent = this.feishuService.createHeadingBlockContent(headingContent, level, headingAlign);
511
+ break;
492
512
  }
493
513
  if (blockContent) {
494
514
  blockContents.push(blockContent);
@@ -504,171 +524,60 @@ export class FeishuMcpServer {
504
524
  }
505
525
  catch (error) {
506
526
  Logger.error(`批量创建飞书块失败:`, error);
507
- const errorMessage = formatErrorMessage(error);
508
- return {
509
- content: [{ type: 'text', text: `批量创建飞书块失败: ${errorMessage}` }],
510
- };
511
- }
512
- });
513
- // 添加创建飞书文本块工具
514
- this.server.tool("create_feishu_single_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.", {
515
- documentId: z.string().describe("Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf"),
516
- parentBlockId: z.string().describe("Parent block ID (required). Target block ID where content will be added, without any URL prefix. For page-level (root level) insertion, extract and use only the document ID portion (not the full URL) as parentBlockId. Obtain existing block IDs using the get_feishu_doc_blocks tool."),
517
- textContents: z.array(z.object({
518
- text: z.string().describe("Text content. Provide plain text without markdown syntax; use style object for formatting."),
519
- style: z.object({
520
- bold: z.boolean().optional().describe("Whether to make text bold. Default is false, equivalent to **text** in Markdown."),
521
- italic: z.boolean().optional().describe("Whether to make text italic. Default is false, equivalent to *text* in Markdown."),
522
- underline: z.boolean().optional().describe("Whether to add underline. Default is false."),
523
- strikethrough: z.boolean().optional().describe("Whether to add strikethrough. Default is false, equivalent to ~~text~~ in Markdown."),
524
- inline_code: z.boolean().optional().describe("Whether to format as inline code. Default is false, equivalent to `code` in Markdown."),
525
- text_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
526
- message: "Text color must be between 1 and 7 inclusive"
527
- }).describe("Text color value. Default is 0 (black). Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error."),
528
- background_color: z.number().optional().refine(val => !val || (val >= 1 && val <= 7), {
529
- message: "Background color must be between 1 and 7 inclusive"
530
- }).describe('Background color value. Available values are only: 1 (gray), 2 (brown), 3 (orange), 4 (yellow), 5 (green), 6 (blue), 7 (purple). Values outside this range will cause an error.')
531
- }).optional().describe("Text style settings. Explicitly set style properties instead of relying on Markdown syntax conversion.")
532
- })).describe("Array of text content objects. A block can contain multiple text segments with different styles. Example: [{text:'Hello',style:{bold:true}},{text:' World',style:{italic:true}}]"),
533
- align: z.number().optional().default(1).describe("Text alignment: 1 for left (default), 2 for center, 3 for right."),
534
- index: z.number().describe("Insertion position index (required). Specifies where the block should be inserted. Use 0 to insert at the beginning. Use get_feishu_doc_blocks tool to understand document structure if unsure. For consecutive insertions, calculate next index as previous index + 1.")
535
- }, async ({ documentId, parentBlockId, textContents, align = 1, index }) => {
536
- try {
537
- if (!this.feishuService) {
538
- return {
539
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
540
- };
541
- }
542
- Logger.log(`开始创建飞书文本块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
543
- const result = await this.feishuService.createTextBlock(documentId, parentBlockId, textContents, align, index);
544
- Logger.log(`飞书文本块创建成功`);
545
- return {
546
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
547
- };
548
- }
549
- catch (error) {
550
- Logger.error(`创建飞书文本块失败:`, error);
551
- const errorMessage = formatErrorMessage(error);
552
527
  return {
553
- content: [{ type: "text", text: `创建飞书文本块失败: ${errorMessage}` }],
554
- };
555
- }
556
- });
557
- // 添加创建飞书代码块工具
558
- this.server.tool("create_feishu_single_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.", {
559
- documentId: z.string().describe("Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf"),
560
- parentBlockId: z.string().describe("Parent block ID (required). Target block ID where content will be added, without any URL prefix. For page-level (root level) insertion, extract and use only the document ID portion (not the full URL) as parentBlockId. Obtain existing block IDs using the get_feishu_doc_blocks tool."),
561
- code: z.string().describe("Code content (required). The complete code text to display."),
562
- language: z.number().optional().default(0).describe("Programming language code (optional). Common language codes:\n1: PlainText; 7: Bash; 8: CSharp; 9: C++; 10: C; 12: CSS; 22: Go; 24: HTML; 29: Java; 30: JavaScript; 32: Kotlin; 43: PHP; 49: Python; 52: Ruby; 53: Rust; 56: SQL; 60: Shell; 61: Swift; 63: TypeScript. Default is 0 (auto-detect)."),
563
- wrap: z.boolean().optional().default(false).describe("Enable automatic line wrapping (optional). Default is false (no auto-wrap). Set to true to improve readability for long code lines."),
564
- index: z.number().describe("Insertion position index (required). Specifies where the block should be inserted. Use 0 to insert at the beginning. Use get_feishu_doc_blocks tool to understand document structure if unsure. For consecutive insertions, calculate next index as previous index + 1.")
565
- }, async ({ documentId, parentBlockId, code, language = 0, wrap = false, index = 0 }) => {
566
- try {
567
- if (!this.feishuService) {
568
- return {
569
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
570
- };
571
- }
572
- Logger.log(`开始创建飞书代码块,文档ID: ${documentId},父块ID: ${parentBlockId},语言: ${language},自动换行: ${wrap},插入位置: ${index}`);
573
- const result = await this.feishuService.createCodeBlock(documentId, parentBlockId, code, language, wrap, index);
574
- Logger.log(`飞书代码块创建成功`);
575
- return {
576
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
577
- };
578
- }
579
- catch (error) {
580
- Logger.error(`创建飞书代码块失败:`, error);
581
- const errorMessage = formatErrorMessage(error);
582
- return {
583
- content: [{ type: "text", text: `创建飞书代码块失败: ${errorMessage}` }],
584
- };
585
- }
586
- });
587
- // 添加创建飞书标题块工具
588
- this.server.tool("create_feishu_single_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.", {
589
- documentId: z.string().describe("Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf"),
590
- parentBlockId: z.string().describe("Parent block ID (required). Target block ID where content will be added, without any URL prefix. For page-level (root level) insertion, extract and use only the document ID portion (not the full URL) as parentBlockId. Obtain existing block IDs using the get_feishu_doc_blocks tool."),
591
- 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)."),
592
- content: z.string().describe("Heading text content (required). The actual text of the heading."),
593
- align: z.number().optional().default(1).refine(val => val === 1 || val === 2 || val === 3, {
594
- message: "Alignment must be one of: 1 (left), 2 (center), or 3 (right)"
595
- }).describe("Text alignment (optional): 1 for left (default), 2 for center, 3 for right. Only these three values are allowed."),
596
- index: z.number().describe("Insertion position index (required). Specifies where the block should be inserted. Use 0 to insert at the beginning. Use get_feishu_doc_blocks tool to understand document structure if unsure. For consecutive insertions, calculate next index as previous index + 1.")
597
- }, async ({ documentId, parentBlockId, level, content, align = 1, index = 0 }) => {
598
- try {
599
- if (!this.feishuService) {
600
- return {
601
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
602
- };
603
- }
604
- // 确保align值在合法范围内(1-3)
605
- if (align !== 1 && align !== 2 && align !== 3) {
606
- return {
607
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
608
- };
609
- }
610
- Logger.log(`开始创建飞书标题块,文档ID: ${documentId},父块ID: ${parentBlockId},标题级别: ${level},对齐方式: ${align},插入位置: ${index}`);
611
- const result = await this.feishuService.createHeadingBlock(documentId, parentBlockId, content, level, index, align);
612
- Logger.log(`飞书标题块创建成功`);
613
- return {
614
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
615
- };
616
- }
617
- catch (error) {
618
- Logger.error(`创建飞书标题块失败:`, error);
619
- const errorMessage = formatErrorMessage(error);
620
- return {
621
- content: [{ type: "text", text: `创建飞书标题块失败: ${errorMessage}` }],
622
- };
623
- }
624
- });
625
- // 添加创建飞书列表块工具
626
- this.server.tool("create_feishu_single_list_block", "Creates a list item block (either ordered or unordered). Perfect for creating hierarchical and structured content with bullet points or numbered lists.", {
627
- documentId: z.string().describe("Document ID or URL (required). Supports the following formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID: e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf"),
628
- parentBlockId: z.string().describe("Parent block ID (required). Target block ID where content will be added, without any URL prefix. For page-level (root level) insertion, extract and use only the document ID portion (not the full URL) as parentBlockId. Obtain existing block IDs using the get_feishu_doc_blocks tool."),
629
- content: z.string().describe("List item content (required). The actual text of the list item."),
630
- isOrdered: z.boolean().optional().default(false).describe("Whether this is an ordered (numbered) list item. Default is false (bullet point/unordered)."),
631
- align: z.number().optional().default(1).refine(val => val === 1 || val === 2 || val === 3, {
632
- message: "Alignment must be one of: 1 (left), 2 (center), or 3 (right)"
633
- }).describe("Text alignment (optional): 1 for left (default), 2 for center, 3 for right. Only these three values are allowed."),
634
- index: z.number().describe("Insertion position index (required). Specifies where the block should be inserted. Use 0 to insert at the beginning. Use get_feishu_doc_blocks tool to understand document structure if unsure. For consecutive insertions, calculate next index as previous index + 1.")
635
- }, async ({ documentId, parentBlockId, content, isOrdered = false, align = 1, index = 0 }) => {
636
- try {
637
- if (!this.feishuService) {
638
- return {
639
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
640
- };
641
- }
642
- // 确保align值在合法范围内(1-3)
643
- if (align !== 1 && align !== 2 && align !== 3) {
644
- return {
645
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
646
- };
647
- }
648
- const listType = isOrdered ? "有序" : "无序";
649
- Logger.log(`开始创建飞书${listType}列表块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
650
- const result = await this.feishuService.createListBlock(documentId, parentBlockId, content, isOrdered, index, align);
651
- Logger.log(`飞书${listType}列表块创建成功`);
652
- return {
653
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
654
- };
655
- }
656
- catch (error) {
657
- Logger.error(`创建飞书列表块失败:`, error);
658
- const errorMessage = formatErrorMessage(error);
659
- return {
660
- content: [{ type: "text", text: `创建飞书列表块失败: ${errorMessage}` }],
528
+ content: [{ type: 'text', text: `批量创建飞书块失败: ${error}` }],
661
529
  };
662
530
  }
663
531
  });
532
+ // // 添加创建飞书标题块工具
533
+ // this.server.tool(
534
+ // "create_feishu_heading_block",
535
+ // "Create a heading block in a Feishu document with specified level (1-9)",
536
+ // {
537
+ // documentId: z.string().describe("Document ID or URL. Supported formats:\n1. Standard document URL: https://xxx.feishu.cn/docs/xxx or https://xxx.feishu.cn/docx/xxx\n2. API URL: https://open.feishu.cn/open-apis/doc/v2/documents/xxx\n3. Direct document ID (e.g., JcKbdlokYoPIe0xDzJ1cduRXnRf)"),
538
+ // parentBlockId: z.string().describe("Parent block ID (NOT URL) where the new block will be added as a child. This should be the raw block ID without any URL prefix. When adding blocks at the page level (root level), use the extracted document ID from documentId parameter"),
539
+ // level: z.number().min(1).max(9).describe("Heading level from 1 to 9, where 1 is the largest heading (h1) and 9 is the smallest (h9)"),
540
+ // content: z.string().describe("Heading text content"),
541
+ // index: z.number().optional().default(0).describe("Insertion position index. Default is 0 (insert at the beginning). If unsure about the position, use the get_feishu_doc_blocks tool first to understand the document structure. For consecutive insertions, calculate the next position as previous_index + 1 to avoid querying document structure repeatedly")
542
+ // },
543
+ // async ({ documentId, parentBlockId, level, content, index = 0 }) => {
544
+ // try {
545
+ // if (!this.feishuService) {
546
+ // return {
547
+ // content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
548
+ // };
549
+ // }
550
+ //
551
+ // Logger.log(`开始创建飞书标题块,文档ID: ${documentId},父块ID: ${parentBlockId},标题级别: ${level},插入位置: ${index}`);
552
+ // const result = await this.feishuService.createHeadingBlock(documentId, parentBlockId, content, level, index);
553
+ // Logger.log(`飞书标题块创建成功`);
554
+ //
555
+ // return {
556
+ // content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
557
+ // };
558
+ // } catch (error) {
559
+ // Logger.error(`创建飞书标题块失败:`, error);
560
+ // return {
561
+ // content: [{ type: "text", text: `创建飞书标题块失败: ${error}` }],
562
+ // };
563
+ // }
564
+ // },
565
+ // );
664
566
  }
665
567
  async connect(transport) {
568
+ // Logger.log("Connecting to transport...");
666
569
  await this.server.connect(transport);
667
570
  Logger.log = (...args) => {
668
- this.server.server.sendLoggingMessage({ level: 'info', data: args });
571
+ this.server.server.sendLoggingMessage({
572
+ level: 'info',
573
+ data: args,
574
+ });
669
575
  };
670
576
  Logger.error = (...args) => {
671
- this.server.server.sendLoggingMessage({ level: 'error', data: args });
577
+ this.server.server.sendLoggingMessage({
578
+ level: 'error',
579
+ data: args,
580
+ });
672
581
  };
673
582
  Logger.log('Server connected and ready to process requests');
674
583
  }
@@ -41,36 +41,6 @@ export class FeishuService {
41
41
  this.appId = appId;
42
42
  this.appSecret = appSecret;
43
43
  }
44
- // 包装和重新抛出错误的辅助方法
45
- wrapAndThrowError(message, originalError) {
46
- Logger.error(`${message}:`, originalError);
47
- // 如果原始错误已经是FeishuError格式,直接重新抛出
48
- if (originalError && typeof originalError === 'object' && 'status' in originalError && 'err' in originalError) {
49
- throw originalError;
50
- }
51
- // 如果是AxiosError,抽取有用信息
52
- if (originalError instanceof AxiosError && originalError.response) {
53
- throw {
54
- status: originalError.response.status,
55
- err: `${message}: ${originalError.response.data?.msg || originalError.message || 'Unknown error'}`,
56
- apiError: originalError.response.data
57
- };
58
- }
59
- // 其他类型的错误,包装为一致的格式
60
- if (originalError instanceof Error) {
61
- throw {
62
- status: 500,
63
- err: `${message}: ${originalError.message}`,
64
- apiError: originalError
65
- };
66
- }
67
- // 未知错误类型
68
- throw {
69
- status: 500,
70
- err: message,
71
- apiError: originalError
72
- };
73
- }
74
44
  isTokenExpired() {
75
45
  if (!this.accessToken || !this.tokenExpireTime)
76
46
  return true;
@@ -92,7 +62,7 @@ export class FeishuService {
92
62
  Logger.log(`请求方法: POST`);
93
63
  Logger.log(`请求数据: ${JSON.stringify(requestData, null, 2)}`);
94
64
  const response = await axios.post(url, requestData);
95
- Logger.log(`响应状态码: ${response?.status}`);
65
+ Logger.log(`响应状态码: ${response.status}`);
96
66
  Logger.log(`响应头: ${JSON.stringify(response.headers, null, 2)}`);
97
67
  Logger.log(`响应数据: ${JSON.stringify(response.data, null, 2)}`);
98
68
  if (response.data.code !== 0) {
@@ -100,7 +70,6 @@ export class FeishuService {
100
70
  throw {
101
71
  status: response.status,
102
72
  err: response.data.msg || "Unknown error",
103
- apiError: response.data
104
73
  };
105
74
  }
106
75
  this.accessToken = response.data.tenant_access_token;
@@ -117,7 +86,6 @@ export class FeishuService {
117
86
  throw {
118
87
  status: error.response.status,
119
88
  err: error.response.data?.msg || "Unknown error",
120
- apiError: error.response.data
121
89
  };
122
90
  }
123
91
  Logger.error('获取访问令牌时发生未知错误:', error);
@@ -160,7 +128,6 @@ export class FeishuService {
160
128
  throw {
161
129
  status: error.response.status,
162
130
  err: error.response.data?.msg || "Unknown error",
163
- apiError: error.response.data
164
131
  };
165
132
  }
166
133
  Logger.error('发送请求时发生未知错误:', error);
@@ -190,7 +157,16 @@ export class FeishuService {
190
157
  return docInfo;
191
158
  }
192
159
  catch (error) {
193
- this.wrapAndThrowError('创建文档失败', error);
160
+ Logger.error(`创建文档失败:`, error);
161
+ if (error instanceof AxiosError) {
162
+ Logger.error(`请求URL: ${error.config?.url}`);
163
+ Logger.error(`请求方法: ${error.config?.method?.toUpperCase()}`);
164
+ Logger.error(`状态码: ${error.response?.status}`);
165
+ if (error.response?.data) {
166
+ Logger.error(`错误详情: ${JSON.stringify(error.response.data, null, 2)}`);
167
+ }
168
+ }
169
+ throw error;
194
170
  }
195
171
  }
196
172
  // 获取文档信息
@@ -407,9 +383,6 @@ export class FeishuService {
407
383
  createHeadingBlockContent(text, level = 1, align = 1) {
408
384
  // 确保标题级别在有效范围内(1-9)
409
385
  const safeLevel = Math.max(1, Math.min(9, level));
410
- // 确保align值在合法范围内(1-3)
411
- // 1表示居左,2表示居中,3表示居右
412
- const safeAlign = (align === 1 || align === 2 || align === 3) ? align : 1;
413
386
  // 根据标题级别设置block_type和对应的属性名
414
387
  // 飞书API中,一级标题的block_type为3,二级标题为4,以此类推
415
388
  const blockType = 2 + safeLevel; // 一级标题为3,二级标题为4,以此类推
@@ -429,7 +402,7 @@ export class FeishuService {
429
402
  }
430
403
  ],
431
404
  style: {
432
- align: safeAlign,
405
+ align: align,
433
406
  folded: false
434
407
  }
435
408
  };
@@ -469,10 +442,7 @@ export class FeishuService {
469
442
  if (!docId) {
470
443
  throw new Error(`无效的文档ID: ${documentId}`);
471
444
  }
472
- // 确保align值在合法范围内(1-3)
473
- // 1表示居左,2表示居中,3表示居右
474
- const safeAlign = (align === 1 || align === 2 || align === 3) ? align : 1;
475
- Logger.log(`开始创建标题块,文档ID: ${docId},父块ID: ${parentBlockId},标题级别: ${level},对齐方式: ${safeAlign},插入位置: ${index}`);
445
+ Logger.log(`开始创建标题块,文档ID: ${docId},父块ID: ${parentBlockId},标题级别: ${level},插入位置: ${index}`);
476
446
  // 确保标题级别在有效范围内(1-9)
477
447
  const safeLevel = Math.max(1, Math.min(9, level));
478
448
  // 根据标题级别设置block_type和对应的属性名
@@ -494,7 +464,7 @@ export class FeishuService {
494
464
  }
495
465
  ],
496
466
  style: {
497
- align: safeAlign,
467
+ align: align,
498
468
  folded: false
499
469
  }
500
470
  };
@@ -502,110 +472,8 @@ export class FeishuService {
502
472
  return await this.createDocumentBlock(documentId, parentBlockId, blockContent, index);
503
473
  }
504
474
  catch (error) {
505
- this.wrapAndThrowError(`创建标题块失败`, error);
506
- }
507
- }
508
- // 获取块内容
509
- async getBlockContent(documentId, blockId) {
510
- try {
511
- const docId = this.extractDocIdFromUrl(documentId);
512
- if (!docId) {
513
- throw new Error(`无效的文档ID: ${documentId}`);
514
- }
515
- Logger.log(`开始获取块内容,文档ID: ${docId},块ID: ${blockId}`);
516
- const endpoint = `/docx/v1/documents/${docId}/blocks/${blockId}?document_revision_id=-1`;
517
- Logger.log(`准备请求API端点: ${endpoint}`);
518
- const response = await this.request(endpoint);
519
- if (response.code !== 0) {
520
- throw new Error(`获取块内容失败: ${response.msg}`);
521
- }
522
- const blockContent = response.data?.block;
523
- Logger.log(`块内容获取成功: ${JSON.stringify(blockContent, null, 2)}`);
524
- return blockContent;
525
- }
526
- catch (error) {
527
- this.wrapAndThrowError(`获取块内容失败`, error);
528
- }
529
- }
530
- // 更新块文本内容
531
- async updateBlockTextContent(documentId, blockId, textElements) {
532
- try {
533
- const docId = this.extractDocIdFromUrl(documentId);
534
- if (!docId) {
535
- throw new Error(`无效的文档ID: ${documentId}`);
536
- }
537
- Logger.log(`开始更新块文本内容,文档ID: ${docId},块ID: ${blockId}`);
538
- const endpoint = `/docx/v1/documents/${docId}/blocks/${blockId}?document_revision_id=-1`;
539
- Logger.log(`准备请求API端点: ${endpoint}`);
540
- const elements = textElements.map(item => ({
541
- text_run: {
542
- content: item.text,
543
- text_element_style: item.style || {}
544
- }
545
- }));
546
- const data = {
547
- update_text_elements: {
548
- elements: elements
549
- }
550
- };
551
- Logger.log(`请求数据: ${JSON.stringify(data, null, 2)}`);
552
- const response = await this.request(endpoint, 'PATCH', data);
553
- if (response.code !== 0) {
554
- throw new Error(`更新块文本内容失败: ${response.msg}`);
555
- }
556
- Logger.log(`块文本内容更新成功: ${JSON.stringify(response.data, null, 2)}`);
557
- return response.data;
558
- }
559
- catch (error) {
560
- this.wrapAndThrowError(`更新块文本内容失败`, error);
561
- }
562
- }
563
- // 创建列表块内容(有序或无序)
564
- createListBlockContent(text, isOrdered = false, align = 1) {
565
- // 确保 align 值在合法范围内(1-3)
566
- const safeAlign = (align === 1 || align === 2 || align === 3) ? align : 1;
567
- // 有序列表是 block_type: 13,无序列表是 block_type: 12
568
- const blockType = isOrdered ? 13 : 12;
569
- const propertyKey = isOrdered ? "ordered" : "bullet";
570
- // 构建块内容
571
- const blockContent = {
572
- block_type: blockType
573
- };
574
- // 设置列表属性
575
- blockContent[propertyKey] = {
576
- elements: [
577
- {
578
- text_run: {
579
- content: text,
580
- text_element_style: {}
581
- }
582
- }
583
- ],
584
- style: {
585
- align: safeAlign,
586
- folded: false
587
- }
588
- };
589
- return blockContent;
590
- }
591
- // 创建列表块(有序或无序)
592
- async createListBlock(documentId, parentBlockId, text, isOrdered = false, index = 0, align = 1) {
593
- try {
594
- const docId = this.extractDocIdFromUrl(documentId);
595
- if (!docId) {
596
- throw new Error(`无效的文档ID: ${documentId}`);
597
- }
598
- // 确保align值在合法范围内(1-3)
599
- const safeAlign = (align === 1 || align === 2 || align === 3) ? align : 1;
600
- const listType = isOrdered ? "有序" : "无序";
601
- Logger.log(`开始创建${listType}列表块,文档ID: ${docId},父块ID: ${parentBlockId},对齐方式: ${safeAlign},插入位置: ${index}`);
602
- // 创建列表块内容
603
- const blockContent = this.createListBlockContent(text, isOrdered, safeAlign);
604
- Logger.log(`列表块内容: ${JSON.stringify(blockContent, null, 2)}`);
605
- return await this.createDocumentBlock(documentId, parentBlockId, blockContent, index);
606
- }
607
- catch (error) {
608
- this.wrapAndThrowError(`创建${isOrdered ? "有序" : "无序"}列表块失败`, error);
475
+ Logger.error(`创建标题块失败:`, error);
476
+ throw error;
609
477
  }
610
478
  }
611
479
  extractDocIdFromUrl(url) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feishu-mcp",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Model Context Protocol server for Feishu integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",