Skip to main content
Glama

ToolKit Local Skill Agent

A local skill assistant based on the MCP (Model Context Protocol), supporting custom skills such as calculators and weather queries, with both Web and API interfaces.

Project Structure

..
├── .env                    # 大模型 API 配置
├── chat_history.db         # SQLite 对话历史数据库(自动生成)
├── index.html              # 前端 Web 界面
├── main.py                 # 主入口(命令行界面)
├── mcp_server.py          # MCP 服务端(核心)
├── server.py               # Flask 后端服务
├── requirements.txt        # 依赖清单
├── README.md               # 项目说明
├── tree.txt                # 目录结构
├── client/                 # 客户端目录
│   ├── doubao_mcp_client.py  # 豆包 API 客户端
│   └── __init__.py
├── config/                 # 配置目录
│   ├── settings.py         # 全局配置
│   └── __init__.py
└── skills/                 # 技能实现目录
    ├── calculator.py       # 计算器技能
    ├── weather.py          # 天气查询技能
    ├── web_search/         # 网络搜索技能目录
    │   └── web_search.py   # DuckDuckGo搜索实现
    |   └── SKILL.md  # skill描述
    |   └── _init_.py   
    └── __init__.py

Related MCP server: MCP Connection Hub

Tech Stack

Backend Framework: Python + Flask for Web services, providing RESTful APIs and SSE streaming interfaces.

AI Protocol & Model Invocation: Based on OpenAI-compatible SDK to interface with LLM APIs, supporting models like Doubao that use the OpenAI format.

Core Protocol: MCP (Model Context Protocol) for standardized tool invocation, unifying skill registration and scheduling.

Asynchronous Architecture: asyncio processing + thread pool isolation to resolve blocking issues in Flask's synchronous environment.

Data Persistence: SQLite for multi-session conversation context storage, supporting session management and history loading.

Skill Plugin System: Modular skill system supporting pluggable tools like calculators, weather, and web search.

Frontend: Native HTML/JS for the Web interface, supporting Markdown rendering, streaming typing effects, and chain-of-thought display.

Engineering: API variable configuration (.env), dependency management (uv/pip), error retry and fallback mechanisms, and tool invocation caching.

Core Features

Stable Asynchronous Processing - Fixed issues with using asyncio.run() directly in Flask routes; uses a thread pool to execute asynchronous functions.

Conversation History Persistence - Uses SQLite to store conversation history, ensuring data is not lost on service restart, with support for multi-session management.

Tool Invocation Fault Tolerance - Automatic retry mechanism; falls back to direct model response if tool invocation fails.

MCP Tool Caching - Caches the tool list after the first fetch to reduce redundant initialization overhead.

Streaming Output - Implemented a full SSE streaming interface for a character-by-character output experience.

Tool Invocation Prompts - Displays "[Invoked tool: {Tool Name}]" when a skill is called.

Multi-platform Support - Provides both Web and command-line interfaces.

Rich Skill Set - Built-in calculator, weather query, and web search skills.

Skill Management - Visual skill management in the frontend, allowing users to toggle skills freely.

Markdown Rendering - Supports Markdown-formatted responses, including code highlighting, tables, lists, and mathematical formulas.

Chain-of-Thought Display - Collapsible AI reasoning process display for better understanding of logic.

Multi-session Management - Supports creating multiple independent conversations, each with its own saved history.

History Loading - Automatically loads conversation history when switching sessions, maintaining a complete record of interactions.

Environment Requirements

  • Python 3.11+

  • openaiSDK(api)

  • uv package manager (recommended) or pip

Installation

  1. Install uv

    # Windows
    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser 
    irm https://astral.sh/uv/install.ps1 | iex
    
    # macOS / Linux
    curl -LsSf https://astral.sh/uv/install.sh | sh
  2. Clone the project

    git clone https://github.com/taffy123d/Doubao-MCP-agent
    cd <项目目录>
  3. Create a virtual environment

    uv venv
  4. Install dependencies

    uv sync

Method 2: Using pip

  1. Clone the project

    git clone https://github.com/taffy123d/Doubao-MCP-agent
    cd <项目目录>
  2. Create a virtual environment

    python -m venv venv
  3. Activate the virtual environment

    # Windows
    venv\Scripts\activate
    
    # macOS / Linux
    source venv/bin/activate
  4. Install dependencies

    pip install -r requirements.txt

Configuration

  • Configure API keys in the frontend
  • Or fill in the API keys in the .env file:
