内容
<p align="center">
<img src="./assets/logo.svg" alt="MochiKit Logo" width="120" />
</p>
<h1 align="center">🍡 MochiKit</h1>
<p align="center">
<em>现代化、插件驱动的TypeScript AI智能体框架。</em>
</p>
<p align="center">
<a href="./README_ZH.md">🇨🇳 中文文档</a>
</p>
<p align="center">
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License">
<img src="https://img.shields.io/badge/node-%3E%3D18-green.svg" alt="Node >=18">
<img src="https://img.shields.io/badge/typescript-strict-informational.svg" alt="TypeScript strict">
<img src="https://img.shields.io/badge/module-ESM-yellow.svg" alt="ESM">
<img src="https://img.shields.io/badge/core%20files-44-lightgrey.svg" alt="44 core files">
</p>
---
> 🧠 **核心哲学:** 复杂性在于框架,而不在于模型。每个机制都依赖于相同的 `LLM → tool_use → results → repeat` 循环。
---
## 为什么选择MochiKit?
MochiKit是一个**极其简洁**的Node.js AI智能体框架。相比主流的替代方案,它的核心文件数量极少,入门门槛非常低。源代码附带**全面的英文注释**,使其成为学习AI智能体架构的绝佳入门项目。
| | MochiKit | LangChain | CrewAI | AutoGen |
|---|---|---|---|---|
| **核心文件** | **44** | 300+ | 200+ | 250+ |
| **总源码行数** | **~9,600** | 100,000+ | 50,000+ | 80,000+ |
| **依赖项** | **3** | 20+ | 15+ | 10+ |
| **学习曲线** | **1天** | 2周 | 1周 | 1周 |
| **TypeScript严格模式** | ✅ 零 `any` | ❌ | ❌ | ❌ |
| **代码注释** | ✅ 完整的JSDoc | ❌ | ❌ | 部分 |
---
## 功能特点
- **🤖 多智能体协作** — 管理者-工作者委托、顺序链、团队邮箱通信,带有协议状态机
- **🔌 插件架构** — 将工具 + 钩子 + 权限规则打包成可重用的插件;使用 `agent.use(plugin)` 安装
- **📋 技能加载** — 声明式SKILL.md文件;两级加载(系统目录、按需完整内容)
- **🧠 统一内存** — `Memory` 接口,带有Markdown文件存储(YAML frontmatter + 索引);自动注入;合并/整合
- **🪝 生命周期钩子** — `UserPromptSubmit`、`PreToolUse`、`PostToolUse`、`Stop` — 按优先级排序、异步、可阻塞或重写
- **🔐 权限管道** — 3级管道:拒绝 → 规则 → 请求 → 解析器;内置 `AllowAllResolver` / `DenyAllResolver`
- **📦 内置工具** — 文件I/O、bash(同步 + 后台)、网络搜索、网络阅读器、TodoWrite、内存、任务DAG、团队消息
- **🔌 MCP服务器兼容性** — 通过stdio或Streamable HTTP连接到MCP服务器;工具自动发现,命名为 `mcp__<server>__<tool>`
- **⚡ 后台任务** — 长运行bash命令异步运行;智能体继续工作
- **🛡️ 错误恢复** — 429/529的指数回退 + 抖动、`prompt_too_long`的反应式压缩、备用模型故障转移
- **🌐 多提供商** — 在单个 `.env` 中配置多个LLM提供商(GLM、OpenAI、Anthropic、DeepSeek…);通过 `loadConfig('provider')` 按智能体选择
- **📐 严格的TypeScript** — 零 `any`、完整类型安全、面向对象编程 + 依赖注入贯穿始终
- **🧪 完全测试** — 135个单元测试(模拟LLM)+ 18个集成测试(真实GLM)
---
## 安装
```bash
git clone https://github.com/MochiKit/MochiKit.git
cd MochiKit
npm install
cp .env.example .env # 编辑 .env 文件,添加您的API密钥
```
**.env** — MochiKit 使用与Anthropic兼容的协议。默认端点是GLM(Zhipu):
```env
BASE_URL=https://open.bigmodel.cn/api/anthropic
API_KEY=your-api-key-here
MODEL=glm-4.7
MOCHIKIT_WEB_API_KEY=your-api-key-here
MOCHIKIT_RUN_INTEGRATION=0
```
> 💡 任何与Anthropic兼容的端点都有效 — 只需更改 `BASE_URL` 和 `MODEL`。
### 多提供商配置
使用 `{NAME}_API_KEY` 命名约定配置多个LLM提供商:
```env
# 默认提供商(无前缀)
API_KEY=your-glm-key
BASE_URL=https://open.bigmodel.cn/api/anthropic
MODEL=glm-4.7
# 命名提供商
DEEPSEEK_API_KEY=sk-your-deepseek-key
DEEPSEEK_BASE_URL=https://api.deepseek.com/v1
DEEPSEEK_MODEL=deepseek-chat
OPENAI_API_KEY=sk-your-openai-key
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=gpt-4o
```
在加载配置时选择提供商:
```ts
import { loadConfig } from 'mochikit';
const glmCfg = loadConfig(); // 默认提供商
const deepCfg = loadConfig('deepseek'); // DeepSeek
const openaiCfg = loadConfig('openai'); // OpenAI
```
### MCP服务器集成
连接到模型上下文协议(MCP)服务器,并在您的智能体中直接使用它们的工具:
```ts
import { Agent, createMCPPlugin, AnthropicAdapter, loadConfig, PermissionManager, AllowAllResolver } from 'mochikit';
const cfg = loadConfig();
// 配置MCP服务器 — 工具自动发现
const mcp = createMCPPlugin({
servers: [
{
name: 'filesystem',
transport: {
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
},
permissionMode: 'auto-allow', // 信任此服务器的工具
},
],
});
const agent = new Agent({
name: 'mcp-demo',
llm: new AnthropicAdapter({ apiKey: cfg.apiKey, baseURL: cfg.baseUrl }),
model: cfg.model,
systemPrompt: '您可以通过MCP访问文件系统工具。',
permission: new PermissionManager({ resolver: new AllowAllResolver() }),
});
agent.use(mcp.plugin); // 安装MCP工具
await mcp.init(); // 等待连接(可选)
console.log(await agent.run('列出/tmp目录下的文件'));
```
工具命名为 `mcp__filesystem__read_file`、`mcp__filesystem__list_directory` 等 —
不会与内置工具冲突。支持 **stdio** (本地子进程)和
**Streamable HTTP** (远程服务器)传输。
---
## 快速入门
```ts
import {
Agent, AnthropicAdapter, loadConfig,
createBashTool, AllowAllResolver, PermissionManager,
} from 'mochikit';
const cfg = loadConfig();
const agent = new Agent({
name: 'demo',
llm: new AnthropicAdapter({ apiKey: cfg.apiKey, baseURL: cfg.baseUrl }),
model: cfg.model,
systemPrompt: '您是一个有帮助的助手。请简洁回答。',
tools: [createBashTool()],
permission: new PermissionManager({ resolver: new AllowAllResolver() }),
});
console.log(await agent.run('列出当前目录下的文件'));
```
运行它:
```bash
npx tsx your-file.ts
```
更多示例:
```bash
npx tsx docs/examples/01-simple-agent.ts # 单个智能体 + 文件/bash工具
npx tsx docs/examples/02-manager-worker.ts # 管理者-工作者协作
npx tsx docs/examples/03-sequential-chain.ts # 顺序链 + 共享内存
npx tsx docs/examples/04-memory-and-vector.ts # Markdown内存 + 向量存储
npx tsx docs/examples/05-custom-plugin.ts # 自定义插件:工具 + 钩子 + 规则
```
---
## 架构
智能体循环是框架的核心:
```
用户输入 → [用户提示提交钩子] → while (turns < maxTurns):
1. 上下文压缩(预算 → 微 → 剪辑)
2. 调用LLM并重试(429/529回退,prompt_too_long → 反应式压缩)
3. 如果end_turn → 返回文本
4. 如果tool_use → 对于每个工具:
[工具使用前钩子] → [权限检查] → 执行 → [工具使用后钩子]
→ 馈送结果 → 循环
```
**所有内容都通过构造函数注入** — 交换任何组件而不触摸循环。
有关详细流程,请参见 [架构指南 →](./docs/architecture.md)。
---
## 文档
| 语言 | 链接 | 描述 |
|---|---|---|
| 🇬🇧 英文 | [`docs/en/`](./docs/en/) | **完整开发者指南** — 19章 |
| 🇨🇳 中文 | [`docs/zh/`](./docs/zh/) | **完整开发者指南** — 19章,从Hello Agent到端到端项目 |
| 📐 架构 | [`docs/architecture.md`](./docs/architecture.md) | 带有Mermaid图表的架构设计文档 |
### 章节索引
| 章节 | 主题 |
|---|---|
| 01 | [安装和配置](./docs/en/01-installation-and-config.md) |
| 02 | [第一个智能体](./docs/en/02-first-agent.md) |
| 03 | [工具系统](./docs/en/03-tool-system.md) |
| 04 | [技能加载](./docs/en/04-skill-loading.md) |
| 05 | [内存系统](./docs/en/05-memory-system.md) |
| 06 | [向量存储](./docs/en/06-vector-store.md) |
| 07 | [管理者-工作者](./docs/en/07-manager-worker.md) |
| 08 | [顺序链](./docs/en/08-sequential-chain.md) |
| 09 | [团队消息](./docs/en/09-team-messaging.md) |
| 10 | [任务系统](./docs/en/10-task-system.md) |
| 11 | [钩子](./docs/en/11-hooks.md) |
| 12 | [权限](./docs/en/12-permission.md) |
| 13 | [压缩和恢复](./docs/en/13-compaction-and-recovery.md) |
| 14 | [插件系统](./docs/en/14-plugin-system.md) |
| 15 | [网络工具](./docs/en/15-web-tools.md) |
| 16 | [MCP集成](./docs/en/16-mcp-integration.md) |
| 17 | [配置和环境变量](./docs/en/17-config-and-env-vars.md) |
| 18 | [测试指南](./docs/en/18-testing-guide.md) |
| 19 | [完整示例](./docs/en/19-complete-example.md) |
---
## 项目结构
```
MochiKit/
├── src/
│ ├── core/ # 智能体循环、类型、LLM适配器、钩子、权限、压缩、恢复
│ ├── collaboration/ # 管理者-工作者、顺序链、团队、子智能体、协议
│ ├── memory/ # 内存接口、MarkdownMemory、向量存储、InMemoryVectorStore
│ ├── infra/ # 配置、消息总线、任务存储、技能注册、后台任务管理器
│ ├── tools/ # 内置工具:fs、bash、web、memory、task、team、todo_write、skill
│ ├── plugins/ # 插件接口、PluginBuilder、PluginRegistry
│ ├── mcp/ # MCP集成:传输、客户端、工具适配器、配置、插件
│ └── index.ts # 出口(公共API)
├── tests/
│ ├── unit/ # 22个测试文件(模拟LLM,快速,无网络)
│ ├── integration/ # 13个测试文件(真实GLM,环境保护)
│ └── helpers/ # MockLLMClient、测试fixtures
├── docs/
│ ├── en/ # 英文开发者文档(19章)
│ ├── zh/ # 中文开发者文档(19章)
│ ├── examples/ # 5个可运行的TypeScript示例
│ └── architecture.md # 架构设计文档
├── assets/ # Logo和视觉资产
└── skills/ # 捆绑的SKILL.md文件
```
---
## 运行测试
```bash
npm run typecheck # 严格的TypeScript类型检查(需要0个错误)
npm run test:unit # 单元测试(模拟LLM — 快速,无网络,无API密钥)
npm run test:integration # 集成测试(真实GLM — 需要.env + MOCHIKIT_RUN_INTEGRATION=1)
npm test # 所有测试
```
```bash
# 运行单个测试文件
npx vitest run tests/unit/hooks.test.ts
# 使用真实LLM运行
MOCHIKIT_RUN_INTEGRATION=1 npx vitest run tests/integration
```
---
## 贡献
MochiKit遵循严格的TypeScript和面向对象编程 + 依赖注入。每个组件都通过构造函数注入以提高可测试性。
1. Fork & clone
2. `npm install` + `cp .env.example .env`
3. 进行更改 — 保持 `tsc --noEmit` 清洁
4. 添加测试 — `npm run test:unit` 必须保持绿色
5. 打开PR
---
## License
MIT © 2024 MochiKit
---
<p align="center">
<sub>使用TypeScript · Anthropic SDK · GLM · Vitest构建 ❤️</sub>
</p>