feishu-mcp 0.0.7 → 0.0.9-alpha

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,516 +1,67 @@
1
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { z } from 'zod';
3
1
  import express from 'express';
4
2
  import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
5
- import { formatErrorMessage } from './utils/error.js';
6
- import { FeishuApiService } from './services/feishuApiService.js';
7
3
  import { Logger } from './utils/logger.js';
8
- import { DocumentIdSchema, ParentBlockIdSchema, BlockIdSchema, IndexSchema, StartIndexSchema, AlignSchema, AlignSchemaWithValidation, TextElementsArraySchema, CodeLanguageSchema, CodeWrapSchema, BlockConfigSchema } from './types/feishuSchema.js';
4
+ import { SSEConnectionManager } from './manager/sseConnectionManager';
5
+ import { FeishuMcp } from './mcp/feishuMcp';
9
6
  export class FeishuMcpServer {
10
7
  constructor() {
11
- Object.defineProperty(this, "server", {
8
+ Object.defineProperty(this, "connectionManager", {
12
9
  enumerable: true,
13
10
  configurable: true,
14
11
  writable: true,
15
12
  value: void 0
16
13
  });
17
- Object.defineProperty(this, "sseTransport", {
18
- enumerable: true,
19
- configurable: true,
20
- writable: true,
21
- value: null
22
- });
23
- Object.defineProperty(this, "feishuService", {
24
- enumerable: true,
25
- configurable: true,
26
- writable: true,
27
- value: null
28
- });
29
- try {
30
- // 使用单例模式获取飞书服务实例
31
- this.feishuService = FeishuApiService.getInstance();
32
- Logger.info('飞书服务初始化成功');
33
- }
34
- catch (error) {
35
- Logger.error('飞书服务初始化失败:', error);
36
- throw new Error('飞书服务初始化失败');
37
- }
38
- this.server = new McpServer({
39
- name: 'Feishu MCP Server',
40
- version: '0.0.1',
41
- }, {
42
- capabilities: {
43
- logging: {},
44
- tools: {},
45
- },
46
- });
47
- this.registerTools();
48
- }
49
- registerTools() {
50
- // 添加创建飞书文档工具
51
- 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.', {
52
- title: z.string().describe('Document title (required). This will be displayed in the Feishu document list and document header.'),
53
- folderToken: z.string().describe('Folder token (required). Specifies where to create the document. Format is an alphanumeric string like "doxcnOu1ZKYH4RtX1Y5XwL5WGRh".'),
54
- }, async ({ title, folderToken }) => {
55
- try {
56
- Logger.info(`开始创建飞书文档,标题: ${title}${folderToken ? `,文件夹Token: ${folderToken}` : ',使用默认文件夹'}`);
57
- const newDoc = await this.feishuService?.createDocument(title, folderToken);
58
- if (!newDoc) {
59
- throw new Error('创建文档失败,未返回文档信息');
60
- }
61
- Logger.info(`飞书文档创建成功,文档ID: ${newDoc.objToken || newDoc.document_id}`);
62
- return {
63
- content: [{ type: 'text', text: JSON.stringify(newDoc, null, 2) }],
64
- };
65
- }
66
- catch (error) {
67
- Logger.error(`创建飞书文档失败:`, error);
68
- const errorMessage = formatErrorMessage(error);
69
- return {
70
- content: [{ type: 'text', text: `创建飞书文档失败: ${errorMessage}` }],
71
- };
72
- }
73
- });
74
- // 添加获取飞书文档信息工具
75
- this.server.tool('get_feishu_document_info', 'Retrieves basic information about a Feishu document. Use this to verify a document exists, check access permissions, or get metadata like title, type, and creation information.', {
76
- documentId: DocumentIdSchema,
77
- }, async ({ documentId }) => {
78
- try {
79
- if (!this.feishuService) {
80
- return {
81
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
82
- };
83
- }
84
- Logger.info(`开始获取飞书文档信息,文档ID: ${documentId}`);
85
- const docInfo = await this.feishuService.getDocumentInfo(documentId);
86
- Logger.info(`飞书文档信息获取成功,标题: ${docInfo.title}`);
87
- return {
88
- content: [{ type: 'text', text: JSON.stringify(docInfo, null, 2) }],
89
- };
90
- }
91
- catch (error) {
92
- Logger.error(`获取飞书文档信息失败:`, error);
93
- const errorMessage = formatErrorMessage(error, '获取飞书文档信息失败');
94
- return {
95
- content: [{ type: 'text', text: errorMessage }],
96
- };
97
- }
98
- });
99
- // 添加获取飞书文档内容工具
100
- this.server.tool('get_feishu_document_content', 'Retrieves the plain text content of a Feishu document. Ideal for content analysis, processing, or when you need to extract text without formatting. The content maintains the document structure but without styling. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
101
- documentId: DocumentIdSchema,
102
- lang: z.number().optional().default(0).describe('Language code (optional). Default is 0 (Chinese). Use 1 for English if available.'),
103
- }, async ({ documentId, lang }) => {
104
- try {
105
- if (!this.feishuService) {
106
- return {
107
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
108
- };
109
- }
110
- Logger.info(`开始获取飞书文档内容,文档ID: ${documentId},语言: ${lang}`);
111
- const content = await this.feishuService.getDocumentContent(documentId, lang);
112
- Logger.info(`飞书文档内容获取成功,内容长度: ${content.length}字符`);
113
- return {
114
- content: [{ type: 'text', text: content }],
115
- };
116
- }
117
- catch (error) {
118
- Logger.error(`获取飞书文档内容失败:`, error);
119
- const errorMessage = formatErrorMessage(error);
120
- return {
121
- content: [{ type: 'text', text: `获取飞书文档内容失败: ${errorMessage}` }],
122
- };
123
- }
124
- });
125
- // 添加获取飞书文档块工具
126
- this.server.tool('get_feishu_document_blocks', 'Retrieves the block structure information of a Feishu document. Essential to use before inserting content to understand document structure and determine correct insertion positions. Returns a detailed hierarchy of blocks with their IDs, types, and content. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
127
- documentId: DocumentIdSchema,
128
- 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.'),
129
- }, async ({ documentId, pageSize }) => {
130
- try {
131
- if (!this.feishuService) {
132
- return {
133
- content: [{ type: 'text', text: 'Feishu service is not initialized. Please check the configuration' }],
134
- };
135
- }
136
- Logger.info(`开始获取飞书文档块,文档ID: ${documentId},页大小: ${pageSize}`);
137
- const blocks = await this.feishuService.getDocumentBlocks(documentId, pageSize);
138
- Logger.info(`飞书文档块获取成功,共 ${blocks.length} 个块`);
139
- return {
140
- content: [{ type: 'text', text: JSON.stringify(blocks, null, 2) }],
141
- };
142
- }
143
- catch (error) {
144
- Logger.error(`获取飞书文档块失败:`, error);
145
- const errorMessage = formatErrorMessage(error);
146
- return {
147
- content: [{ type: 'text', text: `获取飞书文档块失败: ${errorMessage}` }],
148
- };
149
- }
150
- });
151
- // 添加获取块内容工具
152
- 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. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
153
- documentId: DocumentIdSchema,
154
- blockId: BlockIdSchema,
155
- }, async ({ documentId, blockId }) => {
156
- try {
157
- if (!this.feishuService) {
158
- return {
159
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
160
- };
161
- }
162
- Logger.info(`开始获取飞书块内容,文档ID: ${documentId},块ID: ${blockId}`);
163
- const blockContent = await this.feishuService.getBlockContent(documentId, blockId);
164
- Logger.info(`飞书块内容获取成功,块类型: ${blockContent.block_type}`);
165
- return {
166
- content: [{ type: 'text', text: JSON.stringify(blockContent, null, 2) }],
167
- };
168
- }
169
- catch (error) {
170
- Logger.error(`获取飞书块内容失败:`, error);
171
- const errorMessage = formatErrorMessage(error);
172
- return {
173
- content: [{ type: 'text', text: `获取飞书块内容失败: ${errorMessage}` }],
174
- };
175
- }
176
- });
177
- // 添加更新块文本内容工具
178
- 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. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
179
- documentId: DocumentIdSchema,
180
- blockId: BlockIdSchema,
181
- textElements: TextElementsArraySchema,
182
- }, async ({ documentId, blockId, textElements }) => {
183
- try {
184
- if (!this.feishuService) {
185
- return {
186
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
187
- };
188
- }
189
- Logger.info(`开始更新飞书块文本内容,文档ID: ${documentId},块ID: ${blockId}`);
190
- const result = await this.feishuService.updateBlockTextContent(documentId, blockId, textElements);
191
- Logger.info(`飞书块文本内容更新成功`);
192
- return {
193
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
194
- };
195
- }
196
- catch (error) {
197
- Logger.error(`更新飞书块文本内容失败:`, error);
198
- const errorMessage = formatErrorMessage(error);
199
- return {
200
- content: [{ type: 'text', text: `更新飞书块文本内容失败: ${errorMessage}` }],
201
- };
202
- }
203
- });
204
- // 添加通用飞书块创建工具(支持文本、代码、标题)
205
- this.server.tool('batch_create_feishu_blocks', 'RECOMMENDED: Creates multiple blocks of different types (text, code, heading, list) in a single efficient API call. This tool should be PREFERRED OVER individual block creation tools when creating multiple consecutive blocks at the same position. Significantly improves performance and reduces API calls by up to 90% compared to creating blocks individually. AUTOMATICALLY handles batching for large number of blocks (>50) by splitting into multiple requests. For specific block positioning at different locations, use individual block creation tools instead. For error recovery, use get_feishu_document_blocks to check the document state. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.', {
206
- documentId: DocumentIdSchema,
207
- parentBlockId: ParentBlockIdSchema,
208
- startIndex: StartIndexSchema,
209
- blocks: z.array(BlockConfigSchema).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}}}]. Handles any number of blocks by automatically batching in groups of 50.'),
210
- }, async ({ documentId, parentBlockId, startIndex = 0, blocks }) => {
211
- try {
212
- if (!this.feishuService) {
213
- return {
214
- content: [
215
- {
216
- type: 'text',
217
- text: 'Feishu service is not initialized. Please check the configuration',
218
- },
219
- ],
220
- };
221
- }
222
- // 如果块数量不超过50,直接调用一次API
223
- if (blocks.length <= 50) {
224
- Logger.info(`开始批量创建飞书块,文档ID: ${documentId},父块ID: ${parentBlockId},块数量: ${blocks.length},起始插入位置: ${startIndex}`);
225
- // 准备要创建的块内容数组
226
- const blockContents = [];
227
- // 处理每个块配置
228
- for (const blockConfig of blocks) {
229
- const { blockType, options = {} } = blockConfig;
230
- // 创建块内容
231
- const blockContent = this.feishuService.createBlockContent(blockType, options);
232
- if (blockContent) {
233
- blockContents.push(blockContent);
234
- Logger.info(`已准备${blockType}块,内容: ${JSON.stringify(blockContent).substring(0, 100)}...`);
235
- }
236
- }
237
- // 批量创建所有块
238
- const result = await this.feishuService.createDocumentBlocks(documentId, parentBlockId, blockContents, startIndex);
239
- Logger.info(`飞书块批量创建成功,共创建 ${blockContents.length} 个块`);
240
- return {
241
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
242
- };
243
- }
244
- else {
245
- // 如果块数量超过50,需要分批处理
246
- Logger.info(`块数量(${blocks.length})超过50,将分批创建`);
247
- const batchSize = 50; // 每批最大50个
248
- const totalBatches = Math.ceil(blocks.length / batchSize);
249
- const results = [];
250
- let currentStartIndex = startIndex;
251
- let createdBlocksCount = 0;
252
- let allBatchesSuccess = true;
253
- // 分批创建块
254
- for (let batchNum = 0; batchNum < totalBatches; batchNum++) {
255
- const batchStart = batchNum * batchSize;
256
- const batchEnd = Math.min((batchNum + 1) * batchSize, blocks.length);
257
- const currentBatch = blocks.slice(batchStart, batchEnd);
258
- Logger.info(`处理第 ${batchNum + 1}/${totalBatches} 批,起始位置: ${currentStartIndex},块数量: ${currentBatch.length}`);
259
- try {
260
- // 准备当前批次的块内容
261
- const batchBlockContents = [];
262
- for (const blockConfig of currentBatch) {
263
- const { blockType, options = {} } = blockConfig;
264
- const blockContent = this.feishuService.createBlockContent(blockType, options);
265
- if (blockContent) {
266
- batchBlockContents.push(blockContent);
267
- }
268
- }
269
- // 批量创建当前批次的块
270
- const batchResult = await this.feishuService.createDocumentBlocks(documentId, parentBlockId, batchBlockContents, currentStartIndex);
271
- results.push(batchResult);
272
- // 计算下一批的起始位置(当前位置+已创建块数量)
273
- // 注意:每批成功创建后,需要将起始索引更新为当前索引 + 已创建块数量
274
- createdBlocksCount += batchBlockContents.length;
275
- currentStartIndex = startIndex + createdBlocksCount;
276
- Logger.info(`第 ${batchNum + 1}/${totalBatches} 批创建成功,当前已创建 ${createdBlocksCount} 个块`);
277
- }
278
- catch (error) {
279
- Logger.error(`第 ${batchNum + 1}/${totalBatches} 批创建失败:`, error);
280
- allBatchesSuccess = false;
281
- // 如果有批次失败,返回详细错误信息
282
- const errorMessage = formatErrorMessage(error);
283
- return {
284
- content: [
285
- {
286
- type: 'text',
287
- text: `批量创建飞书块部分失败:第 ${batchNum + 1}/${totalBatches} 批处理时出错。\n\n` +
288
- `已成功创建 ${createdBlocksCount} 个块,但还有 ${blocks.length - createdBlocksCount} 个块未能创建。\n\n` +
289
- `错误信息: ${errorMessage}\n\n` +
290
- `建议使用 get_feishu_document_blocks 工具获取文档最新状态,确认已创建的内容,然后从索引位置 ${currentStartIndex} 继续创建剩余块。`
291
- }
292
- ],
293
- };
294
- }
295
- }
296
- if (allBatchesSuccess) {
297
- Logger.info(`所有批次创建成功,共创建 ${createdBlocksCount} 个块`);
298
- return {
299
- content: [
300
- {
301
- type: 'text',
302
- text: `所有飞书块创建成功,共分 ${totalBatches} 批创建了 ${createdBlocksCount} 个块。\n\n` +
303
- `最后一批结果: ${JSON.stringify(results[results.length - 1], null, 2)}`
304
- }
305
- ],
306
- };
307
- }
308
- }
309
- // 这个return语句是为了避免TypeScript错误,实际上代码永远不会执行到这里
310
- return {
311
- content: [{ type: 'text', text: '操作完成' }],
312
- };
313
- }
314
- catch (error) {
315
- Logger.error(`批量创建飞书块失败:`, error);
316
- const errorMessage = formatErrorMessage(error);
317
- return {
318
- content: [
319
- {
320
- type: 'text',
321
- text: `批量创建飞书块失败: ${errorMessage}\n\n` +
322
- `建议使用 get_feishu_document_blocks 工具获取文档当前状态,确认是否有部分内容已创建成功。`
323
- }
324
- ],
325
- };
326
- }
327
- });
328
- // 添加创建飞书文本块工具
329
- this.server.tool("create_feishu_text_block", "Creates a new text block with precise style control. Unlike markdown-based formatting, this tool lets you explicitly set text styles for each text segment. Ideal for formatted documents where exact styling control is needed. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
330
- documentId: DocumentIdSchema,
331
- parentBlockId: ParentBlockIdSchema,
332
- textContents: TextElementsArraySchema,
333
- align: AlignSchema,
334
- index: IndexSchema
335
- }, async ({ documentId, parentBlockId, textContents, align = 1, index }) => {
336
- try {
337
- if (!this.feishuService) {
338
- return {
339
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
340
- };
341
- }
342
- Logger.info(`开始创建飞书文本块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
343
- const result = await this.feishuService.createTextBlock(documentId, parentBlockId, textContents, align, index);
344
- Logger.info(`飞书文本块创建成功`);
345
- return {
346
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
347
- };
348
- }
349
- catch (error) {
350
- Logger.error(`创建飞书文本块失败:`, error);
351
- const errorMessage = formatErrorMessage(error);
352
- return {
353
- content: [{ type: "text", text: `创建飞书文本块失败: ${errorMessage}` }],
354
- };
355
- }
356
- });
357
- // 添加创建飞书代码块工具
358
- this.server.tool("create_feishu_code_block", "Creates a new code block with syntax highlighting and formatting options. Ideal for technical documentation, tutorials, or displaying code examples with proper formatting and language-specific highlighting. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
359
- documentId: DocumentIdSchema,
360
- parentBlockId: ParentBlockIdSchema,
361
- code: z.string().describe("Code content (required). The complete code text to display."),
362
- language: CodeLanguageSchema,
363
- wrap: CodeWrapSchema,
364
- index: IndexSchema
365
- }, async ({ documentId, parentBlockId, code, language = 1, wrap = false, index = 0 }) => {
366
- try {
367
- if (!this.feishuService) {
368
- return {
369
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
370
- };
371
- }
372
- Logger.info(`开始创建飞书代码块,文档ID: ${documentId},父块ID: ${parentBlockId},语言: ${language},自动换行: ${wrap},插入位置: ${index}`);
373
- const result = await this.feishuService.createCodeBlock(documentId, parentBlockId, code, language, wrap, index);
374
- Logger.info(`飞书代码块创建成功`);
375
- return {
376
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
377
- };
378
- }
379
- catch (error) {
380
- Logger.error(`创建飞书代码块失败:`, error);
381
- const errorMessage = formatErrorMessage(error);
382
- return {
383
- content: [{ type: "text", text: `创建飞书代码块失败: ${errorMessage}` }],
384
- };
385
- }
386
- });
387
- // 添加创建飞书标题块工具
388
- this.server.tool("create_feishu_heading_block", "Creates a heading block with customizable level and alignment. Use this tool to add section titles, chapter headings, or any hierarchical structure elements to your document. Supports nine heading levels for different emphasis needs. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
389
- documentId: DocumentIdSchema,
390
- parentBlockId: ParentBlockIdSchema,
391
- 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)."),
392
- content: z.string().describe("Heading text content (required). The actual text of the heading."),
393
- align: AlignSchemaWithValidation,
394
- index: IndexSchema
395
- }, async ({ documentId, parentBlockId, level, content, align = 1, index = 0 }) => {
396
- try {
397
- if (!this.feishuService) {
398
- return {
399
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
400
- };
401
- }
402
- // 确保align值在合法范围内(1-3)
403
- if (align !== 1 && align !== 2 && align !== 3) {
404
- return {
405
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
406
- };
407
- }
408
- Logger.info(`开始创建飞书标题块,文档ID: ${documentId},父块ID: ${parentBlockId},标题级别: ${level},对齐方式: ${align},插入位置: ${index}`);
409
- const result = await this.feishuService.createHeadingBlock(documentId, parentBlockId, content, level, index, align);
410
- Logger.info(`飞书标题块创建成功`);
411
- return {
412
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
413
- };
414
- }
415
- catch (error) {
416
- Logger.error(`创建飞书标题块失败:`, error);
417
- const errorMessage = formatErrorMessage(error);
418
- return {
419
- content: [{ type: "text", text: `创建飞书标题块失败: ${errorMessage}` }],
420
- };
421
- }
422
- });
423
- // 添加创建飞书列表块工具
424
- this.server.tool("create_feishu_list_block", "Creates a list item block (either ordered or unordered). Perfect for creating hierarchical and structured content with bullet points or numbered lists. NOTE: If creating multiple blocks at once, use batch_create_feishu_blocks tool instead for better efficiency. Note: For Feishu wiki links (https://xxx.feishu.cn/wiki/xxx) you must first use convert_feishu_wiki_to_document_id tool to obtain a compatible document ID.", {
425
- documentId: DocumentIdSchema,
426
- parentBlockId: ParentBlockIdSchema,
427
- content: z.string().describe("List item content (required). The actual text of the list item."),
428
- isOrdered: z.boolean().optional().default(false).describe("Whether this is an ordered (numbered) list item. Default is false (bullet point/unordered)."),
429
- align: AlignSchemaWithValidation,
430
- index: IndexSchema
431
- }, async ({ documentId, parentBlockId, content, isOrdered = false, align = 1, index = 0 }) => {
432
- try {
433
- if (!this.feishuService) {
434
- return {
435
- content: [{ type: "text", text: "Feishu service is not initialized. Please check the configuration" }],
436
- };
437
- }
438
- // 确保align值在合法范围内(1-3)
439
- if (align !== 1 && align !== 2 && align !== 3) {
440
- return {
441
- content: [{ type: "text", text: "错误: 对齐方式(align)参数必须是1(居左)、2(居中)或3(居右)中的一个值。" }],
442
- };
443
- }
444
- const listType = isOrdered ? "有序" : "无序";
445
- Logger.info(`开始创建飞书${listType}列表块,文档ID: ${documentId},父块ID: ${parentBlockId},对齐方式: ${align},插入位置: ${index}`);
446
- const result = await this.feishuService.createListBlock(documentId, parentBlockId, content, isOrdered, index, align);
447
- Logger.info(`飞书${listType}列表块创建成功`);
448
- return {
449
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
450
- };
451
- }
452
- catch (error) {
453
- Logger.error(`创建飞书列表块失败:`, error);
454
- const errorMessage = formatErrorMessage(error);
455
- return {
456
- content: [{ type: "text", text: `创建飞书列表块失败: ${errorMessage}` }],
457
- };
458
- }
459
- });
460
- // 添加飞书Wiki文档ID转换工具
461
- this.server.tool('convert_feishu_wiki_to_document_id', 'Converts a Feishu Wiki document link to a compatible document ID. This conversion is required before using wiki links with any other Feishu document tools.', {
462
- wikiUrl: z.string().describe('Wiki URL or Token (required). Supports complete URL formats like https://xxx.feishu.cn/wiki/xxxxx or direct use of the Token portion'),
463
- }, async ({ wikiUrl }) => {
464
- try {
465
- if (!this.feishuService) {
466
- return {
467
- content: [{ type: 'text', text: '飞书服务未初始化,请检查配置' }],
468
- };
469
- }
470
- Logger.info(`开始转换Wiki文档链接,输入: ${wikiUrl}`);
471
- const documentId = await this.feishuService.convertWikiToDocumentId(wikiUrl);
472
- Logger.info(`Wiki文档转换成功,可用的文档ID为: ${documentId}`);
473
- return {
474
- content: [
475
- { type: 'text', text: `Converted Wiki link to Document ID: ${documentId}\n\nUse this Document ID with other Feishu document tools.` }
476
- ],
477
- };
478
- }
479
- catch (error) {
480
- Logger.error(`转换Wiki文档链接失败:`, error);
481
- const errorMessage = formatErrorMessage(error);
482
- return {
483
- content: [{ type: 'text', text: `转换Wiki文档链接失败: ${errorMessage}` }],
484
- };
485
- }
486
- });
14
+ this.connectionManager = new SSEConnectionManager();
487
15
  }
488
16
  async connect(transport) {
489
- await this.server.connect(transport);
17
+ const server = new FeishuMcp();
18
+ await server.connect(transport);
490
19
  Logger.info = (...args) => {
491
- this.server.server.sendLoggingMessage({ level: 'info', data: args });
20
+ server.server.sendLoggingMessage({ level: 'info', data: args });
492
21
  };
493
22
  Logger.error = (...args) => {
494
- this.server.server.sendLoggingMessage({ level: 'error', data: args });
23
+ server.server.sendLoggingMessage({ level: 'error', data: args });
495
24
  };
496
25
  Logger.info('Server connected and ready to process requests');
497
26
  }
498
27
  async startHttpServer(port) {
499
28
  const app = express();
500
- app.get('/sse', async (_req, res) => {
501
- console.log('New SSE connection established');
502
- this.sseTransport = new SSEServerTransport('/messages', res);
503
- await this.server.connect(this.sseTransport);
29
+ app.get('/sse', async (req, res) => {
30
+ const sseTransport = new SSEServerTransport('/messages', res);
31
+ const sessionId = sseTransport.sessionId;
32
+ Logger.log(`[SSE Connection] New SSE connection established for sessionId ${sessionId} params:${JSON.stringify(req.params)} headers:${JSON.stringify(req.headers)} `);
33
+ this.connectionManager.addConnection(sessionId, sseTransport, req, res);
34
+ try {
35
+ const tempServer = new FeishuMcp();
36
+ await tempServer.connect(sseTransport);
37
+ Logger.info(`[SSE Connection] Successfully connected transport for: ${sessionId}`);
38
+ }
39
+ catch (error) {
40
+ Logger.error(`[SSE Connection] Error connecting server to transport for ${sessionId}:`, error);
41
+ this.connectionManager.removeConnection(sessionId);
42
+ if (!res.writableEnded) {
43
+ res.status(500).end('Failed to connect MCP server to transport');
44
+ }
45
+ return;
46
+ }
504
47
  });
505
48
  app.post('/messages', async (req, res) => {
506
- if (!this.sseTransport) {
507
- res.sendStatus(400);
49
+ const sessionId = req.query.sessionId;
50
+ Logger.info(`[SSE messages] Received message with sessionId: ${sessionId}, params: ${JSON.stringify(req.query)}, body: ${JSON.stringify(req.body)}`);
51
+ if (!sessionId) {
52
+ res.status(400).send('Missing sessionId query parameter');
53
+ return;
54
+ }
55
+ const transport = this.connectionManager.getTransport(sessionId);
56
+ Logger.log(`[SSE messages] Retrieved transport for sessionId ${sessionId}: ${transport ? transport.sessionId : 'Transport not found'}`);
57
+ if (!transport) {
58
+ res
59
+ .status(404)
60
+ .send(`No active connection found for sessionId: ${sessionId}`);
508
61
  return;
509
62
  }
510
- await this.sseTransport.handlePostMessage(req, res);
63
+ await transport.handlePostMessage(req, res);
511
64
  });
512
- Logger.info = console.log;
513
- Logger.error = console.error;
514
65
  app.listen(port, () => {
515
66
  Logger.info(`HTTP server listening on port ${port}`);
516
67
  Logger.info(`SSE endpoint available at http://localhost:${port}/sse`);
@@ -70,6 +70,7 @@ export class FeishuService {
70
70
  throw {
71
71
  status: response.status,
72
72
  err: response.data.msg || "Unknown error",
73
+ apiError: response.data
73
74
  };
74
75
  }
75
76
  this.accessToken = response.data.tenant_access_token;
@@ -86,6 +87,7 @@ export class FeishuService {
86
87
  throw {
87
88
  status: error.response.status,
88
89
  err: error.response.data?.msg || "Unknown error",
90
+ apiError: error.response.data
89
91
  };
90
92
  }
91
93
  Logger.error('获取访问令牌时发生未知错误:', error);
@@ -128,6 +130,7 @@ export class FeishuService {
128
130
  throw {
129
131
  status: error.response.status,
130
132
  err: error.response.data?.msg || "Unknown error",
133
+ apiError: error.response.data
131
134
  };
132
135
  }
133
136
  Logger.error('发送请求时发生未知错误:', error);