feishu-mcp 0.0.3 → 0.0.5

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
@@ -1,12 +1,136 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { z } from "zod";
3
- import { FeishuService } from "./services/feishu.js";
4
- import express from "express";
5
- import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ import { FeishuService } from './services/feishu.js';
4
+ import express from 'express';
5
+ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
6
6
  export const Logger = {
7
- log: (...args) => { console.log(...args); },
8
- error: (...args) => { console.error(...args); },
7
+ log: (...args) => {
8
+ console.log(...args);
9
+ },
10
+ error: (...args) => {
11
+ console.error(...args);
12
+ },
9
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
+ }
10
134
  export class FeishuMcpServer {
11
135
  constructor(feishuConfig) {
12
136
  Object.defineProperty(this, "server", {
@@ -38,8 +162,8 @@ export class FeishuMcpServer {
38
162
  throw new Error('飞书服务初始化失败');
39
163
  }
40
164
  this.server = new McpServer({
41
- name: "Feishu MCP Server",
42
- version: "0.0.1",
165
+ name: 'Feishu MCP Server',
166
+ version: '0.0.1',
43
167
  }, {
44
168
  capabilities: {
45
169
  logging: {},
@@ -50,121 +174,364 @@ export class FeishuMcpServer {
50
174
  }
51
175
  registerTools() {
52
176
  // 添加创建飞书文档工具
53
- this.server.tool("create_feishu_doc", "Create a new Feishu document", {
54
- title: z.string().describe("Document title"),
55
- folderToken: z.string().optional().describe("Folder token where the document will be created. If not provided, the document will be created in the root directory"),
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".'),
56
180
  }, async ({ title, folderToken }) => {
57
181
  try {
58
- Logger.log(`开始创建飞书文档,标题: ${title}${folderToken ? `,文件夹Token: ${folderToken}` : ''}`);
59
- // @ts-ignore
60
- const newDoc = await this.feishuService.createDocument(title, folderToken);
61
- Logger.log(`飞书文档创建成功,文档ID: ${newDoc?.objToken || newDoc?.document_id}`);
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}`);
62
188
  return {
63
- content: [{ type: "text", text: JSON.stringify(newDoc, null, 2) }],
189
+ content: [{ type: 'text', text: JSON.stringify(newDoc, null, 2) }],
64
190
  };
65
191
  }
66
192
  catch (error) {
67
193
  Logger.error(`创建飞书文档失败:`, error);
194
+ const errorMessage = formatErrorMessage(error);
68
195
  return {
69
- content: [{ type: "text", text: `创建飞书文档失败: ${error}` }],
196
+ content: [{ type: 'text', text: `创建飞书文档失败: ${errorMessage}` }],
70
197
  };
71
198
  }
72
199
  });
73
200
  // 添加获取飞书文档信息工具
74
- // this.server.tool(
75
- // "get_feishu_doc_info",
76
- // "Get basic information about a Feishu document",
77
- // {
78
- // 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)"),
79
- // },
80
- // async ({ documentId }) => {
81
- // try {
82
- // if (!this.feishuService) {
83
- // return {
84
- // content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
85
- // };
86
- // }
87
- // Logger.log(`开始获取飞书文档信息,文档ID: ${documentId}`);
88
- // const docInfo = await this.feishuService.getDocumentInfo(documentId);
89
- // Logger.log(`飞书文档信息获取成功,标题: ${docInfo.title}`);
90
- // return {
91
- // content: [{ type: "text", text: JSON.stringify(docInfo, null, 2) }],
92
- // };
93
- // } catch (error) {
94
- // Logger.error(`获取飞书文档信息失败:`, error);
95
- // return {
96
- // content: [{ type: "text", text: `获取飞书文档信息失败: ${error}` }],
97
- // };
98
- // }
99
- // },
100
- // );
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
+ });
101
225
  // 添加获取飞书文档内容工具
102
- this.server.tool("get_feishu_doc_content", "Get the plain text content of a Feishu document", {
103
- 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)"),
104
- lang: z.number().optional().default(0).describe("Language code. Default is 0 (Chinese)"),
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.'),
105
229
  }, async ({ documentId, lang }) => {
106
230
  try {
107
231
  if (!this.feishuService) {
108
232
  return {
109
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
233
+ content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
110
234
  };
111
235
  }
112
236
  Logger.log(`开始获取飞书文档内容,文档ID: ${documentId},语言: ${lang}`);
113
237
  const content = await this.feishuService.getDocumentContent(documentId, lang);
114
238
  Logger.log(`飞书文档内容获取成功,内容长度: ${content.length}字符`);
115
239
  return {
116
- content: [{ type: "text", text: content }],
240
+ content: [{ type: 'text', text: content }],
117
241
  };
118
242
  }
119
243
  catch (error) {
120
244
  Logger.error(`获取飞书文档内容失败:`, error);
245
+ const errorMessage = formatErrorMessage(error);
121
246
  return {
122
- content: [{ type: "text", text: `获取飞书文档内容失败: ${error}` }],
247
+ content: [{ type: 'text', text: `获取飞书文档内容失败: ${errorMessage}` }],
123
248
  };
124
249
  }
125
250
  });
126
251
  // 添加获取飞书文档块工具
127
- 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", {
128
- 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)"),
129
- pageSize: z.number().optional().default(500).describe("Number of blocks per page. Default is 500"),
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.'),
130
255
  }, async ({ documentId, pageSize }) => {
131
256
  try {
132
257
  if (!this.feishuService) {
133
258
  return {
134
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
259
+ content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
135
260
  };
136
261
  }
137
262
  Logger.log(`开始获取飞书文档块,文档ID: ${documentId},页大小: ${pageSize}`);
138
263
  const blocks = await this.feishuService.getDocumentBlocks(documentId, pageSize);
139
264
  Logger.log(`飞书文档块获取成功,共 ${blocks.length} 个块`);
140
265
  return {
141
- content: [{ type: "text", text: JSON.stringify(blocks, null, 2) }],
266
+ content: [{ type: 'text', text: JSON.stringify(blocks, null, 2) }],
142
267
  };
143
268
  }
144
269
  catch (error) {
145
270
  Logger.error(`获取飞书文档块失败:`, error);
271
+ const errorMessage = formatErrorMessage(error);
272
+ return {
273
+ content: [{ type: 'text', text: `获取飞书文档块失败: ${errorMessage}` }],
274
+ };
275
+ }
276
+ });
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);
146
298
  return {
147
- content: [{ type: "text", text: `获取飞书文档块失败: ${error}` }],
299
+ content: [{ type: 'text', text: `获取飞书块内容失败: ${errorMessage}` }],
148
300
  };
149
301
  }
150
302
  });
151
- // 添加创建飞书文档块工具
152
- this.server.tool("create_feishu_text_block", "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)", {
153
- 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)"),
154
- 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"),
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 }) => {
324
+ try {
325
+ if (!this.feishuService) {
326
+ return {
327
+ content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
328
+ };
329
+ }
330
+ Logger.log(`开始更新飞书块文本内容,文档ID: ${documentId},块ID: ${blockId}`);
331
+ const result = await this.feishuService.updateBlockTextContent(documentId, blockId, textElements);
332
+ Logger.log(`飞书块文本内容更新成功`);
333
+ return {
334
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
335
+ };
336
+ }
337
+ catch (error) {
338
+ Logger.error(`更新飞书块文本内容失败:`, error);
339
+ const errorMessage = formatErrorMessage(error);
340
+ return {
341
+ content: [{ type: 'text', text: `更新飞书块文本内容失败: ${errorMessage}` }],
342
+ };
343
+ }
344
+ });
345
+ // 添加通用飞书块创建工具(支持文本、代码、标题)
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.'),
401
+ }, async ({ documentId, parentBlockId, startIndex = 0, blocks }) => {
402
+ try {
403
+ if (!this.feishuService) {
404
+ return {
405
+ content: [
406
+ {
407
+ type: 'text',
408
+ text: 'Feishu service is not initialized. Please check the configuration',
409
+ },
410
+ ],
411
+ };
412
+ }
413
+ if (blocks.length > 50) {
414
+ return {
415
+ content: [{
416
+ type: 'text',
417
+ text: '错误: 每次调用最多只能创建50个块。请分批次创建或减少块数量。'
418
+ }],
419
+ };
420
+ }
421
+ Logger.log(`开始批量创建飞书块,文档ID: ${documentId},父块ID: ${parentBlockId},块数量: ${blocks.length},起始插入位置: ${startIndex}`);
422
+ // 准备要创建的块内容数组
423
+ const blockContents = [];
424
+ // 处理每个块配置
425
+ for (const blockConfig of blocks) {
426
+ const { blockType, options = {} } = blockConfig;
427
+ // 使用指定的索引或当前索引
428
+ let blockContent;
429
+ switch (blockType) {
430
+ case 'text':
431
+ // 处理文本块
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;
444
+ }
445
+ case 'code':
446
+ // 处理代码块
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
+ }
456
+ break;
457
+ }
458
+ case 'heading':
459
+ // 处理标题块
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
+ }
490
+ break;
491
+ }
492
+ }
493
+ if (blockContent) {
494
+ blockContents.push(blockContent);
495
+ Logger.log(`已准备${blockType}块,内容: ${JSON.stringify(blockContent).substring(0, 100)}...`);
496
+ }
497
+ }
498
+ // 批量创建所有块
499
+ const result = await this.feishuService.createDocumentBlocks(documentId, parentBlockId, blockContents, startIndex);
500
+ Logger.log(`飞书块批量创建成功,共创建 ${blockContents.length} 个块`);
501
+ return {
502
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
503
+ };
504
+ }
505
+ catch (error) {
506
+ 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."),
155
517
  textContents: z.array(z.object({
156
- text: z.string().describe("Text content"),
518
+ text: z.string().describe("Text content. Provide plain text without markdown syntax; use style object for formatting."),
157
519
  style: z.object({
158
- bold: z.boolean().optional().describe("Whether to make text bold. Default is false"),
159
- italic: z.boolean().optional().describe("Whether to make text italic. Default is false"),
160
- underline: z.boolean().optional().describe("Whether to add underline. Default is false"),
161
- strikethrough: z.boolean().optional().describe("Whether to add strikethrough. Default is false"),
162
- inline_code: z.boolean().optional().describe("Whether to format as inline code. Default is false"),
163
- text_color: z.number().optional().describe("Text color as a number. Default is 0")
164
- }).optional().describe("Text style settings")
165
- })).describe("Array of text content objects. A block can contain multiple text segments with different styles"),
166
- align: z.number().optional().default(1).describe("Text alignment: 1 for left, 2 for center, 3 for right. Default is 1"),
167
- 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")
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.")
168
535
  }, async ({ documentId, parentBlockId, textContents, align = 1, index }) => {
169
536
  try {
170
537
  if (!this.feishuService) {
@@ -172,35 +539,8 @@ export class FeishuMcpServer {
172
539
  content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
173
540
  };
174
541
  }
175
- // 处理Markdown语法转换
176
- const processedTextContents = textContents.map(content => {
177
- let { text, style = {} } = content;
178
- // 创建一个新的style对象,避免修改原始对象
179
- const newStyle = { ...style };
180
- // 处理粗体 **text**
181
- if (text.match(/\*\*([^*]+)\*\*/g)) {
182
- text = text.replace(/\*\*([^*]+)\*\*/g, "$1");
183
- newStyle.bold = true;
184
- }
185
- // 处理斜体 *text*
186
- if (text.match(/(?<!\*)\*([^*]+)\*(?!\*)/g)) {
187
- text = text.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, "$1");
188
- newStyle.italic = true;
189
- }
190
- // 处理删除线 ~~text~~
191
- if (text.match(/~~([^~]+)~~/g)) {
192
- text = text.replace(/~~([^~]+)~~/g, "$1");
193
- newStyle.strikethrough = true;
194
- }
195
- // 处理行内代码 `code`
196
- if (text.match(/`([^`]+)`/g)) {
197
- text = text.replace(/`([^`]+)`/g, "$1");
198
- newStyle.inline_code = true;
199
- }
200
- return { text, style: newStyle };
201
- });
202
542
  Logger.log(`开始创建飞书文本块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
203
- const result = await this.feishuService.createTextBlock(documentId, parentBlockId, processedTextContents, align, index);
543
+ const result = await this.feishuService.createTextBlock(documentId, parentBlockId, textContents, align, index);
204
544
  Logger.log(`飞书文本块创建成功`);
205
545
  return {
206
546
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
@@ -208,19 +548,20 @@ export class FeishuMcpServer {
208
548
  }
209
549
  catch (error) {
210
550
  Logger.error(`创建飞书文本块失败:`, error);
551
+ const errorMessage = formatErrorMessage(error);
211
552
  return {
212
- content: [{ type: "text", text: `创建飞书文本块失败: ${error}` }],
553
+ content: [{ type: "text", text: `创建飞书文本块失败: ${errorMessage}` }],
213
554
  };
214
555
  }
215
556
  });
216
557
  // 添加创建飞书代码块工具
217
- this.server.tool("create_feishu_code_block", "Create a new code block in a Feishu document", {
218
- 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)"),
219
- 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"),
220
- code: z.string().describe("Code content"),
221
- 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"),
222
- wrap: z.boolean().optional().default(false).describe("Whether to enable automatic line wrapping. Default is false"),
223
- 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")
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.")
224
565
  }, async ({ documentId, parentBlockId, code, language = 0, wrap = false, index = 0 }) => {
225
566
  try {
226
567
  if (!this.feishuService) {
@@ -237,27 +578,37 @@ export class FeishuMcpServer {
237
578
  }
238
579
  catch (error) {
239
580
  Logger.error(`创建飞书代码块失败:`, error);
581
+ const errorMessage = formatErrorMessage(error);
240
582
  return {
241
- content: [{ type: "text", text: `创建飞书代码块失败: ${error}` }],
583
+ content: [{ type: "text", text: `创建飞书代码块失败: ${errorMessage}` }],
242
584
  };
243
585
  }
244
586
  });
245
587
  // 添加创建飞书标题块工具
246
- this.server.tool("create_feishu_heading_block", "Create a heading block in a Feishu document with specified level (1-9)", {
247
- 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)"),
248
- 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"),
249
- 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)"),
250
- content: z.string().describe("Heading text content"),
251
- 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")
252
- }, async ({ documentId, parentBlockId, level, content, index = 0 }) => {
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 }) => {
253
598
  try {
254
599
  if (!this.feishuService) {
255
600
  return {
256
601
  content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
257
602
  };
258
603
  }
259
- Logger.log(`开始创建飞书标题块,文档ID: ${documentId},父块ID: ${parentBlockId},标题级别: ${level},插入位置: ${index}`);
260
- const result = await this.feishuService.createHeadingBlock(documentId, parentBlockId, content, level, index);
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);
261
612
  Logger.log(`飞书标题块创建成功`);
262
613
  return {
263
614
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
@@ -265,37 +616,70 @@ export class FeishuMcpServer {
265
616
  }
266
617
  catch (error) {
267
618
  Logger.error(`创建飞书标题块失败:`, error);
619
+ const errorMessage = formatErrorMessage(error);
268
620
  return {
269
- content: [{ type: "text", text: `创建飞书标题块失败: ${error}` }],
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}` }],
270
661
  };
271
662
  }
272
663
  });
273
664
  }
274
665
  async connect(transport) {
275
- // Logger.log("Connecting to transport...");
276
666
  await this.server.connect(transport);
277
667
  Logger.log = (...args) => {
278
- this.server.server.sendLoggingMessage({
279
- level: "info",
280
- data: args,
281
- });
668
+ this.server.server.sendLoggingMessage({ level: 'info', data: args });
282
669
  };
283
670
  Logger.error = (...args) => {
284
- this.server.server.sendLoggingMessage({
285
- level: "error",
286
- data: args,
287
- });
671
+ this.server.server.sendLoggingMessage({ level: 'error', data: args });
288
672
  };
289
- Logger.log("Server connected and ready to process requests");
673
+ Logger.log('Server connected and ready to process requests');
290
674
  }
291
675
  async startHttpServer(port) {
292
676
  const app = express();
293
- app.get("/sse", async (_req, res) => {
294
- console.log("New SSE connection established");
295
- this.sseTransport = new SSEServerTransport("/messages", res);
677
+ app.get('/sse', async (_req, res) => {
678
+ console.log('New SSE connection established');
679
+ this.sseTransport = new SSEServerTransport('/messages', res);
296
680
  await this.server.connect(this.sseTransport);
297
681
  });
298
- app.post("/messages", async (req, res) => {
682
+ app.post('/messages', async (req, res) => {
299
683
  if (!this.sseTransport) {
300
684
  res.sendStatus(400);
301
685
  return;