# OpenAI 兼容格式的 API 配置
OPENAI_API_KEY=你的API密钥
OPENAI_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
OPENAI_MODEL=你的模型ID

Running

uv run server.py
#或者
python server.py
  • Frontend access: http://localhost:5000

  • API interface: http://localhost:5000/api/*

Method 2: Command Line Interface

uv run main.py
#或者
python main.py
  • Chat directly in the terminal

  • Supports multi-turn conversations and history

  • Type clear to clear conversation history

  • Type exit, quit to exit the program

API Endpoints

Endpoint

Method

Description

/

GET

Frontend page

/api/health

GET

Health check

/api/tools

GET

Get skill list

/api/config

GET

Get configuration

/api/config

POST

Save configuration

/api/test-connection

POST

Test API connection

/api/chat

POST

Chat (supports history)

/api/chat/stream

POST

Streaming chat (SSE)

/api/chat/clear

POST

Clear conversation history

/api/sessions

GET

Get all session lists

/api/sessions/<id>

DELETE

Delete specific session

/api/sessions/<id>/history

GET

Get session history

API Request Examples

Chat Endpoint

curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "你的API密钥",
    "model": "你的模型ID",
    "base_url": "https://ark.cn-beijing.volces.com/api/v3",
    "message": "北京天气",
    "session_id": "default"
  }'

Streaming Chat Endpoint

curl -X POST http://localhost:5000/api/chat/stream \
  -H "Content-Type: application/json" \
  -d '{
    "api_key": "你的API密钥",
    "model": "你的模型ID",
    "base_url": "https://ark.cn-beijing.volces.com/api/v3",
    "message": "北京天气",
    "session_id": "default"
  }'

Clear History Endpoint

curl -X POST http://localhost:5000/api/chat/clear \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "default"
  }'

How to Use

Web Interface

  1. Configure API

    • Enter API Key and Endpoint ID in the left configuration panel

    • Click "Test" to verify the connection

  2. Chat

    • Enter your question in the input box

    • Supported skills:

      • Calculator: calculate 123+456

      • Weather: Beijing weather

      • Web Search: search latest AI news

  3. Skill Management

    • Click "🔧 Skill Management" on the left to expand the panel

    • View all available skills and their descriptions

    • Toggle switches to enable/disable skills

    • Only enabled skills will be invoked

  4. Multi-session Management

    • Click "💬 Conversation Management" on the left to expand the panel

    • Click "➕ New Chat" to create a new session

    • Click items in the list to switch sessions

    • Click 🗑️ to delete unwanted sessions

    • Each session saves its own history

  5. View Results

    • The system automatically invokes the appropriate skill and returns results

    • Supports Markdown formatting (code highlighting, tables, lists, etc.)

    • Click "🧠 Thought Process" to view AI reasoning logic

    • Supports multi-turn conversations

Command Line Interface

  1. Run the program

python main.py
  1. Enter questions

    • Type your question directly in the terminal

    • Supported skills:

      • Calculator: calculate 123+456

      • Weather: Beijing weather

  2. View results

    • The system automatically invokes the appropriate skill and returns results

    • Supports multi-turn conversations

    • Type clear to clear conversation history

How to Add New Skills

Step 1: Create a skill file

Create a new skill file in the skills/ directory, e.g., my_skill.py:

"""我的自定义技能"""
from mcp.server.fastmcp import FastMCP

def register_my_skill(mcp: FastMCP):
    """注册技能到 MCP 服务"""
    
    @mcp.tool()
    def my_skill(param1: str, param2: int = 1) -> str:
        """
        我的自定义技能描述
        示例:my_skill(param1="值", param2=2)
        
        Args:
            param1: 参数1描述
            param2: 参数2描述(默认值)
        Returns:
            技能执行结果
        """
        try:
            # 技能逻辑实现
            result = f"处理结果: {param1} - {param2}"
            return result
        except Exception as e:
            return f"处理失败: {str(e)}"

Step 2: Register the skill

Edit skills/__init__.py and add the registration function for the new skill:

from .calculator import register_calculator_tool
from .weather import register_weather_tool
from .my_skill import register_my_skill

__all__ = [
    "register_calculator_tool", 
    "register_weather_tool",
    "register_my_skill"
]

Step 3: Update the MCP service

Edit mcp_server.py and add the registration for the new skill:

from skills import register_calculator_tool, register_weather_tool, register_my_skill

# 注册所有技能工具
register_calculator_tool(mcp)
register_weather_tool(mcp)
register_my_skill(mcp)  # 添加这一行

Step 4: Restart the service

