Content
# Feishu MCP Server
[](https://www.typescriptlang.org/)
[](https://nodejs.org/)
[](LICENSE)
Feishu MCP Server is a service based on the [Model Context Protocol](https://modelcontextprotocol.ai/) that provides Feishu API integration, allowing AI models to easily interact with Feishu services.
## Table of Contents
- [Features](#features)
- [Project Architecture](#project-architecture)
- [Code Structure](#code-structure)
- [Design Principles](#design-principles)
- [Workflow](#workflow)
- [Quick Start](#quick-start)
- [Prerequisites](#prerequisites)
- [Installation Steps](#installation-steps)
- [Run Service](#run-service)
- [Configuration Instructions](#configuration-instructions)
- [API Documentation](#api-documentation)
- [Document Operations](#document-operations)
- [Robot Operations](#robot-operations)
- [Chat Operations](#chat-operations)
- [Multidimensional Table Operations](#multidimensional-table-operations)
- [Development Guide](#development-guide)
- [Code Standards](#code-standards)
- [Error Handling](#error-handling)
- [Commit Guidelines](#commit-guidelines)
- [Extension Guide](#extension-guide)
- [Frequently Asked Questions](#frequently-asked-questions)
- [License](#license)
- [Contribution Guidelines](#contribution-guidelines)
## Features
- **Document Service**: Read content and metadata from Feishu documents
- **Bot Service**: Send text messages and interactive cards to Feishu chats
- **Chat Service**: Manage groups and chat sessions
- **Multi-mode Support**:
- **STDIO Mode**: Communicate via standard input/output, suitable for CLI environments and integration into other applications
- **HTTP Mode**: Provides REST API and SSE connections, suitable for web services and distributed deployments
- **Comprehensive Error Handling**: Unified error handling mechanism that provides detailed error information
- **Type Safety**: Based on TypeScript, offering complete type definitions
- **Modular Architecture**: Easy to extend new features and integrate other Feishu APIs
## Project Architecture
### Code Structure
```
/src
/client # API client implementation (low-level API request encapsulation)
/documents # Document-related API client
/bots # Bot API client
/chats # Chat-related API client
/services # Service layer implementation (business logic and error handling)
/documents # Document-related services
/bots # Bot-related services
/chats # Chat-related services
/server # MCP Server implementation
/tools # MCP tool registration and implementation
/typings # Type definitions
/utils # Utility functions
/http # HTTP server implementation
/logger # Logging service
/consts # Constant definitions
config.ts # Configuration management
index.ts # Entry point
```
### Design Principles
The project adopts a layered architecture design to ensure separation of concerns and clear responsibilities:
#### 1. Layered Responsibilities
- **Client Layer**
- Encapsulates the details of HTTP requests
- Handles underlying API parameters and response formats
- Manages authentication and token refresh
- Does not contain business logic
- **Service Layer**
- Executes API operations using the client
- Implements business logic
- Handles and transforms errors
- Provides a user-friendly interface for the upper layer
- **Tools Layer**
- Implements tools defined by the MCP (Message Control Protocol)
- Handles parameter validation and format conversion
- Calls the service layer to perform actual operations
- Formats the returned results
#### 2. Dependency Direction
- The service layer depends on the client layer.
- The tool layer depends on the service layer.
- Strictly avoid circular dependencies.
#### 3. Error Handling Strategy
- Use `FeiShuApiError` to uniformly handle API errors
- The client layer returns the original error
- The service layer catches and converts it into business-related errors
- The utility layer handles all exceptions and returns user-friendly messages
### Workflow
1. The MCP server receives the request (STDIO or HTTP)
2. The tool layer validates the parameters and calls the corresponding service
3. The service layer implements the business logic and calls the client
4. The client executes the actual API request and returns the result
5. The result is processed by the service layer and returned to the tool layer
6. The tool layer formats the result and returns it to the MCP server
## Quick Start
### Prerequisites
- Node.js version 23.0 or higher
- pnpm package manager
- A valid Feishu (Lark) developer account and a created self-built application
### Installation Steps
1. Clone the repository
```bash
git clone https://github.com/yourusername/feishu-mcp-server.git
cd feishu-mcp-server
```
2. Install dependencies
```bash
pnpm install
```
3. Create a `.env` file
```
# Feishu Application Credentials (Required)
FEISHU_APP_ID=your_app_id
FEISHU_APP_SECRET=your_app_secret
# Server Configuration (Optional)
PORT=3344
LOG_LEVEL=info
```
### Running the Service
#### Development Mode
```bash
```
# Development Mode (Auto Restart)
pnpm dev
# Or use the normal start
```bash
pnpm start
```
#### Production Mode
```bash
```
# Build the Project
pnpm build
# Run the Compiled Code
node dist/index.js
```
#### STDIO Mode
```bash
# Method 1: Using Environment Variables
NODE_ENV=cli node dist/index.js
# Method 2: Using Command Line Arguments
node dist/index.js --stdio
```
## Configuration Instructions
| Option | Environment Variable | Command Line Parameter | Default Value | Description |
|--------|---------------------|-----------------------|---------------|-------------|
| Feishu App ID | `FEISHU_APP_ID` | `--feishu-app-id` | - | App ID of the self-built Feishu application |
| Feishu App Secret | `FEISHU_APP_SECRET` | `--feishu-app-secret` | - | App Secret of the self-built Feishu application |
| Server Port | `PORT` | `--port` | 3344 | HTTP server port number |
| Log Level | `LOG_LEVEL` | `--log-level` | info | Log level (debug/info/warn/error) |
| Token Cache Duration | `TOKEN_CACHE_DURATION` | - | 7100 | Access token cache duration (seconds) |
## API Documentation
### Document Operations
#### `get_feishu_doc_raw`
Get the raw content of a Feishu document.
Parameters:
- `docId` - Document ID, usually found in the URL (e.g., feishu.cn/docx/<documentId>)
Returns:
- The text content of the document
#### `get_feishu_doc_info`
Get the metadata information of the Feishu document.
Parameters:
- `docId` - Document ID
Returns:
- Metadata of the document (in JSON format)
### Robot Operation
#### `send_feishu_text_message`
Send a text message to Feishu chat.
Parameters:
- `chatId` - Chat ID
- `text` - The text content to be sent
Returns:
- Sending status and message ID
#### `send_feishu_card`
Send an interactive card to Feishu chat.
Parameters:
- `chatId` - Chat ID
- `cardContent` - Card content (JSON string)
Returns:
- Send status and message ID
### Chat Operations
#### `get_feishu_chat_info`
Get basic information about the Feishu chat.
Parameters:
- `chatId` - Chat ID
Returns:
- Basic information of the chat (in JSON format)
### Multidimensional Table Operations
#### `get_feishu_sheet_meta`
Get the metadata information of the Feishu (飞书) multi-dimensional table.
Parameters:
- `appToken` - The multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
Returns:
- The metadata of the multi-dimensional table (in JSON format), including table ID, name, revision version, creator, creation time, permissions, and other information.
#### `get_feishu_sheet_tables`
Get the list of data tables in Feishu's multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `pageSize` - The number of data tables returned per page, optional, default is 20, maximum is 100
- `pageToken` - Pagination token, optional, used to get the next page of data
Returns:
- List of data tables (in JSON format), including table ID, name, field information, etc.
#### `get_feishu_sheet_views`
Get the list of views for a data table in Feishu (飞书) multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `pageSize` - The number of views returned per page, optional, defaults to 20, maximum is 100
- `pageToken` - Pagination token, optional, used to retrieve the next page of data
Returns:
- A list of views (in JSON format), including view ID, name, type, and attributes, among other information
#### `get_feishu_sheet_view`
Get detailed information about a specific view of a data table in Feishu (飞书) multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `viewId` - View ID, the view for which to retrieve detailed information
Returns:
- View details (in JSON format), including view ID, name, type, and properties, among other information.
#### `get_feishu_sheet_records`
Retrieve data table records from Feishu's multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `viewId` - View ID, optional, defaults to the default view if not specified
- `fieldIds` - List of field IDs, optional, specifies which fields to return
- `filter` - Filtering conditions, optional, in FQL format
- `sort` - Sorting conditions, optional, in JSON format
- `pageSize` - Number of records returned per page, optional, defaults to 20, maximum is 100
- `pageToken` - Pagination token, optional, used to retrieve the next page of data
Returns:
- List of records (in JSON format), including record IDs and field values
#### `get_feishu_sheet_record`
Retrieve a single record from Feishu's multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in the URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `recordId` - Record ID
- `fieldIds` - List of field IDs, optional, specifies which fields to return
Returns:
- A single record (in JSON format), containing the record ID and field values
## Development Guide
### Code Standards
The project follows strict TypeScript standards and ESLint configuration:
- Use TypeScript interfaces and type definitions
- Avoid using `any` type
- Use `Record<string, unknown>` instead of `object` type
- All code files, comments, and error messages are in English
Run code checks:
```bash
# Run Code Check
pnpm lint
# Run Code Check and Fix
pnpm lint:fix
# Run Code Formatting
```bash
pnpm format
```
### Error Handling
All errors related to the FeiShu API should be handled using the `FeiShuApiError` class:
```typescript
try {
// API operation
} catch (error) {
if (error instanceof FeiShuApiError) {
// Handle specific API errors
logger.error(`FeiShu API Error (${error.code}): ${error.message}`);
} else {
// Handle general errors
logger.error('Unexpected error:', error);
}
// Convert to user-friendly message
throw new FeiShuApiError('Operation failed', { cause: error });
}
```
### Commit Guidelines
Commit messages must follow the format:
```
<type>(<scope>): <subject>
```
For example:
- `feat(bot): Add card sending feature`
- `fix(documents): Fix error in document content retrieval`
Supported types:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code formatting adjustments
- `refactor`: Code refactoring
- `perf`: Performance optimization
- `test`: Testing related
- `chore`: Changes to build process or auxiliary tools
### Extension Guide
Steps to add new features:
1. **Create Client Class**
- Create in the `src/client/<feature>/` directory
- Inherit from the `ApiClient` base class
- Implement API request methods
```typescript
// src/client/feature/feature-client.ts
export class FeatureClient extends ApiClient {
async getFeatureData(id: string): Promise<FeatureData> {
return this.request<FeatureResponse>('/feature/get', { id });
}
}
```
2. **Create Service Class**
- Create in the `src/services/<feature>/` directory
- Use the corresponding client class
- Implement business logic and error handling
```typescript
// src/services/feature/feature-service.ts
export class FeatureService {
private client: FeatureClient;
constructor(config: ApiClientConfig) {
this.client = new FeatureClient(config);
}
async getFeature(id: string): Promise<Feature> {
try {
const data = await this.client.getFeatureData(id);
return this.transformData(data);
} catch (error) {
handleError(error);
}
}
}
```
3. **Register Service**
- Export the new service in `src/services/index.ts`
- Add the service to the `FeiShuServices` class
4. **Create MCP Tools**
- Create in `src/server/tools/feature-tools.ts`
- Use Zod for parameter validation
- Call service layer methods
```typescript
// src/server/tools/feature-tools.ts
export function registerFeatureTools(params: ToolRegistryParams): void {
const { server, services, logger } = params;
server.tool(
'get_feishu_feature',
'Get feature from FeiShu',
{
id: z.string().describe('Feature ID'),
},
async ({ id }) => {
try {
const feature = await services.feature.getFeature(id);
return { content: [{ type: 'text', text: JSON.stringify(feature) }] };
} catch (error) {
return handleToolError(error, logger);
}
}
);
}
```
5. **Register Tools**
- Import and register the new tools in `src/server/tools/index.ts`
## Frequently Asked Questions
### Authentication Failure
**Issue**: API request returns authentication error
**Solution**:
- Check if the application ID and secret are correct
- Ensure the application has the required scope of permissions
- Verify that the server time is correctly synchronized
### Token Refresh Issues
**Issue**: Token refresh failed
**Solution**:
- Set a shorter token cache duration
- Check the stability of the network connection
- Check the application status on the Feishu Developer Platform
## License
MIT
## Contribution Guidelines
We welcome contributions! Please follow these steps:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'feat: add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
Before submitting your PR, please ensure that:
- The code passes all tests
- Relevant documentation is updated
- The project's code style and naming conventions are followed
- Necessary unit tests are added
Connection Info
You Might Also Like
Git
Model Context Protocol Servers
TrendRadar
🎯 Say goodbye to information overload. AI helps you understand news hotspots...
repomix
📦 Repomix is a powerful tool that packs your entire repository into a...
Mastra
The TypeScript AI agent framework. ⚡ Assistants, RAG, observability....
Blender
BlenderMCP integrates Blender with Claude AI for enhanced 3D modeling.
cua
Open-source infrastructure for Computer-Use Agents. Sandboxes, SDKs, and...