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/), providing FeiShu API integration to enable AI models to interact with FeiShu services easily.
## 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)
- [Code Style](#code-style)
- [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 through standard input/output, suitable for CLI environments and integration into other applications
- **HTTP Mode**: Provide REST API and SSE connection, suitable for web services and distributed deployment
- **Complete 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-related 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 # General 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**
- Encapsulate HTTP request details
- Handle underlying API parameters and response formats
- Manage authentication and token refresh
- No business logic
- **Service Layer**
- Use clients to perform API operations
- Implement business logic
- Handle and convert errors
- Provide friendly interfaces to upper layers
- **Tool Layer**
- Implement tools defined by MCP protocol
- Handle parameter validation and format conversion
- Call service layer to complete actual operations
- Format return results
#### 2. Dependency Direction
- Service layer depends on client layer
- Tool layer depends on service layer
- Strictly avoid circular dependencies
#### 3. Error Handling Strategy
- Use `FeiShuApiError` to handle API errors uniformly
- Client layer returns raw errors
- Service layer captures and converts to business-related errors
- Tool layer handles all exceptions and returns user-friendly messages
### Workflow
1. MCP server receives requests (STDIO or HTTP)
2. Tool layer validates parameters and calls corresponding services
3. Service layer implements business logic and calls clients
4. Clients perform actual API requests and return results
5. Results are processed by service layer and returned to tool layer
6. Tool layer formats results and returns to MCP server
## Quick Start
### Prerequisites
- Node.js 23.0 or higher
- pnpm package manager
- Valid FeiShu developer account and 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 `.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` | - | FeiShu self-built application App ID |
| FeiShu App Secret | `FEISHU_APP_SECRET` | `--feishu-app-secret` | - | FeiShu self-built application App Secret |
| 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 URL (e.g., feishu.cn/docx/<documentId>)
Returns:
- Document text content
#### `get_feishu_doc_info`
Get metadata information of a FeiShu document.
Parameters:
- `docId` - Document ID
Returns:
- Document metadata (JSON format)
### Bot Operations
#### `send_feishu_text_message`
Send a text message to a FeiShu chat.
Parameters:
- `chatId` - Chat ID
- `text` - Text content to send
Returns:
- Sending status and message ID
#### `send_feishu_card`
Send 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`
Get basic information of a FeiShu chat.
Parameters:
- `chatId` - Chat ID
Returns:
- Chat basic information (JSON format)
### Multi-dimensional Table Operations
#### `get_feishu_sheet_meta`
Get metadata information of a FeiShu multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
Returns:
- Multi-dimensional table metadata (JSON format), including table ID, name, revision, creator, creation time, permissions, etc.
#### `get_feishu_sheet_tables`
Get a list of data tables in a FeiShu multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `pageSize` - 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:
- Data table list (JSON format), including table ID, name, field information, etc.
#### `get_feishu_sheet_views`
Get a list of views for a data table in a FeiShu multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `pageSize` - Number of views returned per page, optional, default is 20, maximum is 100
- `pageToken` - Pagination token, optional, used to get the next page of data
Returns:
- View list (JSON format), including view ID, name, type, and properties, etc.
#### `get_feishu_sheet_view`
Get 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 URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `viewId` - View ID to get detailed information
Returns:
- View details (JSON format), including view ID, name, type, and properties, etc.
#### `get_feishu_sheet_records`
Get records from a data table in a FeiShu multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `viewId` - View ID, optional, default view used if not specified
- `fieldIds` - Field ID list, optional, specify which fields to return
- `filter` - Filter conditions, optional, using FQL format
- `sort` - Sorting conditions, optional, using JSON format
- `pageSize` - Number of records returned per page, optional, default is 20, maximum is 100
- `pageToken` - Pagination token, optional, used to get the next page of data
Returns:
- Record list (JSON format), including record ID and field values
#### `get_feishu_sheet_record`
Get a single record from a FeiShu multi-dimensional table.
Parameters:
- `appToken` - Multi-dimensional table ID, usually found in URL (e.g., feishu.cn/base/<appToken> or feishu.cn/app/<appToken>)
- `tableId` - Data table ID
- `recordId` - Record ID
- `fieldIds` - Field ID list, optional, specify which fields to return
Returns:
- Single record (JSON format), including record ID and field values
## Development Guide
### Code Style
The project uses strict TypeScript specifications 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 use English
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 FeiShu API-related errors 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>
```
Example:
- `feat(bot): Add send card feature`
- `fix(documents): Fix document content retrieval error`
Supported types:
- `feat`: New feature
- `fix`: Fix bug
- `docs`: Documentation change
- `style`: Code format adjustment
- `refactor`: Code refactoring
- `perf`: Performance optimization
- `test`: Test-related
- `chore`: Build process or auxiliary tool changes
### Extension Guide
Steps to add new features:
1. **Create client class**
- Create in `src/client/<feature>/` directory
- Inherit `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 `src/services/<feature>/` directory
- Use 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 new service in `src/services/index.ts`
- Add service to `FeiShuServices` class
4. **Create MCP tool**
- Create in `src/server/tools/feature-tools.ts`
- Use Zod for parameter validation
- Call service layer method
```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 tool**
- Import and register new tool in `src/server/tools/index.ts`
## FAQ
### Authentication Failure
**Issue**: API request returns authentication error
**Solution**:
- Check if application ID and secret are correct
- Confirm if the application has required permission scopes
- Check if server time is synchronized correctly
### Token Refresh Issue
**Issue**: Token refresh fails
**Solution**:
- Set shorter token cache duration
- Check network connection stability
- View application status on FeiShu developer platform
## License
MIT
## Contribution Guide
Welcome to contribute! Please follow these steps:
1. Fork repository
2. Create feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'feat: add some amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open Pull Request
Ensure before submitting PR:
- Code passes all tests
- Updated relevant documentation
- Follow project's code style and naming conventions
- Add necessary unit tests
Connection Info
You Might Also Like
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
awesome-mcp-servers
A collection of MCP servers.
git
A Model Context Protocol server for Git automation and interaction.
oh-my-opencode
Background agents · Curated agents like oracle, librarians, frontend...
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
Appwrite
Build like a team of hundreds