Restart the MCP service and the backend service to use the new skill.

Skill Development Specifications

  1. File Naming: Use lowercase letters and underscores

  2. Function Naming: Use register_xxx_tool format

  3. Tool Decorator: Use @mcp.tool() decorator

  4. Docstrings: Include functional description, examples, and parameter explanations

  5. Error Handling: Catch exceptions and return friendly prompts

  6. Parameter Types: Use type annotations

How to Create Complex Skills (with SKILL.md)

For complex skills, it is recommended to create an independent skill directory containing the implementation and a SKILL.md description file.

Directory Structure

skills/
└── my_complex_skill/          # skill 目录
    ├── __init__.py            # 导出配置(必选)
    ├── my_skill.py            # 技能实现(必选)
    └── SKILL.md               # skill 描述文档(必选)

Step 1: Create skill directory and implementation file

Create a new skill directory in skills/, e.g., skills/my_complex_skill/

1.1 Create implementation file my_skill.py

"""我的复杂技能实现"""
from mcp.server.fastmcp import FastMCP
from duckduckgo_search import AsyncDuckDuckGoSearcher  # 示例依赖

def register_my_complex_skill(mcp: FastMCP):
    """注册复杂技能到 MCP 服务"""
    
    @mcp.tool()
    async def my_complex_skill(query: str, limit: int = 5) -> str:
        """
        我的复杂技能描述
        
        Args:
            query: 查询关键词
            limit: 返回结果数量,默认5
        
        Returns:
            格式化的搜索结果
        """
        try:
            async with AsyncDuckDuckGoSearcher() as searcher:
                results = await searcher.atext(query, max_results=limit)
                # 处理并返回结果
                return f"找到 {len(results)} 条结果..."
        except Exception as e:
            return f"搜索失败: {str(e)}"

1.2 Create __init__.py to export configuration

"""my_complex_skill - 我的复杂技能"""
from .my_skill import register_my_complex_skill

__all__ = ["register_my_complex_skill"]

1.3 Create SKILL.md description document

# 我的复杂技能

## 功能描述
一句话描述技能功能...

## 使用场景
### ✅ 适用场景
- 场景1
- 场景2

## 参数说明
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| query | string | 是 | - | 查询关键词 |

## 使用示例
```python
# 示例1
my_complex_skill(query="关键词")

Return Result Format

  • Result 1: xxx

  • Result 2: xxx

Exception Handling

Error Type

Handling Method

Network Error

Return a friendly error prompt

Notes

  1. Note 1

  2. Note 2


### 步骤 2:更新 skills/__init__.py

```python
from .calculator import register_calculator_tool
from .weather import register_weather_tool
from .web_search import register_web_search_tool
from .my_complex_skill import register_my_complex_skill  # 新增

__all__ = [
    "register_calculator_tool", 
    "register_weather_tool",
    "register_web_search_tool",
    "register_my_complex_skill"  # 新增
]

Step 3: Update mcp_server.py

from skills import (
    register_calculator_tool, 
    register_weather_tool, 
    register_web_search_tool,
    register_my_complex_skill  # 新增
)

# 注册所有技能工具
register_calculator_tool(mcp)
register_weather_tool(mcp)
register_web_search_tool(mcp)
register_my_complex_skill(mcp)  # 新增

Step 4: Install extra dependencies (if needed)

If the new skill requires additional Python packages, add them using uv add or in requirements.txt:

uv add 包名称
或
包名称 >=版本号 #requirements.txt

Then run:

uv sync
# 或
pip install 包名称

Step 5: Restart the service

Restart the service to use the new skill.

SKILL.md Specification

Field

Required

Description

# Title

Yes

Skill name

## Functional Description

Yes

One-sentence description of the skill

## Usage Scenarios

Recommended

List applicable scenarios

## Parameter Description

Recommended

Explain parameters in table format

## Usage Examples

Recommended

Code and conversation examples

## Return Result Format

Recommended

Explain the structure of returned content

## Exception Handling

Recommended

Error handling methods

## Notes

Recommended

Usage precautions

Example Skills

Calculator Skill

  • Function: Supports addition, subtraction, multiplication, division, parentheses, and exponentiation

  • Invocation: calculate (10+5)*2

Weather Query Skill

  • Function: Query city weather and forecasts

  • Invocation: Shanghai weather or Beijing weather 3 days

Web Search Skill

  • Function: Use DuckDuckGo to search for the latest news

  • Invocation: search latest Python version or search today's tech news

  • Dependency: ddgs library (pip install duckduckgo-search)

