Content
# Feishu MCP Server
[](https://www.typescriptlang.org/)
[](https://nodejs.org/)
[](LICENSE)
Feishu MCP Server is a service based on [Model Context Protocol](https://modelcontextprotocol.ai/) that provides Feishu API integration, enabling 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)
- [Running the Service](#running-the-service)
- [Configuration](#configuration)
- [API Documentation](#api-documentation)
- [Document Operations](#document-operations)
- [Bot Operations](#bot-operations)
- [Chat Operations](#chat-operations)
- [Multi-dimensional Table Operations](#multi-dimensional-table-operations)
- [Development Guide](#development-guide)
- [Coding Standards](#coding-standards)
- [Error Handling](#error-handling)
- [Commit Guidelines](#commit-guidelines)
- [Extension Guide](#extension-guide)
- [FAQ](#faq)
- [License](#license)
- [Contribution Guide](#contribution-guide)
## Features
- **Document Service**: Read Feishu document content and metadata
- **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, providing detailed error information
- **Type Safety**: Based on TypeScript, providing complete type definitions
- **Modular Architecture**: Easy to extend new features and integrate other Feishu APIs
## Project Architecture
### Code Structure
```
/src
/client # API client implementation (underlying 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 service
/bots # Bot-related service
/chats # Chat-related service
/server # MCP server implementation
/tools # MCP tool registration and implementation
/typings # Type definitions
/utils # Common 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 HTTP request details
- Handles underlying API parameters and response formats
- Manages authentication and token refresh
- Does not contain business logic
- **Service Layer**
- Uses the client to perform API operations
- Implements business logic
- Handles and transforms errors
- Provides friendly interfaces for upper layers to use
- **Tool Layer**
- Implements tools defined by the MCP protocol
- Handles parameter validation and format conversion
- Calls the service layer to complete actual operations
- Formats return 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 raw errors
- The service layer catches and converts errors into business-related errors
- The tool layer handles all exceptions and returns user-friendly messages
### Workflow
1. The MCP server receives a request (STDIO or HTTP)
2. The tool layer validates parameters and calls the corresponding service
3. The service layer implements 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 23.0 or higher
- pnpm package manager
- Valid Feishu 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 (automatic restart)
pnpm dev
# Or use normal startup
pnpm start
```
#### Production Mode
```bash
# Build the project
pnpm build
# Run the compiled code
node dist/index.js
```
#### STDIO Mode
```bash
# Method 1: Use environment variables
NODE_ENV=cli node dist/index.js
# Method 2: Use command-line arguments
node dist/index.js --stdio
```
## Configuration
| Option | Environment Variable | Command-Line Argument | Default Value | Description |
|------|----------|------------|--------|------|
| Feishu App ID | `FEISHU_APP_ID` | `--feishu-app-id` | - | App ID of the Feishu self-built application |
| Feishu App Secret | `FEISHU_APP_SECRET` | `--feishu-app-secret` | - | App Secret of the Feishu self-built 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`
Gets 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`
Gets the metadata information of a Feishu document.
Parameters:
- `docId` - Document ID
Returns:
- The metadata of the document (JSON format)
### Bot Operations
#### `send_feishu_text_message`
Sends a text message to a Feishu chat.
Parameters:
- `chatId` - Chat ID
- `text` - The text content to send
Returns:
- Sending status and message ID
#### `send_feishu_card`
Sends an interactive card to a Feishu chat.
Parameters:
- `chatId` - Chat ID
- `cardContent` - Card content (JSON string)
Returns:
- Sending status and message ID
### Chat Operations
#### `get_feishu_chat_info`
Gets the basic information of a Feishu chat.
Parameters:
- `chatId` - Chat ID
Returns:
- The basic information of the chat (JSON format)
### Multi-dimensional Table Operations
#### `get_feishu_sheet_meta`
Gets the metadata information of a 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>)
Returns:
- The metadata of the multi-dimensional table (JSON format), including table ID, name, revision version, creator, creation time, permissions, etc.
#### `get_feishu_sheet_tables`
Gets the list of data tables in a 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>)
- `pageSize` - The number of data tables returned per page, optional, defaults to 20, maximum is 100
- `pageToken` - Pagination token, optional, used to get the next page of data
Returns:
- A list of data tables (JSON format), including table ID, name, field information, etc.
#### `get_feishu_sheet_views`
Gets the list of views for a data table in a 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 get the next page of data
Returns:
- A list of views (JSON format), including view ID, name, type, and properties, etc.
#### `get_feishu_sheet_view`
Gets the detailed information of a specific view for a data table in a 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 get detailed information
Returns:
- View details (JSON format), including view ID, name, type, and properties, etc.
#### `get_feishu_sheet_records`
Gets the records of a data table in a 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, optional, uses the default view if not specified
- `fieldIds` - List of field IDs, optional, specifies which fields to return
- `filter` - Filter condition, optional, uses FQL format
- `sort` - Sorting condition, optional, uses JSON format
- `pageSize` - The number of records returned per page, optional, defaults to 20, maximum is 100
- `pageToken` - Pagination token, optional, used to get the next page of data
Returns:
- A list of records (JSON format), including record ID and field values
#### `get_feishu_sheet_record`
Gets a single record in a 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
- `recordId` - Record ID
- `fieldIds` - List of field IDs, optional, specifies which fields to return
Returns:
- A single record (JSON format), including record ID and field values
## Development Guide
### Coding Standards
The project uses strict TypeScript standards and ESLint configuration:
- Use TypeScript interfaces and type definitions
- Avoid using the `any` type
- Use `Record<string, unknown>` instead of the `object` type
- Use English for all code files, comments, and error messages
Run code checks:
```bash
# Run code checks
pnpm lint
# Run code checks and fix
pnpm lint:fix
# Run code formatting
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 following format:
```
<type>(<scope>): <subject>
```
For example:
- `feat(bot): Add send card feature`
- `fix(documents): Fix document content retrieval error`
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 the build process or auxiliary tools
### Extension Guide
Steps to add a new feature:
1. **Create a Client Class**
- Create in the `src/client/<feature>/` directory
- Inherit 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 a 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 the Service**
- Export the new service in `src/services/index.ts`
- Add the service to the `FeiShuServices` class
4. **Create an MCP Tool**
- Create in `src/server/tools/feature-tools.ts`
- Use Zod for parameter validation
- Call the 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 the Tool**
- Import and register the new tool in `src/server/tools/index.ts`
## FAQ
### Authentication Failed
**Problem**: API request returns an authentication error
**Solution**:
- Check if the application ID and secret are correct
- Confirm that the application has the required permission scopes
- Check if the server time is synchronized correctly
### Token Refresh Issues
**Problem**: Token refresh fails
**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 Guide
Contributions are welcome! 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 a PR, please ensure:
- The code passes all tests
- The relevant documentation has been updated
- The project's code style and naming conventions are followed
- Necessary unit tests have been added
Connection Info
You Might Also Like
awesome-mcp-servers
A collection of MCP servers.
git
A Model Context Protocol server for Git automation and interaction.
Appwrite
Build like a team of hundreds
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
oh-my-opencode
Background agents · Curated agents like oracle, librarians, frontend...
chatbox
User-friendly Desktop Client App for AI Models/LLMs (GPT, Claude, Gemini, Ollama...)