npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zzp123/zentao-kb-mcp

v3.5.2

Published

MCP Server for ZenTao Knowledge Base

Downloads

1,776

Readme

zentao-kb-mcp

MCP Server for ZenTao Knowledge Base / 禅道知识库 MCP 服务

npm version Node.js TypeScript MCP SDK License: MIT vitest

Let AI assistants (Claude, etc.) read and write your ZenTao Knowledge Base via Model Context Protocol.

基于禅道文档系统的知识库 MCP 服务,让 AI 助手能够直接读写禅道知识库。


Table of Contents / 目录


Architecture / 系统架构

graph TB
    subgraph MCP_Client ["MCP Client / MCP 客户端"]
        Claude["Claude Desktop / Claude Code"]
    end

    subgraph MCP_Server ["zentao-kb-mcp Server"]
        Transport["StdioServerTransport"]
        Server["MCP Server<br/>ListTools + CallTool"]
        ToolDefs["Tool Definitions<br/>17 MCP Tools"]
        Schemas["Content Schemas<br/>intro / logic / dataFormat / experience"]
        Formatters["Formatters<br/>formatTree, formatStats,<br/>formatSearch, toMcpResponse"]

        subgraph ClientLayer ["Client Layer / 客户端层"]
            IKBClient["IKBClient Interface<br/>19 methods"]
            HybridClient["HybridClient<br/>API Auth + DB Ops"]
            ApiClient["ApiClient<br/>HTTP REST Only"]
            DbClient["DbClient<br/>MySQL Direct"]
        end

        Config["Config Loader<br/>.zentaoKB / ENV"]
    end

    subgraph Backend ["ZenTao Backend / 禅道后端"]
        API["ZenTao REST API<br/>/api.php/v1/aikb/*"]
        MySQL["MySQL Database<br/>zt_ai_knowledgelib<br/>zt_ai_knowledgeitem"]
    end

    Claude -- "stdio JSON-RPC" --> Transport
    Transport --> Server
    Server --> ToolDefs
    Server --> Schemas
    Server --> ClientLayer
    ClientLayer --> Formatters
    Formatters --> Server

    Config -.->|"loadConfig()"| Server

    IKBClient -.->|implements| HybridClient
    IKBClient -.->|implements| ApiClient
    IKBClient -.->|implements| DbClient

    HybridClient -- "login + auth" --> API
    HybridClient -- "CRUD operations" --> MySQL
    ApiClient -- "all operations" --> API
    DbClient -- "all operations" --> MySQL

    style MCP_Client fill:#e1f5fe,stroke:#0288d1
    style MCP_Server fill:#f3e5f5,stroke:#7b1fa2
    style Backend fill:#e8f5e9,stroke:#388e3c
    style ClientLayer fill:#fff3e0,stroke:#f57c00