Technical Highlights

  1. Async Processing Optimization - Uses a thread pool to execute async functions, avoiding the issue of creating a new event loop for every request

  2. Conversation History Persistence - SQLite-based persistent storage, data survives service restarts, supports multi-session isolation

  3. Tool Invocation Fault Tolerance - Automatically retries twice on failure, falls back to direct model response, improving robustness

  4. MCP Tool Caching - Reduces redundant initialization overhead, improving response speed

  5. Streaming Output Implementation - Full SSE streaming interface for better user experience

  6. Tool Invocation Prompts - Clear tool invocation prompts for better UX

  7. Multi-platform Support - Provides both Web and CLI interfaces

  8. Skill Management System - Visual skill management in the frontend with flexible toggling

  9. Markdown Rendering - Full Markdown support, including code highlighting, tables, etc.

  10. Chain-of-Thought Display - Collapsible AI reasoning process display

  11. Multi-session Management - Full session creation, switching, and deletion functionality

  12. History Loading - Automatically loads and displays session history

Notes

  1. API Key Security: Do not commit API keys to version control

  2. Skill Security: Avoid performing dangerous operations within skills

  3. Performance Optimization: Consider using async processing for time-consuming operations

  4. Error Handling: Ensure skills handle exceptions gracefully

Troubleshooting

  • Connection Failed: Check API key and network connection

  • Skill Not Responding: Check if the MCP service is running normally

  • Frontend Not Displaying: Check browser console for errors

  • Streaming Interface Issues: Ensure stable network connection to avoid mid-stream disconnection

  • Database Error: Check chat_history.db file permissions to ensure read/write access

Data Storage

The project uses an SQLite database to persist conversation history:

  • Database File: chat_history.db (root directory, generated automatically on first run)

  • Table Structure:

    CREATE TABLE messages (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      session_id TEXT NOT NULL,    -- 会话ID,支持多会话隔离
      role TEXT NOT NULL,           -- 角色(user/assistant/tool)
      content TEXT NOT NULL,        -- 消息内容
      timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
    )
  • Query History: Use SQLite tools or command line to view

    sqlite3 chat_history.db "SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10;"

Extension Suggestions

  1. More Skills: Add translation, stock queries, news, etc.

  2. Multi-language Support: Add multi-language interface

  3. Deployment Optimization: Use Docker for containerized deployment

  4. Skill Marketplace: Create a marketplace for users to share and download skills

  5. Model Switching: Support switching between different LLMs

Changelog

2026-03-29 Major Update

API Invocation Upgrade

  • httpx → OpenAI SDK: All API calls changed from httpx direct HTTP requests to openai>=1.0.0 SDK

  • Configuration Field Renaming:

    • DOUBAO_API_KEYOPENAI_API_KEY

    • DOUBAO_ENDPOINT_IDOPENAI_MODEL

    • DOUBAO_BASE_URLOPENAI_BASE_URL (removed /chat/completions suffix)

Tool Invocation Optimization

  • Schema Cleanup: Automatically removes fields not supported by Doubao API such as title, default

  • Description Cleanup: Compresses extra whitespace, optimizes formatting

  • Message Conversion: Added _msg_to_dict() function to correctly handle ChatCompletionMessage objects returned by the OpenAI SDK

  • Second Invocation: Fixed message format issues for secondary requests after tool invocation

Bug Fixes

  • ✅ Fixed "Object of type ChatCompletionMessage is not JSON serializable" error

  • ✅ Fixed type conversion issues when saving message history

  • ✅ Added detailed exception stack traces for easier debugging

Architecture Improvements

  • Added _msg_to_dict() helper function for unified message format conversion

  • Added API type detection (automatically skips tools parameter for Xunfei API)

  • Optimized exception handling and logging for chat() route


F
license - not found
Not graded
quality - not tested
D
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    A comprehensive demonstration server that provides tools for calculations, weather, and note management alongside an interactive web interface. It showcases how AI assistants can seamlessly interact with external data sources and functions using the Model Context Protocol.
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables AI assistants to operate Huawei Cloud resources (ECS, OBS, GaussDB, etc.) through conversational workflows via the Model Context Protocol.
    Apache 2.0

View all related MCP servers

Related MCP Connectors

  • A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…

  • Agent-first skill marketplace with USK open standard for Claude, Cursor, Gemini, Codex CLI.

  • Git-backed platform for skills, tools, and context for AI agents

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/taffy123d/LocalSkill-MCP-Agent'

If you have feedback or need assistance with the MCP directory API, please join our Discord server