Content
# IMA Copilot MCP Server
Based on the FastMCP v2 framework, the Tencent IMA Copilot MCP (Model Context Protocol) server, **configured using environment variables**, simplifies the project structure and focuses on MCP protocol implementation.
## ✨ Main Features
- 🚀 **Minimal Configuration**: Only two required parameters to start, out of the box
- 🤖 **MCP Protocol Support**: Complete implementation of the Model Context Protocol specification (based on FastMCP 2.14.1)
- 🔧 **Environment Variable Configuration**: Manage all configurations through the `.env` file
- 📡 **HTTP Transport**: Supports HTTP transport protocol for easy MCP Inspector connection
- 🛠️ **Enhanced MCP Tools**: Provides Tencent IMA knowledge base Q&A functionality with structured reference materials
- 🔄 **Token Automatic Refresh**: Intelligent management of authentication tokens, automatic refresh to maintain session validity
- 💪 **Tenacity-powered Retries**: Integrated tenacity library, optimized retry mechanism, supports exponential backoff and targeted error retries
- 🧯 **Code=3 Self-healing**: Performs backoff retries and automatic recovery for high concurrency instantaneous `Code=3` errors
- 🚦 **Concurrent Limiting**: Default serial Q&A (concurrency=1), reduces system errors caused by request bursts
- 📝 **Loguru-enhanced Logging**: Adopt Loguru to enhance logging experience, providing clearer and more structured log output
- ⏱️ **Timeout Protection**: Built-in request timeout mechanism to prevent long-term blocking (up to 300 seconds)
- 🎯 **One-click Launch**: Simplified startup process, automatic environment check, and configuration verification
- 🐳 **Docker Support**: Official Docker image provided, out of the box
## 🚀 Latest Progress (2025-12-21)
- ✅ **Server Successfully Running**: Verified that the HTTP transport mode based on FastMCP 2.14.1 works normally.
- ✅ **Fixed Startup Error**: Solved the `AttributeError: 'FastMCP' object has no attribute 'on_shutdown'` issue (by disabling this hook in the current version).
- ✅ **Full-process Verification**: Verified the complete chain from token refresh, session initialization to SSE stream response parsing, supporting long replies (35 seconds+ response verified).
## Quick Start
### Method 1: Using Docker (Recommended)
#### 1. Using Docker Run
```bash
# Pull the image
docker pull highkay/tencent-ima-copilot-mcp:latest
# Run the container (need to replace the following two required environment variables)
docker run -d \
--name ima-copilot-mcp \
-p 8081:8081 \
-e IMA_X_IMA_COOKIE="your_x_ima_cookie_here" \
-e IMA_X_IMA_BKN="your_x_ima_bkn_here" \
-v $(pwd)/logs:/app/logs \
--restart unless-stopped \
highkay/tencent-ima-copilot-mcp:latest
# View logs
docker logs -f ima-copilot-mcp
```
#### 2. Using Docker Compose (More Convenient)
Create a `.env` file (or directly set environment variables in the shell):
```bash
# .env file
IMA_X_IMA_COOKIE="your_x_ima_cookie_here"
IMA_X_IMA_BKN="your_x_ima_bkn_here"
```
Start the service:
```bash
# Start the service
docker-compose up -d
# View logs
docker-compose logs -f
```
### Method 2: Local Installation
#### 1. Install Dependencies
```bash
# Install FastMCP, tenacity, Loguru, and all dependencies
pip install -r requirements.txt
```
#### 2. Configure Environment Variables
```bash
# Copy the configuration file template
cp .env.example .env
# Edit the .env file and fill in the IMA authentication information obtained from the browser
nano .env # or use another editor
```
#### Required Configuration Items
The following environment variables must be correctly configured to use the service:
- **`IMA_X_IMA_COOKIE`**: X-Ima-Cookie request header value (contains platform information, token, etc.)
- **`IMA_X_IMA_BKN`**: X-Ima-Bkn request header value (business key)
#### 3. Obtain IMA Authentication Information
#### Step 1: Access IMA Copilot
1. Visit [https://ima.qq.com](https://ima.qq.com) and log in
2. Open the developer tools by pressing F12
3. Switch to the **Network** tab
#### Step 2: Obtain Authentication Header Information
1. Send a message in IMA
2. Find the POST request to `/cgi-bin/assistant/qa`
3. View **Request Headers**, copy the following fields:
- `x-ima-cookie` → `IMA_X_IMA_COOKIE`
- `x-ima-bkn` → `IMA_X_IMA_BKN`
#### 4. Start the Server
##### Method 1: Using the Startup Script (Recommended)
```bash
# Windows
start.bat
# or use the Python script (cross-platform)
python run.py
```
##### Method 2: Using the fastmcp Command
```bash
fastmcp run ima_server_simple.py:mcp --transport http --host 127.0.0.1 --port 8081
```
#### 5. Use MCP Inspector
```bash
# Install MCP Inspector
npx @modelcontextprotocol/inspector
# Connect to the server
# Enter in Inspector: http://127.0.0.1:8081/mcp
```
### Server Endpoints
- **MCP Protocol Endpoint**: `http://127.0.0.1:8081/mcp` (for MCP Inspector or other MCP clients)
- **Log File**: `logs/debug/ima_server_YYYYMMDD_HHMMSS.log` (automatically generated and managed by Loguru)
- **Raw SSE Log**: `logs/debug/raw/sse_*.log` (automatically saved when an error occurs)
## Available MCP Tools
### 1. `ask`
Ask any question to the Tencent IMA knowledge base
**Parameters:**
- `question` (required): The question to ask
**Example:**
```
Question: "What is machine learning?"
Question: "How to make tomato omelette?"
```
**Features:**
- Automatically manage sessions without manual creation
- Intelligent token refresh to ensure authentication validity
- Built-in concurrency limiting (default `IMA_ASK_CONCURRENCY_LIMIT=1`)
- Automatically retry with exponential backoff for `Code=3` errors without text (up to 2 times)
- **300 seconds timeout protection** to prevent long-term waiting
- Return content is **`TextContent` list**, including **answer text** and formatted **reference materials**
> Note: When multiple knowledge base IDs are configured, `ask` will directly report an error and prompt to use `ask_with_kb`.
### 2. `ask_with_kb`
Ask a question to a specified knowledge base (multi-knowledge base mode)
**Parameters:**
- `question` (required): The question to ask
- `knowledge_base_id` (required): Target knowledge base ID (must be in the configuration list)
**Example:**
```
Question: "Summarize the core content of this knowledge base"
knowledge_base_id: "7305806844290061"
```
## Available MCP Resources
### 1. `ima://config`
Get the current configuration information (excluding sensitive data)
### 2. `ima://help`
Get help information
## Configuration Options
### Required Environment Variables
| Variable Name | Description | Acquisition Method |
|--------|------|---------|
| `IMA_X_IMA_COOKIE` | X-Ima-Cookie request header | Copy from browser developer tools Network tab |
| `IMA_X_IMA_BKN` | X-Ima-Bkn request header | Copy from browser developer tools Network tab |
### Optional Environment Variables
| Variable Name | Description | Default Value |
|--------|------|--------|
| `IMA_KNOWLEDGE_BASE_ID` / `knowledgeBaseId` | Single knowledge base ID (both are equivalent) | None (must be explicitly configured) |
| `IMA_KNOWLEDGE_BASE_IDS` / `knowledgeBaseIds` | Multi-knowledge base ID list (comma-separated) | None |
| `IMA_MCP_HOST` | MCP server address | `127.0.0.1` |
| `IMA_MCP_PORT` | MCP server port | `8081` |
| `IMA_MCP_LOG_LEVEL` | Log level (supports `DEBUG`, `INFO`, `WARNING`, `ERROR`) | `INFO` |
| `IMA_REQUEST_TIMEOUT` | IMA API request timeout (seconds) | `30` |
| `IMA_RETRY_COUNT` | Network/timeout exception retry times | `3` |
| `IMA_ASK_CONCURRENCY_LIMIT` | Q&A concurrency limit (recommended 1-2) | `1` |
| `IMA_ROBOT_TYPE` | Robot type | `5` |
| `IMA_SCENE_TYPE` | Scene type | `1` |
| `IMA_MODEL_TYPE` | Model type | `4` |
### Knowledge Base Configuration Mode
- Single knowledge base mode (compatible with old logic): Configure `IMA_KNOWLEDGE_BASE_ID` (or `knowledgeBaseId`), use `ask` or `ask_with_kb` as needed.
- Multi-knowledge base mode: Configure `IMA_KNOWLEDGE_BASE_IDS` (or `knowledgeBaseIds`, comma-separated), must use `ask_with_kb`.
- When both are configured: Prioritize using `IMA_KNOWLEDGE_BASE_ID` (single knowledge base mode).
- Start strong verification: If neither `IMA_KNOWLEDGE_BASE_ID` nor `IMA_KNOWLEDGE_BASE_IDS` is configured, the service will exit directly.
### Migration from Old Versions
- Using one knowledge base: Keep the original `IMA_KNOWLEDGE_BASE_ID=<id>` and no need to change the call method.
- Need multiple knowledge bases: Add `IMA_KNOWLEDGE_BASE_IDS=id1,id2,...` and change the call from `ask(question)` to `ask_with_kb(question, knowledge_base_id)`.
## Troubleshooting
### Common Issues
**Q: Authentication failed (Token verification failed), what should I do?**
A:
1. Check if `IMA_X_IMA_COOKIE` and `IMA_X_IMA_BKN` in the `.env` file are correct
2. Confirm if `IMA_X_IMA_COOKIE` contains `IMA-REFRESH-TOKEN` field
3. Re-obtain the latest authentication information from the browser
**Q: How to connect to a specific knowledge base?**
A:
Set `IMA_KNOWLEDGE_BASE_ID` (or `knowledgeBaseId`) in the `.env` file. Acquisition method:
1. Select the knowledge base on the IMA webpage
2. Find the `init_session` request
3. View Payload and find `knowledge_base_id`
**Q: How to configure and call multiple knowledge bases?**
A:
1. Set `IMA_KNOWLEDGE_BASE_IDS=id1,id2,id3` in `.env`
2. Use `ask_with_kb(question, knowledge_base_id)` when calling the tool
3. If `ask` is called, it will prompt an error and provide a list of available `knowledge_base_id`
**Q: What should I do if `Code=3` occurs occasionally without text?**
A:
1. Keep the default concurrency (`IMA_ASK_CONCURRENCY_LIMIT=1`)
2. Avoid sudden concurrent requests for the same knowledge base in a short time
3. The service has built-in `Code=3` backoff retry; if it still occurs frequently, consider increasing the request interval
## License
MIT License
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.