LarkAgentNexus
A framework facilitating AI-driven function execution and message processing within the Lark environment, leveraging an existing user account as the conversational AI interface. It dynamically maps user prompts to appropriate tool invocations and ensures all interaction history is persistently cataloged in a MySQL backend.
Author

cv-cat
Quick Info
Actions
Tags
Lark Agent Nexus - Your Integrated Feishu AI Conduit 🚀
An advanced AI Agent built atop the Feishu (Lark) platform, enabling large language models to perform sophisticated function calls and manage bidirectional message flow.
Activate AI capabilities instantly—no separate bot setup required. Your personal Lark account becomes the intelligent assistant.
Simply define the required functions and their documentation; the system automatically handles invocation based on context.
Project Synopsis 🌟
Lark Agent Nexus is a contemporary Python implementation engineered to:
- 📊 Intercept and decode Feishu's proprietary Websocket traffic and APIs for real-time message capture and logging.
- 🤖 Expose a curated set of callable functions ready for model utilization.
- 🔄 Establish a robust function invocation architecture compliant with the Model Context Protocol (MCP).
- 💾 Ensure transactional integrity by persisting all conversation logs into a MySQL database via SQLAlchemy.
Visual Demonstrations 🧸
Figure 1: Backend Operational Log
Figure 2: Database Record Inspection
Figure 3: Weather Retrieval Example
Figure 4: Function Registration Simplicity
✨ Core Capabilities
- Tool Registration System: Intuitive decorator-based mechanism for instantly onboarding new functions.
- Comprehensive Message Capture: Logs all incoming communications (both direct messages and group chats).
- Asynchronous Operations: Fully leverages async/await patterns for non-blocking communication.
- Data Persistence Layer: Utilizes SQLAlchemy for reliable storage in MySQL.
- Configuration Flexibility: Managed entirely through environmental variables.
- Containerization Support: Includes assets for rapid deployment via Docker.
- Intelligent Tool Invocation: The AI autonomously analyzes natural language input to select the optimal function; developers only need to provide the function signature and descriptive docstrings.
📦 Currently Available Tools
This project preloads the following utilities for model access:
| Function Name | Description |
|---|---|
tell_joke |
Deliver a random humorous anecdote |
get_time |
Retrieve the current system time |
fortune |
Draw a random daily prognostication |
get_weather |
Fetch meteorological data for a specified locale |
count_daily_speakers |
Tabulate the number of unique participants today |
get_top_speaker_today |
Identify the most prolific communicator in the current day |
send_message |
Transmit a private message to a designated recipient |
list_tools |
Output the registry of all accessible functions and their summaries |
extra_order_from_content |
Parse textual data to extract structured order details (ID, item, quantity, etc.) |
Invocation is typically triggered via a predefined prefix followed by the desired action, e.g., /run Tell me a joke.
📂 Directory Layout
project/ ├── app/ # Application core modules │ ├── api/ # Interface definitions │ │ ├── auth.py # Authentication protocols │ │ └── lark_client.py # Feishu communication handler │ ├── config/ # System parameters │ │ └── settings.py # Configuration loading │ ├── core/ # Primary business logic │ │ ├── mcp_server.py # MCP engine (tool registration/dispatch) │ │ ├── llm_service.py # Language Model integration layer │ │ └── message_service.py # Incoming message processing pipeline │ ├── db/ # Data access layer │ │ ├── models.py # SQLAlchemy entity definitions │ │ └── session.py # Database session management │ └── utils/ # Utility functions ├── builder/ # Request payload construction utilities ├── extension/ # External integrations │ └── weather_api/ # Weather service adapter ├── static/ # Static assets │ ├── resource/ # Imagery and media │ ├── proto_pb2.py # Generated protocol buffers │ └── lark_decrypt.js # Auxiliary Feishu decryption utility ├── .env # Runtime variables definition ├── main.py # Application bootstrap ├── requirements.txt # Python dependency manifest ├── docker-compose.yml # Multi-container orchestration file └── Dockerfile # Single container build instructions
🛠️ Custom Tool Development
Extend functionality by defining new methods within app/core/mcp_server.py and marking them with the @register_tool decorator:
python @register_tool(name="tell_joke", description="Deliver a random humorous anecdote") def tell_joke() -> str: jokes = [ "Why do programmers prefer dark mode? Because light attracts bugs.", "What do Python and snakes have in common? Once they wrap around you, letting go is hard.", "Why are Java developers rarely invited to parties? They constantly throw exceptions.", ] return random.choice(jokes)
@register_tool(name="send_message", description="Transmit a private message to a designated recipient {user:recipient_name content:message_body}") def send_message(user: str, content: str) -> str: """Sends a direct message to the specified user via Lark.""" lark_client = LarkClient(get_auth()) # ... Implementation details ... return f"Successfully relayed private message to {user}: '{content}'"
Crucial Note: By merely supplying the function definition and its descriptive documentation, the AI is empowered to automatically deduce and execute the correct tool based on user queries, eliminating the need for manual invocation logic.
🔧 Prerequisites
- Python Interpreter (Version 3.10 or newer)
- Node.js Runtime (Version 18 or newer)
- Active MySQL Database Instance
📦 Installation Procedures
Local Environment Setup
-
Install necessary dependencies: bash pip install -r requirements.txt
-
Windows Users Note: Specific compatibility packages may be required on Windows: bash pip install win-inet-pton==1.1.0
Docker Deployment
Option A: Manual Image Build bash
Build the image
docker build -t feishuapp .
Run the container (requires external mysql access, recommended via --env-file)
docker run -it feishuapp bash
Option B: Docker Compose (Recommended for full stack) bash
Start all services (application and database) in detached mode
docker-compose up -d
Monitor combined logs
docker-compose logs -f
Terminate and remove all services
docker-compose down
Docker Compose streamlines the process by provisioning the entire stack, including the MySQL dependency, making initialization efficient and reproducible.
🛠️ Configuration Variables
Duplicate the .env.example file into .env and populate the following settings:
Database Connection Parameters
DB_HOST=localhost DB_PORT=3306 DB_USER=root DB_PASSWORD=123456 DB_NAME=lark_messages
Lark Session Cookie - Bypasses official bot setup by utilizing user session
LARK_COOKIE=""
Function Trigger Prefix (Inputs prefixed with this are parsed for tool calls; ALL messages are logged regardless of prefix)
FUNCTION_TRIGGER_FLAG="/run"
AI Response Prefix (Currently reserved/unused)
AI_BOT_PREFIX="Lark AI Bot:"
LLM Provider Configuration (Defaults to Alibaba Qwen, compatible with OpenAI endpoints)
OPENAI_API_KEY="" OPENAI_API_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" OPENAI_API_MODEL="qwen-plus"
🚀 Execution Guide
Starting the Service
Method 1: Direct Execution bash python main.py
Method 2: Docker Compose Orchestration bash docker-compose up -d
The system will proceed to: 1. Initialize the MCP engine. 2. Establish a persistent connection to Lark, operating under your user credentials. 3. Monitor incoming stream data. 4. Interpret and execute tool requests dispatched by the LLM via Feishu. 5. Persist conversation records into the configured MySQL storage.
🗄️ Database Schema Details
The interaction records are stored in the messages table with the following attributes:
| Column Name | Data Type | Purpose |
|---|---|---|
| id | INT (PK) | Primary Identifier |
| user_name | VARCHAR(255) | Sender's Display Name |
| user_id | VARCHAR(255) | Sender's Unique Lark ID |
| content | TEXT | Full text of the message |
| is_group_chat | BOOLEAN | Flag indicating group origin |
| group_name | VARCHAR(255) | Group context (if applicable) |
| chat_id | VARCHAR(255) | Unique chat thread identifier |
| message_time | DATETIME | Timestamp of original message submission |
| created_at | DATETIME | Timestamp of database record creation |
🤝 Contribution Protocol
We welcome external contributions! Please feel free to submit a Pull Request.
- Fork the repository.
- Create a dedicated feature branch (
git checkout -b feature/my-enhancement). - Commit changes (
git commit -m 'Implement amazing new feature'). - Push the branch (
git push origin feature/my-enhancement). - Open a formal Pull Request.
🐛 Support and Issue Reporting
Should you encounter any operational difficulties or require clarification, please raise an issue or participate in our community discussions.
