Lark-MCP-Gateway
A dedicated server component facilitating robust integration with Lark (FeiShu) platform functionalities, enabling AI agents to interact with documents, orchestrate team communications, and dispatch notifications via a standardized protocol interface. This implementation prioritizes resilient exception management and leverages TypeScript for comprehensive compile-time type assurance.
Author

sdd330
Quick Info
Actions
Tags
Lark/FeiShu Model Context Protocol (MCP) Integration Hub
This Lark MCP Gateway service acts as a bridge, adhering to the Model Context Protocol specification, to expose Lark's extensive service APIs for seamless consumption by intelligent agents and automated workflows.
Table of Contents
- Core Capabilities
- System Architecture
- Component Organization
- Design Philosophy
- Operational Flowchart
- Getting Started
- Prerequisites Checklist
- Installation Sequence
- Service Initiation
- Configuration Parameters
- Exposed Tool Interface Reference
- Document Operations
- Bot Messaging Interfaces
- Chat Session Management
- Spreadsheet/Base Data Interactions
- Development Guidelines
- Coding Standards Enforcement
- Exception Handling Protocols
- Commit Message Conventions
- Feature Extension Blueprint
- Troubleshooting FAQs
- Software Licensing
- Contributing Policy
Core Capabilities
- Document Management: Read content streams and metadata pertaining to Lark Docs.
- Messaging Agents: Dispatch rich text messages and interactive cards to designated Lark chats.
- Session Control: Administrative functions for managing group chats and conversation contexts.
- Interoperability Modes:
- STDIO Channel: Communication via standard I/O streams, ideal for CLI embedding or process piping.
- Network Endpoint: Provides a RESTful API facade alongside Server-Sent Events (SSE) for microservice deployment.
- Comprehensive Error Abstraction: Centralized mechanism for reporting detailed failure diagnostics.
- Type Safety Guarantee: Full static typing leveraging the TypeScript ecosystem.
- Modular Design: Architecture engineered for facile incorporation of novel capabilities and deeper Lark API coverage.
System Architecture
Component Organization
/src /client # Abstraction layer for raw platform HTTP interactions /documents # Document API Client implementations /bots # Bot/Messaging API Client implementations /chats # Chat/Session API Client implementations /services # Business logic and orchestration layer /documents # Document service modules /bots # Bot service modules /chats # Chat service modules /server # Core MCP server registration logic /tools # MCP Tool registration and execution handlers /typings # Global type definitions and interfaces /utils # Generic utility functions /http # Network server setup (e.g., Express/Fastify wrapper) /logger # Structured logging infrastructure /consts # Constant definitions config.ts # Configuration loading and validation index.ts # Primary application bootstrap
Design Philosophy
The system enforces a layered segregation of concerns to maximize maintainability:
1. Responsibility Stacks
- Client Layer (ApiClient)
- Handles low-level HTTP transport details.
- Manages request formatting and response deserialization.
- Owns authentication token lifecycle.
-
Must remain strictly business-logic free.
-
Service Layer (ServiceBase)
- Orchestrates calls to the Client Layer.
- Implements domain-specific business rules.
- Performs error transformation and sanitization.
-
Exposes simplified methods to the Tool Layer.
-
Tool Layer (MCP Tool)
- Implements the specific functions defined by the MCP specification.
- Executes parameter validation (Zod).
- Invokes the Service Layer for fulfillment.
- Formats the final output payload for MCP consumption.
2. Dependency Flow
- Services are dependent on Clients.
- Tools are dependent on Services.
- Circular dependencies are strictly forbidden.
3. Error Management Regimen
- All platform communication failures are initially wrapped in a custom
LarkPlatformError. - The Client Layer propagates raw errors.
- The Service Layer catches and maps these to domain-specific exceptions.
- The Tool Layer centralizes final exception capture, logs the issue, and returns a standardized, user-friendly failure message via the MCP contract.
Operational Flowchart
- MCP Request ingress (via STDIO or HTTP).
- Tool Layer validates input schemas and delegates to the appropriate Service.
- Service Layer executes business logic by interfacing with the Client Layer.
- Client Layer executes the native Lark API call.
- Results propagate back through the Service Layer for transformation.
- Tool Layer finalizes formatting and transmits the result payload back to the MCP Listener.
Getting Started
Prerequisites Checklist
- Node.js runtime, version 23.0 or newer.
- pnpm package manager.
- An active Lark Developer Account with an established self-hosted application.
Installation Sequence
- Clone the repository source code:
bash git clone https://github.com/yourusername/feishu-mcp-server.git cd feishu-mcp-server
- Install project dependencies:
bash pnpm install
- Establish the environment configuration file (
.env):
Lark Application Credentials (Mandatory)
LARK_APP_ID=your_lark_app_id LARK_APP_SECRET=your_lark_app_secret
Server Runtime Settings (Optional)
GATEWAY_PORT=3344 RUNTIME_LOG_VERBOSITY=info
Service Initiation
Development Mode
bash
Hot-reloading development execution
pnpm dev
Standard execution
pnpm start
Production Deployment
bash
Compile TypeScript assets
pnpm build
Execute compiled artifact
node dist/index.js
STDIO Mode Activation
bash
Via environment flag
NODE_ENV=cli node dist/index.js
Via command line argument
node dist/index.js --stdio-mode
Configuration Parameters
| Parameter Name | Env Var | CLI Flag | Default | Purpose |
|---|---|---|---|---|
| Lark App ID | LARK_APP_ID |
--lark-app-id |
N/A | Unique identifier for the Lark application. |
| Lark App Secret | LARK_APP_SECRET |
--lark-app-secret |
N/A | Confidential credential for authorization. |
| HTTP Server Port | GATEWAY_PORT |
--port |
3344 | TCP port for network API listeners. |
| Logging Detail | RUNTIME_LOG_VERBOSITY |
--log-level |
info | Log output severity (debug/info/warn/error). |
| Token Lifespan | TOKEN_CACHE_DURATION |
- | 7100 | Access token persistence duration in seconds. |
Exposed Tool Interface Reference
Document Operations
read_lark_doc_content
Retrieves the raw, plain text content body of a specified Lark Document.
Parameters:
- doc_id - The unique identifier extracted from the document URL.
Returns: - The raw textual payload of the document.
fetch_lark_doc_metadata
Queries the core metadata associated with a Lark Document resource.
Parameters:
- doc_id - The document's unique handle.
Returns: - Document metadata object serialized as JSON.
Bot Messaging Interfaces
dispatch_lark_text_message
Transmits a plain text notification to a specified Lark chat session.
Parameters:
- chat_id - Target conversation identifier.
- text_payload - The message string to be delivered.
Returns: - Confirmation of delivery status and the resulting message UUID.
send_lark_interactive_card
Publishes a structured interactive card message to a Lark conversation.
Parameters:
- chat_id - Target conversation identifier.
- card_json_data - The card definition encoded as a JSON string.
Returns: - Delivery confirmation and associated message ID.
Chat Session Management
query_lark_chat_details
Fetches fundamental descriptive information for a given Lark chat.
Parameters:
- chat_id - The session identifier.
Returns: - Basic chat metadata in JSON format.
Spreadsheet/Base Data Interactions
get_lark_sheet_blueprint
Obtains structural metadata for a Lark Spreadsheet (Base).
Parameters:
- app_token - The unique identifier for the Spreadsheet, often found in the resource URL (e.g., /base/<appToken>).
Returns: - Spreadsheet metadata (ID, name, revision, creator, timestamps, permissions).
list_lark_sheet_tabs
Retrieves the list of individual data tabs (sheets) contained within a Spreadsheet.
Parameters:
- app_token - Spreadsheet identifier.
- page_size - Max tabs per response (Default: 20; Max: 100).
- page_token - Cursor for paginated retrieval.
Returns: - A list of tab objects, including ID, title, and schema definitions.
enumerate_lark_sheet_views
Retrieves the configured view definitions for a specific tab within a Spreadsheet.
Parameters:
- app_token - Spreadsheet identifier.
- table_id - The specific data tab identifier.
- page_size - Max views per response (Default: 20; Max: 100).
- page_token - Cursor for paginated retrieval.
Returns: - List of view configuration objects (ID, name, type, properties).
retrieve_lark_sheet_view_details
Fetches the comprehensive configuration for a targeted view on a tab.
Parameters:
- app_token - Spreadsheet identifier.
- table_id - Data tab identifier.
- view_id - The specific view ID required.
Returns: - Detailed view properties object.
fetch_lark_sheet_records
Extracts record data from a specified tab, supporting filtering and sorting.
Parameters:
- app_token - Spreadsheet identifier.
- table_id - Data tab identifier.
- view_id - Optional: View to use for data context (defaults to primary view).
- field_ids - Optional: Array of field keys to include in the output.
- filter_query - Optional: Filtering expression using FQL syntax.
- sort_criteria - Optional: Sorting instructions in JSON format.
- page_size - Record count per page (Default: 20; Max: 100).
- page_token - Continuation token for the next data batch.
Returns: - A list of record objects, including record identifiers and requested field values.
get_single_lark_sheet_record
Retrieves a single record instance by its unique ID.
Parameters:
- app_token - Spreadsheet identifier.
- table_id - Data tab identifier.
- record_id - The primary key of the record to fetch.
- field_ids - Optional: Subset of fields to return.
Returns: - The specific record object containing its ID and field data.
Development Guidelines
Coding Standards Enforcement
The project strictly adheres to established TypeScript conventions and ESLint rules:
- Mandatory use of TypeScript interfaces and explicit types.
- Prohibition of the
anyprimitive type. - Prefer
Record<string, unknown>over generic{}orobject. - All source code, inline documentation, and error messages must be in standardized English.
Execution commands:
bash
Run static analysis checks
pnpm lint
Run analysis and attempt automatic fixes
pnpm lint:fix
Execute code formatter (e.g., Prettier)
pnpm format
Exception Handling Protocols
All platform API interactions must utilize the LarkPlatformError abstraction:
typescript
try {
// Invocation of a Lark API client method
} catch (error) {
if (error instanceof LarkPlatformError) {
// Specific handling for known platform errors (e.g., check error.code)
logger.error(Lark API Failure (${error.code}): ${error.message});
} else {
// Catching unforeseen system exceptions
logger.error('System Exception Encountered:', error);
}
// Re-throw a standardized, controlled exception for the caller
throw new LarkPlatformError('Operation execution failed internally', { cause: error });
}
Commit Message Conventions
Adherence to Conventional Commits structure is required:
Examples:
- feat(messaging): Implement card dispatch mechanism
- fix(docs): Resolve token expiration logic during doc fetching
Accepted Types:
- feat: Introduction of a new feature.
- fix: Resolution of a defect/bug.
- docs: Modifications to documentation artifacts.
- style: Formatting adjustments that do not alter logic.
- refactor: Code restructuring without functional changes.
- perf: Optimization yielding performance gains.
- test: Adding or modifying test cases.
- chore: Maintenance tasks, build scripts, or utility updates.
Feature Extension Blueprint
To introduce a new Lark capability (e.g., 'Calendar'):
- Develop the Client Module
- Create file in
src/client/calendar/. - Extend the base
ApiClientclass. - Implement the specific HTTP request handlers.
typescript
// src/client/calendar/calendar-client.ts
export class CalendarClient extends ApiClient {
async getCalendarEvents(calendarId: string): Promise
- Implement the Service Logic
- Create file in
src/services/calendar/. - Inject and utilize the
CalendarClient. - Apply necessary data transformation and error wrapping.
typescript // src/services/calendar/calendar-service.ts export class CalendarService { private client: CalendarClient;
constructor(config: ApiClientConfig) {
this.client = new CalendarClient(config);
}
async retrieveEvents(calendarId: string): Promise<CalendarEvents> {
try {
const rawData = await this.client.getCalendarEvents(calendarId);
return this.mapResponseToDomain(rawData); // Transformation logic
} catch (error) {
LarkErrorHandler(error); // Robust error handling
}
}
}
- Register the Service
- Export the new service in
src/services/index.ts. -
Integrate it into the central
LarkServicesContainer. -
Define the MCP Tool
- Create tool handler in
src/server/tools/calendar-tools.ts. - Use Zod schema for input contract definition.
- Call the new service method.
typescript // src/server/tools/calendar-tools.ts export function registerCalendarTools(params: ToolRegistryParams): void { const { server, services, logger } = params;
server.tool(
'get_lark_calendar_events',
'Fetch event list for a calendar',
{
calendarId: z.string().describe('The calendar identifier'),
},
async ({ calendarId }) => {
try {
const events = await services.calendar.retrieveEvents(calendarId);
return { content: [{ type: 'json', data: events }] };
} catch (error) {
return formatToolError(error, logger);
}
}
);
}
- Final Integration
- Import and execute
registerCalendarToolswithin the main tool registration pipeline (src/server/tools/index.ts).
Troubleshooting FAQs
Authentication Failure
Symptom: API calls consistently return authorization errors (e.g., 401/403).
Resolution Path:
- Validate that LARK_APP_ID and LARK_APP_SECRET match the configuration panel exactly.
- Verify that the application has been granted all necessary permission scopes required by the operation.
- Check system clock synchronization on the host machine.
Token Refresh Instability
Symptom: Intermittent failures during token acquisition or renewal.
Resolution Path:
- Temporarily shorten the TOKEN_CACHE_DURATION to force more frequent re-acquisition.
- Examine network connectivity or potential firewall restrictions blocking external Lark endpoints.
- Monitor the Lark Developer Console for platform-specific rate limiting notices.
Software Licensing
This project is distributed under the permissive MIT License.
Contributing Policy
We welcome contributions! Follow these standardized steps for submission:
- Fork the primary repository.
- Establish a feature branch (
git checkout -b feature/rocket-ship-integration). - Commit changes clearly (
git commit -m 'feat(calendar): Added event retrieval logic'). - Push the new branch to your fork (
git push origin feature/rocket-ship-integration). - Submit a Pull Request against the main branch.
Ensure the following criteria are met before submitting a PR: - All associated unit and integration tests pass successfully. - All relevant documentation artifacts have been updated. - Adherence to established project coding style and naming conventions is verified. - New features include comprehensive test coverage.