Features / 功能特性

  • 17 MCP Tools — 覆盖知识库管理全流程:项目管理、节点 CRUD、搜索、标签、统计、批量操作、发布、导出
  • Three Client Modes — 混合模式(API 认证 + 数据库)、纯 API 模式、纯数据库模式
  • Hierarchical Sub-libraries — 自动根据路径创建层级子知识库,如 "Backend/API/Users" → 3 级子库
  • TypeScript Full Typing — 完整的 TypeScript 类型定义(.d.ts
  • Connection Pooling — 数据库连接池管理,高性能持久连接
  • Vector Search — 支持语义向量搜索,回退关键词搜索
  • Content Formatting — 结构化 JSON 与 Markdown 双向转换

Database Design / 数据库设计

erDiagram
    zt_ai_knowledgelib {
        int id PK "Auto Increment"
        varchar name "Library name"
        text desc "Description"
        enum type "personal | team"
        enum acl "open | private | custom"
        int parent FK "Parent lib ID, 0=root"
        varchar path "Hierarchy path e.g. comma1comma2comma3comma"
        tinyint grade "Depth level, 1=root"
        smallint order "Sort order in siblings"
        int project "Associated project ID"
        varchar category "bug | task | logic | api | experience"
        varchar createdBy "Creator account"
        datetime createdDate "Creation time"
        varchar editedBy "Last editor"
        datetime editedDate "Last edit time"
        tinyint published "0=draft 1=published"
        enum deleted "0 | 1"
    }

    zt_ai_knowledgeitem {
        int id PK "Auto Increment"
        int lib FK "Belongs to which lib"
        varchar title "Item title"
        longtext content "Markdown content"
        varchar type "text | file | url"
        varchar contentType "markdown"
        json attrs "tags and status and contentType"
        int file "Attachment file ID"
        varchar objectType "Related object type"
        int objectID "Related object ID"
        varchar createdBy "Creator account"
        datetime createdDate "Creation time"
        varchar editedBy "Last editor"
        datetime editedDate "Last edit time"
        enum deleted "0 | 1"
    }

    zt_ai_knowledgelib ||--o{ zt_ai_knowledgelib : "parent self-ref hierarchy"
    zt_ai_knowledgelib ||--o{ zt_ai_knowledgeitem : "lib has many items"

Key Design Decisions / 关键设计决策

| Decision / 决策 | Rationale / 理由 | |-----------------|-----------------| | Adjacency List (parent + path) | 查询灵活,path 字段支持快速祖先查询,避免递归 | | attrs JSON column | 可扩展的元数据存储(tags, status, contentType),无需 ALTER TABLE | | Soft delete (deleted field) | 数据安全,支持误删恢复 | | Sub-library hierarchy | 对应禅道 UI 树形结构,一个"目录"就是一个子知识库 |


Client Architecture / 客户端架构

classDiagram
    class IKBClient {
        <<interface>>
        +listProjects() ApiResult~ProjectData[]~
        +createProject(data) ApiResult~ProjectData~
        +checkProjectExists() ProjectExistence
        +getProject() ApiResult~ProjectData~
        +getNodeTree() ApiResult~KBNode[]~
        +getTags() ApiResult~TagData[]~
        +getStats() ApiResult~StatsData~
        +getIncomplete() ApiResult~IncompleteResult~
        +getNodeByPath(path) ApiResult~KBNode~
        +searchNodes(query, options) ApiResult~SearchResult~
        +createNode(data) ApiResult
        +updateNode(path, data) ApiResult
        +deleteNode(path) ApiResult
        +batchCreateNodes(nodes) ApiResult~BatchResult~
        +exportProject() ApiResult
        +vectorSearch(options) ApiResult~VectorSearchResult~
        +publishProject() ApiResult~PublishResult~
        +unpublishProject() ApiResult~PublishResult~
        +close() void
    }

    class HybridClient {
        -config ZentaoConfig
        -token string
        -user UserInfo
        -db Pool
        +initialize() void
        -login() void
        -connectDatabase() void
        -ensureSubLibPath(rootLibID, segments) number
        -buildAttrs(data) string
        -parseAttrs(raw) object
    }

    class ApiClient {
        -baseUrl string
        -token string
        -libID number
        +login() string
        -ensureToken() void
        -request(method, path, body) Response
        -ensureSubLibPath(rootLibID, segments) number
    }

    class DbClient {
        -pool Pool
        -projectName string
        -query(sql, params) ApiResult
        -ensureSubLibPath(rootLibID, segments) number
    }

    class ZentaoError {
        +message string
        +code string
    }
    class AuthenticationError
    class DatabaseError
    class NotFoundError
    class ConfigError

    IKBClient <|.. HybridClient : implements
    IKBClient <|.. ApiClient : implements
    IKBClient <|.. DbClient : implements
    ZentaoError <|-- AuthenticationError
    ZentaoError <|-- DatabaseError
    ZentaoError <|-- NotFoundError
    ZentaoError <|-- ConfigError

Client Comparison / 客户端模式对比

| Feature | HybridClient | ApiClient | DbClient | |---------|:------------:|:---------:|:--------:| | Auth / 认证 | API login | API login | None | | Data Access / 数据访问 | MySQL direct | REST API | MySQL direct | | ACL Check / 权限检查 | Yes | Yes | No | | Performance / 性能 | High | Medium | High | | Vector Search / 向量搜索 | API + fallback | API only | Keyword only | | Recommended / 推荐 | Production | No DB access | Dev/Test only |


Prerequisites / 前置要求

  • Node.js 18+
  • 禅道专业版/企业版(带 AI 知识库功能)
  • 禅道服务可访问(本地或远程)

Installation / 安装

npm install -g @zzp123/zentao-kb-mcp

Quick Start / 快速开始

# 1. Install / 安装
npm install -g @zzp123/zentao-kb-mcp

# 2. Configure / 配置(在工作目录创建 .zentaoKB)
cat > .zentaoKB << 'EOF'
{
  "apiUrl": "http://127.0.0.1:7137/zentao/api.php/v1/aikb",
  "projectName": "my-kb",
  "account": "admin",
  "password": "your_password",
  "dbHost": "127.0.0.1",
  "dbPort": 3307,
  "dbUser": "root",
  "dbPassword": "123456",
  "dbName": "zentao"
}
EOF

# 3. Run / 运行
zentao-kb-mcp

Configuration / 配置

Configuration Flow / 配置加载流程

flowchart TD
    Start(["Server Start / 服务启动"])
    ReadFile["Read .zentaoKB file<br/>读取配置文件"]
    FileExists{".zentaoKB<br/>exists?"}
    ParseJSON["Parse JSON"]
    ReadEnv["Read ENV variables<br/>读取环境变量"]
    HasProject{"projectName<br/>exists?"}
    ThrowErr["Throw ConfigError"]

    CheckAuth{"hasApiAuth?<br/>apiUrl + token/password"}
    CheckDB{"hasDbConfig?<br/>dbHost/dbUser/dbName"}
    CheckDB2{"hasDbConfig?"}

    Hybrid["Hybrid Mode / 混合模式<br/>useHybrid = true"]
    APIMode["API Mode / API 模式<br/>useDatabase = false"]
    DBMode["DB Mode / 数据库模式<br/>useDatabase = true"]
    NoConn["Throw ConfigError<br/>No connection info"]

    CreateClient["createClient(config)"]
    Ready(["MCP Server Ready"])

    Start --> ReadFile --> FileExists
    FileExists -- Yes --> ParseJSON --> HasProject
    FileExists -- No --> ReadEnv --> HasProject
    HasProject -- No --> ThrowErr
    HasProject -- Yes --> CheckAuth
    CheckAuth -- Yes --> CheckDB
    CheckAuth -- No --> CheckDB2
    CheckDB -- Yes --> Hybrid
    CheckDB -- No --> APIMode
    CheckDB2 -- Yes --> DBMode
    CheckDB2 -- No --> NoConn

    Hybrid --> CreateClient --> Ready
    APIMode --> CreateClient
    DBMode --> CreateClient

    style Hybrid fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
    style APIMode fill:#e3f2fd,stroke:#1565c0
    style DBMode fill:#fff9c4,stroke:#f9a825
    style ThrowErr fill:#ffcdd2,stroke:#c62828
    style NoConn fill:#ffcdd2,stroke:#c62828

Config File / 配置文件(.zentaoKB

在项目根目录或工作目录创建 .zentaoKB 文件:

1. Hybrid Mode / 混合模式(推荐)

API 认证 + 数据库访问,兼顾安全性与高性能。

{
  "apiUrl": "http://127.0.0.1:7137/zentao/api.php/v1/aikb",
  "projectName": "我的知识库",
  "account": "admin",
  "password": "your_password",
  "dbHost": "127.0.0.1",
  "dbPort": 3307,
  "dbUser": "root",
  "dbPassword": "123456",
  "dbName": "zentao"
}

2. API Mode / 纯 API 模式

仅使用禅道 API,无需数据库配置。适用于无法直接访问数据库的场景。

{
  "apiUrl": "http://127.0.0.1:7137/zentao/api.php/v1/aikb",
  "projectName": "我的知识库",
  "account": "admin",
  "password": "your_password"
}

3. DB Mode / 纯数据库模式

直接访问数据库,无需 API 配置。仅建议在本地开发或测试环境使用(跳过权限检查)。

{
  "projectName": "我的知识库",
  "dbHost": "127.0.0.1",
  "dbPort": 3307,
  "dbUser": "root",
  "dbPassword": "123456",
  "dbName": "zentao"
}

Token Auth / 使用 Token(避免明文密码)

{
  "apiUrl": "http://127.0.0.1:7137/zentao/api.php/v1/aikb",
  "projectName": "我的知识库",
  "token": "your_token_here",
  "dbHost": "127.0.0.1",
  "dbPort": 3307
}

获取 Token:

curl -X POST http://127.0.0.1:7137/zentao/api.php/v1/tokens \
  -H "Content-Type: application/json" \
  -d '{"account":"admin","password":"your_password"}'

Auth Mode Comparison / 认证模式对比

| Mode / 模式 | Security / 安全性 | Performance / 性能 | Use Case / 适用场景 | |------|--------|------|----------| | Hybrid | High | High | Production(推荐) | | API | High | Medium | 无数据库访问时 | | DB | Low | High | 本地开发/测试 |

Environment Variables / 环境变量配置

# API
export ZENTAO_API_URL="http://127.0.0.1:7137/zentao/api.php/v1/aikb"
export ZENTAO_PROJECT="我的知识库"
export ZENTAO_ACCOUNT="admin"
export ZENTAO_PASSWORD="your_password"

# Or Token
export ZENTAO_TOKEN="your_token"

# Database (Hybrid / DB mode)
export ZENTAO_DB_HOST="127.0.0.1"
export ZENTAO_DB_PORT="3307"
export ZENTAO_DB_USER="root"
export ZENTAO_DB_PASSWORD="123456"
export ZENTAO_DB_NAME="zentao"

Claude Integration / Claude 集成

Claude Desktop

编辑 Claude Desktop 配置文件:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "zentao-kb": {
      "command": "zentao-kb-mcp",
      "env": {
        "ZENTAO_PROJECT": "my-kb",
        "ZENTAO_API_URL": "http://localhost:7137/zentao/api.php/v1/aikb",
        "ZENTAO_ACCOUNT": "admin",
        "ZENTAO_PASSWORD": "password",
        "ZENTAO_DB_HOST": "127.0.0.1",
        "ZENTAO_DB_PORT": "3307",
        "ZENTAO_DB_USER": "root",
        "ZENTAO_DB_PASSWORD": "123456",
        "ZENTAO_DB_NAME": "zentao"
      }
    }
  }
}

Claude Code

方式一:使用 claude mcp add 命令:

claude mcp add zentao-kb zentao-kb-mcp

方式二:在项目根目录放置 .zentaoKB 配置文件,然后在该目录启动 Claude Code:

claude

MCP Tools / MCP 工具 (17)

Project Management / 项目管理

| Tool / 工具 | Description / 说明 | |------|------| | kb_list_projects | List all KB projects / 列出所有知识库项目 | | kb_create_project | Create a new KB project / 创建新项目(名称、描述、图标) | | kb_publish_project | Publish the project / 发布项目 | | kb_unpublish_project | Unpublish the project / 取消发布 |

Structure & Stats / 结构与统计

| Tool / 工具 | Description / 说明 | |------|------| | kb_get_schema | Get content schema / 获取内容结构说明(intro/logic/dataFormat/experience) | | kb_get_tree | Get tree structure / 获取树形结构 | | kb_get_tags | Get all tags / 获取所有标签 | | kb_get_stats | Get statistics / 获取统计信息 | | kb_get_incomplete | List incomplete nodes / 获取待完善节点列表 |

Node Operations / 节点操作

| Tool / 工具 | Description / 说明 | |------|------| | kb_read_node | Read node by path / 读取指定路径的节点 | | kb_search_nodes | Search nodes / 搜索节点(关键词、类型、标签、状态) | | kb_vector_search | Semantic search / 语义向量搜索(回退关键词) | | kb_create_node | Create node / 创建节点(自动创建层级子库) | | kb_update_node | Update node / 更新节点 | | kb_delete_node | Delete node / 删除节点 | | kb_batch_create | Batch create / 批量创建节点 |

Export / 导出

| Tool / 工具 | Description / 说明 | |------|------| | kb_export | Export entire project / 导出整个项目 |


How It Works / 工作原理

以下时序图展示了 kb_create_node 的完整调用链,这是最能体现系统设计的核心流程:

sequenceDiagram
    participant C as MCP Client<br/>(Claude)
    participant S as MCP Server<br/>(index.ts)
    participant H as HybridClient
    participant DB as MySQL

    C->>S: CallTool: kb_create_node<br/>{path, title, content, tags}

    Note over S: switch(name)<br/>case 'kb_create_node'

    S->>H: ensureProjectExists()
    H->>DB: SELECT FROM zt_ai_knowledgelib<br/>WHERE name = projectName
    DB-->>H: rootLibID
    H-->>S: exists: true

    S->>H: createNode(data)

    Note over H: Parse path<br/>"A/B/doc" to dirSegments=["A","B"]

    H->>H: ensureSubLibPath(rootLibID, ["A","B"])

    loop For each segment
        H->>DB: SELECT id FROM zt_ai_knowledgelib<br/>WHERE parent=? AND name=?
        alt Exists
            DB-->>H: existing lib ID
        else Not found
            H->>DB: INSERT INTO zt_ai_knowledgelib<br/>(name, parent, grade, path, ...)
            DB-->>H: new lib ID
            H->>DB: UPDATE path = parentPath + newID
        end
    end

    H-->>H: targetLibID

    Note over H: contentToMarkdown(content)<br/>buildAttrs({tags, status})

    H->>DB: INSERT INTO zt_ai_knowledgeitem<br/>(lib=targetLibID, title, content, attrs)
    DB-->>H: insertId

    H-->>S: {success, data: {id, path, title}}
    S-->>C: "Node created successfully"

Hierarchical Storage / 层级存储机制

当创建一个路径为 "数据格式/委员会会议/调查附件格式" 的知识项时,系统会自动将路径解析为层级子知识库结构:

flowchart TD
    Input(["path = 'Data/Meetings/AttachFormat'<br/>title = 'AttachFormat'"])
    Split["Split by '/'<br/>segments = ['Data', 'Meetings', 'AttachFormat']"]
    Extract["dirSegments = ['Data', 'Meetings']<br/>leafTitle = 'AttachFormat'"]
    Init["parentID = rootLibID"]
    HasMore{"More<br/>segments?"}
    Next["segment = next item"]

    Query["SELECT id FROM zt_ai_knowledgelib<br/>WHERE parent=parentID AND name=segment"]
    Exists{"Exists?"}
    Use["parentID = existing.id"]
    GetParent["Get parent's path, grade, type, acl"]
    Insert["INSERT INTO zt_ai_knowledgelib<br/>(name, parent, grade+1, type, acl)"]
    UpdatePath["UPDATE path = parentPath + newID + ','"]
    SetParent["parentID = newLibID"]

    Return["targetLibID = parentID"]
    InsertItem["INSERT INTO zt_ai_knowledgeitem<br/>(lib=targetLibID, title=leafTitle)"]
    Done(["Node Created"])

    Input --> Split --> Extract --> Init --> HasMore
    HasMore -- Yes --> Next --> Query --> Exists
    Exists -- Yes --> Use --> HasMore
    Exists -- No --> GetParent --> Insert --> UpdatePath --> SetParent --> HasMore
    HasMore -- No --> Return --> InsertItem --> Done

    style Input fill:#e1f5fe,stroke:#0288d1
    style Done fill:#c8e6c9,stroke:#2e7d32
    style Insert fill:#fff3e0,stroke:#f57c00
    style InsertItem fill:#fff3e0,stroke:#f57c00

Database State Example / 数据库状态示例

以路径 "Backend/API设计/用户接口" 为例:

Step 1: Create sub-lib "Backend" (id=2, parent=1, grade=2, path=",1,2,")
Step 2: Create sub-lib "API设计" (id=3, parent=2, grade=3, path=",1,2,3,")
Step 3: Insert item into lib=3, title="用户接口"
zt_ai_knowledgelib:
┌────┬──────────┬────────┬───────┬────────────┐
│ id │   name   │ parent │ grade │    path    │
├────┼──────────┼────────┼───────┼────────────┤
│  1 │ 知识库   │      0 │     1 │ ,1,        │
│  2 │ Backend  │      1 │     2 │ ,1,2,      │
│  3 │ API设计  │      2 │     3 │ ,1,2,3,    │
└────┴──────────┴────────┴───────┴────────────┘

zt_ai_knowledgeitem:
┌────┬─────┬──────────┬─────────────────────────┐
│ id │ lib │  title   │         attrs           │
├────┼─────┼──────────┼─────────────────────────┤
│  1 │   3 │ 用户接口 │ {"status":"complete",...}│
└────┴─────┴──────────┴─────────────────────────┘

Node Lifecycle / 节点生命周期

stateDiagram-v2
    [*] --> Incomplete : kb_create_node<br/>(default status)

    Incomplete --> Incomplete : kb_update_node<br/>(edit content or tags)
    Incomplete --> Complete : kb_update_node<br/>(status: complete)
    Complete --> Incomplete : kb_update_node<br/>(status: incomplete)
    Complete --> Complete : kb_update_node<br/>(edit content or tags)

    Incomplete --> SoftDeleted : kb_delete_node
    Complete --> SoftDeleted : kb_delete_node

    state SoftDeleted {
        [*] --> Deleted
        Deleted : Record remains in DB
        Deleted : deleted = '1'
        Deleted : Hidden from all queries
    }

    note right of Incomplete
        Visible via kb_get_incomplete
    end note

    note right of Complete
        Full content available
    end note

Content Types / 内容类型

每个文档节点可设置以下内容类型:

| Type / 类型 | Name / 中文名 | Description / 说明 | |------|--------|------| | intro | 概述 | 模块或功能的总体介绍 | | logic | 逻辑 | 业务逻辑、流程说明 | | dataFormat | 数据格式 | 数据结构、接口格式定义 | | experience | 经验 | 开发经验、最佳实践、注意事项 |


Usage Examples / 使用示例

查看知识库结构

使用 kb_get_tree 工具查看当前知识库的目录结构

创建文档节点

使用 kb_create_node 创建文档:
- path: "Backend/API设计/用户接口"
- title: "用户接口文档"
- nodeType: "document"
- contentType: "logic"
- tags: ["api", "user"]
- content: {"summary": "用户相关接口说明"}

搜索节点

使用 kb_search_nodes 搜索:
- query: "用户"
- contentType: "logic"
- tag: "api"

批量创建节点

使用 kb_batch_create 批量创建:
- nodes: [
    { path: "Backend/数据库", title: "数据库设计", nodeType: "directory" },
    { path: "Backend/数据库/用户表", title: "用户表结构", nodeType: "document", contentType: "dataFormat" }
  ]

Content Examples / 内容写入示例

Logic / 逻辑 (logic):

{
  "path": "Backend/用户认证模块",
  "title": "用户认证模块",
  "contentType": "logic",
  "status": "complete",
  "tags": ["认证", "JWT", "后端"],
  "content": {
    "purpose": "处理用户登录、注册、Token刷新",
    "flow": "1. 用户提交凭证 → 2. 验证 → 3. 签发JWT → 4. 返回Token",
    "dependencies": ["jsonwebtoken", "bcrypt"],
    "keyFiles": ["src/auth/controller.ts", "src/auth/middleware.ts"]
  }
}

Experience / 经验 (experience):

{
  "path": "经验记录/MySQL连接池超时问题",
  "title": "MySQL连接池超时问题",
  "contentType": "experience",
  "status": "complete",
  "tags": ["MySQL", "连接池", "踩坑"],
  "content": {
    "problem": "长时间空闲后数据库查询报 ECONNRESET",
    "solution": "启用 enableKeepAlive + keepAliveInitialDelay",
    "lessons": ["连接池需要配置心跳", "不要用单连接"]
  }
}

Data Format / 数据格式 (dataFormat):

{
  "path": "数据格式/API响应格式",
  "title": "API响应格式",
  "contentType": "dataFormat",
  "status": "complete",
  "tags": ["API", "接口规范"],
  "content": {
    "format": "ApiResult<T>",
    "fields": {
      "success": "boolean - 操作是否成功",
      "data": "T - 成功时的数据",
      "error": "string - 错误码"
    }
  }
}

Claude Code Skill Workflow / 开发工作流

本项目提供了一套 Claude Code Skill(开发工作流 Hook),可在 Claude Code 中实现知识库驱动的全周期智能开发。

Core Philosophy / 核心理念

你不仅仅是一个代码生成器,更是一位严格的代码审查员和知识库维护者。

  • 文档代码双重验证 — 任何修改必须同时基于知识库(理论)和现有代码(实际)
  • 扼杀错误于摇篮 — 输出代码前进行逻辑沙盘推演
  • 零容忍版本冲突 — 彻底移除旧版本代码,禁止注释保留
  • 知识库同步铁律 — 代码变了,文档必须变

5-Step Workflow / 5 步工作流

① Analyze ──► ② Plan ──► ③ Execute ──► ④ Verify ──► ⑤ Sync
    │             │            │              │            │
 Scan code+docs  Design     Code+Review    User test    Update KB
 Clarify tasks   🛑 Wait    Clean debt     Fix bugs     Archive

KB Tool Quick Reference / 知识库工具速查

Analysis Phase / 分析阶段:

| Tool / 工具 | Purpose / 用途 | |------|------| | kb_get_tree | 获取知识库树形结构全貌 | | kb_search_nodes | 搜索相关文档 | | kb_read_node | 读取指定节点内容 | | kb_get_stats | 统计信息 | | kb_get_schema | 查看内容结构说明 | | kb_get_incomplete | 查看待完善节点 |

Write Phase / 写入阶段:

| Tool / 工具 | Purpose / 用途 | |------|------| | kb_create_node | 创建新节点 | | kb_update_node | 更新节点 | | kb_batch_create | 批量创建 | | kb_delete_node | 删除过时节点 |

Management Phase / 管理阶段:

| Tool / 工具 | Purpose / 用途 | |------|------| | kb_list_projects | 列出项目 | | kb_create_project | 创建新项目 | | kb_export | 导出项目备份 |

Install Hook & Commands / 安装 Hook 与 Commands

npm 包内附带了 resources/.claude/ 目录,包含:

| File / 文件 | Type / 类型 | Trigger / 触发 | Description / 说明 | |------|------|----------|------| | hooks/SystemPrompt.md | Hook | 每次对话自动加载 | 5 步开发工作流、知识库同步铁律 | | commands/review.md | Command | /review | 全维度代码审查 | | commands/sync.md | Command | /sync | 代码到知识库同步 |

安装步骤:

# From global install / 全局安装后
cp -r $(npm root -g)/@zzp123/zentao-kb-mcp/resources/.claude/ .claude/

# From local install / 项目本地安装后
cp -r node_modules/@zzp123/zentao-kb-mcp/resources/.claude/ .claude/

安装后项目目录结构:

your-project/
├── .claude/
│   ├── hooks/
│   │   └── SystemPrompt.md    # Auto-load → Workflow
│   └── commands/
│       ├── review.md          # /review → Code review
│       └── sync.md            # /sync → KB sync
├── .zentaoKB                  # KB config
└── ...

REST API Reference / API 路由参考

PHP 后端提供以下 REST API 端点:

Knowledge Libraries / 知识库

| Method | Endpoint | Description / 说明 | |--------|----------|------| | GET | /aikb/libs | List all libraries (with parent/grade) / 列出所有知识库 | | POST | /aikb/libs | Create library (supports parent for sub-lib) / 创建知识库/子库 | | GET | /aikb/libs/:libID | Get library details / 获取知识库详情 | | PUT | /aikb/libs/:libID | Update library / 更新知识库 | | DELETE | /aikb/libs/:libID | Soft delete library / 删除知识库 |

Knowledge Items / 知识项

| Method | Endpoint | Description / 说明 | |--------|----------|------| | GET | /aikb/libs/:libID/items | List items in library / 列出知识项 | | POST | /aikb/libs/:libID/items | Create item / 创建知识项 | | GET | /aikb/libs/:libID/items/:itemID | Get item details / 获取知识项详情 | | PUT | /aikb/libs/:libID/items/:itemID | Update item / 更新知识项 | | DELETE | /aikb/libs/:libID/items/:itemID | Soft delete item / 删除知识项 |

Advanced Operations / 高级操作

| Method | Endpoint | Description / 说明 | |--------|----------|------| | POST | /aikb/libs/:libID/items/batch | Batch create items / 批量创建 | | GET | /aikb/libs/:libID/items/search?q= | Search items / 搜索知识项 | | GET | /aikb/libs/:libID/stats | Get library stats / 获取统计信息 |

Response Format / 响应格式

// Success
{ "success": true, "data": { /* ... */ } }

// Error
{ "success": false, "code": "ERROR_CODE", "message": "Description" }

Development / 开发

git clone <your-git-repo-url>
cd zentao-kb-mcp
npm install

npm run build          # TypeScript compile
npm run dev            # Dev mode (tsx hot reload)
npm test               # Run vitest tests
npm run typecheck      # Type check only

Project Structure / 项目结构

zentao-kb-mcp/
├── src/
│   ├── index.ts              # MCP server entry, tool dispatch
│   ├── config.ts             # Config loader (.zentaoKB + ENV)
│   ├── types.ts              # Shared TypeScript types
│   ├── errors.ts             # Custom error classes
│   ├── clients/
│   │   ├── base-client.ts    # IKBClient interface (19 methods)
│   │   ├── api-client.ts     # REST API client
│   │   ├── db-client.ts      # MySQL direct client
│   │   └── hybrid-client.ts  # API auth + DB ops client
│   ├── tools/
│   │   ├── definitions.ts    # MCP tool definitions
│   │   └── schemas.ts        # Content type schemas
│   ├── formatters/
│   │   └── index.ts          # Output formatters
│   └── __tests__/            # Unit tests (vitest)
├── resources/.claude/        # Claude Code Hook & Commands
├── dist/                     # Build output (JS + d.ts + sourcemap)
├── package.json
├── tsconfig.json
├── vitest.config.ts
├── .zentaoKB.example
└── README.md

Scripts / 可用脚本

| Script / 脚本 | Description / 说明 | |------|------| | npm run build | TypeScript 编译 | | npm run build:watch | 监听模式编译 | | npm run dev | tsx 开发模式运行 | | npm start | 运行编译后的服务 | | npm test | vitest 测试 | | npm run test:watch | 监听模式测试 | | npm run test:coverage | 测试覆盖率报告 | | npm run typecheck | TypeScript 类型检查 | | npm run lint | ESLint 检查 | | npm run lint:fix | ESLint 自动修复 | | npm run clean | 清理 dist 目录 |


Security / 安全建议

  • .zentaoKB 加入 .gitignore,避免提交敏感信息到版本控制
  • 生产环境建议使用 Token 代替明文密码
  • 为数据库访问创建专用用户,仅授予必要权限
  • 使用防火墙限制数据库访问 IP
  • 配置 HTTPS 避免密码明文传输
echo ".zentaoKB" >> .gitignore
chmod 600 .zentaoKB

Related Links / 相关链接

  • ZenTao Official / 禅道官方:https://www.zentao.net
  • MCP Protocol / MCP 协议:https://modelcontextprotocol.io

License / 许可证

MIT