迷你码
一个Python SDK,用于构建具有LLM、工具、技能和MCP支持的AI代理。
概述
迷你码 是一个干净、可扩展的框架,用于在Python中构建AI代理。Minicode为以下内容提供了一个简单而强大的抽象层:
- LLM集成 -通过通用接口支持任何LLM提供者
- 工具系统 -具有JSON模式验证的可扩展工具框架
- MCP支持 -连接到模型上下文协议服务器以获得更多功能
- 技能 -从技能目录加载和使用技能
- 异步优先 -内置async/await以实现高效的I/O操作
- 类型安全 -完整的类型注释,以获得更好的IDE支持
安装
pip install minicode-sdk快速开始
提示: 最简单的入门方法是使用内置技能.minicode/skills/。只需让您的AI编码助手(如Claude Code)调用minicode_usage或minicode_contributing帮助您使用minicodesdk进行开发的技能。
克劳德代码20行
一个生产就绪的编码助手,具有文件操作、shell执行、web访问、子代理等功能,所有这些都只需要20行代码。
查看完整示例: 示例/claude_code_in20_lines.py
import asyncio, os
from minicode import Agent
from minicode.llm import OpenRouterLLM
from minicode.tools.builtin import *
async def main():
llm = OpenRouterLLM(api_key=os.getenv("OPENROUTER_API_KEY"), model="anthropic/claude-sonnet-4")
tools = [ReadTool(), WriteTool(), EditTool(), GlobTool(), GrepTool(), BashTool(),
WebFetchTool(), WebSearchTool(), TaskTool(), ThinkTool(), SkillTool(), AskUserQuestionTool()]
agent = Agent("ClaudeCode", llm, "You are a helpful coding assistant.", tools)
while True:
if msg := input("\n> User: ").strip():
print(f"\n> Agent:")
async for chunk in agent.stream(msg):
chunk_type = chunk.get("type")
if chunk_type == "content":
print(chunk.get("content", ""), end="", flush=True)
elif chunk_type == "tool_call":
func = chunk.get("tool_call", {}).get("function", {})
print(f"\n[TOOL] {func.get('name')} | args: {func.get('arguments')}")
elif chunk_type == "tool_result":
print(f"[RESULT] {chunk.get('tool_name')}: {chunk.get('result')}")
print()
asyncio.run(main())# Setup
export OPENROUTER_API_KEY=your_key
python examples/claude_code_in_20_lines.py核心概念
1.代理人
这 Agent 类是微代码的核心。它结合了LLM、工具和会话管理:
from minicode import Agent
agent = Agent(
name="my-agent",
llm=my_llm,
tools=[tool1, tool2],
prompt="System prompt for the agent",
temperature=0.7,
top_p=1.0,
mode="primary", # or "subagent" or "all"
)关键方法:
stream(message)-流式传输来自代理的响应generate(message)-获得完整的响应(非流媒体)add_tool(tool)-向代理添加工具reset_session()-清除对话历史记录
2.法学硕士论文摘要
minicode为LLM提供者提供了一个干净的抽象:
from minicode.llm import BaseLLM
class MyCustomLLM(BaseLLM):
async def stream(self, messages, tools=None, **kwargs):
# Implement streaming logic
yield {"type": "content", "content": "Hello"}
yield {"type": "done", "finish_reason": "stop"}
async def generate(self, messages, **kwargs):
# Implement non-streaming logic
return {"content": "Hello", "finish_reason": "stop"}内置实现:
OpenAILLM-OpenAI API集成(GPT-4、GPT-3.5等)
3.工具系统
工具允许代理与环境交互:
from minicode import BaseTool, ToolContext
from typing import Dict, Any
class MyTool(BaseTool):
@property
def name(self) -> str:
return "my_tool"
@property
def description(self) -> str:
return "What this tool does"
@property
def parameters_schema(self) -> Dict[str, Any]:
return {
"type": "object",
"properties": {
"input": {"type": "string", "description": "Input text"}
},
"required": ["input"]
}
async def execute(self, params: Dict[str, Any], context: ToolContext) -> Dict[str, Any]:
return {
"success": True,
"data": f"Processed: {params['input']}"
}内置工具:
AskUserQuestionTool-通过超时支持向用户提问并等待答案BashTool-执行具有超时支持和后台执行的bash命令BashOutputTool-监控后台bash进程的输出KillShellTool-终止后台bash进程ReadTool-读取文件内容(文本、图像、PDF、Jupyter笔记本)WriteTool-将内容写入文件EditTool-文件中的精确字符串替换GlobTool-文件模式匹配(例如。,**/*.py)GrepTool-使用正则表达式进行代码搜索(ripgrep+Python回退)WebFetchTool-通过HTML到Markdown/文本转换获取web内容WebSearchTool-具有可配置后端的网络搜索(Exa、DuckDuckGo)NotebookEditTool-编辑Jupyter笔记本单元格(替换/插入/删除)TodoWriteTool-创建和管理结构化任务列表以跟踪进度TaskTool-启动子代理以处理孤立会话中的复杂任务TaskOutputTool-子代理使用此功能提前返回结果SkillTool-从技能目录加载和执行技能ThinkTool-记录代理人对透明度的推理和思考过程
Web工具用法:
from minicode.tools.builtin import WebFetchTool, WebSearchTool
# Fetch web content
webfetch = WebFetchTool()
result = await webfetch.execute(
{"url": "https://example.com", "format": "markdown"},
context
)
# Search the web
websearch = WebSearchTool(default_backend="exa")
result = await websearch.execute(
{
"query": "Python tutorials",
"num_results": 10,
"type": "deep", # Exa-specific: auto, fast, or deep
"livecrawl": "preferred" # Exa-specific: fallback or preferred
},
context
)WebFetch功能:
- 支持多种输出格式:
text,markdown,html - 使用html2text自动将HTML转换为Markdown
- 纯文本提取,删除脚本/样式
- 可配置超时(默认30秒,最大120秒)
- 响应大小限制为5MB
网站搜索功能:
- 可配置后端:
exa(默认),duckduckgo(需要duckduckgo搜索包) - Exa后端支持高级选项:搜索类型(自动/快速/深度),实时抓取模式
- 可定制的结果数量
- Exa的LLM优化上下文
笔记本工具用法:
from minicode.tools.builtin import NotebookEditTool
# Replace a cell's content
notebook_tool = NotebookEditTool()
result = await notebook_tool.execute(
{
"notebook_path": "/path/to/notebook.ipynb",
"cell_id": "abc123",
"new_source": "print('Hello, World!')"
},
context
)
# Insert a new cell
result = await notebook_tool.execute(
{
"notebook_path": "/path/to/notebook.ipynb",
"edit_mode": "insert",
"cell_id": "abc123", # Insert after this cell
"cell_type": "code",
"new_source": "x = 42"
},
context
)
# Delete a cell
result = await notebook_tool.execute(
{
"notebook_path": "/path/to/notebook.ipynb",
"edit_mode": "delete",
"cell_id": "abc123",
"new_source": "" # Required but not used
},
context
)笔记本编辑功能:
- 用单元格ID替换单元格内容
- 在任何位置插入新单元格(代码或标记)
- 按ID删除单元格
- 更改单元格类型(代码↔ 降价)
- 编辑代码单元格时自动清除输出
- 保留笔记本元数据和结构
TodoWrite用法:
from minicode.tools.builtin import TodoWriteTool
# Create and manage task lists
todo_tool = TodoWriteTool()
result = await todo_tool.execute(
{
"todos": [
{
"content": "Implement feature X",
"activeForm": "Implementing feature X",
"status": "pending"
},
{
"content": "Write tests",
"activeForm": "Writing tests",
"status": "in_progress"
},
{
"content": "Update documentation",
"activeForm": "Updating documentation",
"status": "completed"
}
]
},
context
)TodoWrite功能:
- 跟踪多个任务的状态(待定/正在进行/已完成)
- 每个任务都有
content(命令式)和activeForm(当前连续) - 提供对代理进度的可见性
- 如果有多个任务正在进行中,则发出警告
- 存在待处理任务时,如果没有任务正在进行中,则发出警告
- 帮助组织复杂的多步骤任务
后台处理工具使用:
from minicode.tools.builtin import BashTool, BashOutputTool, KillShellTool
# Start a background process
bash_tool = BashTool()
result = await bash_tool.execute(
{
"command": "python long_running_script.py",
"run_in_background": True
},
context
)
bash_id = result["bash_id"]
# Monitor output from background process
output_tool = BashOutputTool()
output = await output_tool.execute(
{
"bash_id": bash_id,
"filter": "ERROR|WARNING" # Optional regex filter
},
context
)
print(output["output"]) # Only new output since last check
# Kill background process
kill_tool = KillShellTool()
result = await kill_tool.execute(
{"shell_id": bash_id},
context
)后台流程特点:
- 运行长时间运行的命令而不阻塞
- 使用BashOutput增量监控输出
- 使用正则表达式模式过滤输出
- 需要时终止进程
- 每个后台进程都有一个唯一的ID
- 输出缓冲区自动管理
AskUserQuestion用法:
from minicode.tools.builtin import AskUserQuestionTool
# Define callback to handle questions (for UI/web integration)
async def question_handler(question: str) -> str:
# Get answer from your UI/web interface
return user_interface.get_input(question)
# Create tool with callback
ask_tool = AskUserQuestionTool(
question_callback=question_handler,
default_timeout=None # No timeout by default
)
# Agent can ask questions during execution
result = await ask_tool.execute(
{
"question": "Which API version should I use?",
"default_answer": "v2", # Optional default
"timeout": 30 # Optional timeout in seconds
},
context
)
print(result["answer"]) # User's answer
# CLI mode (no callback - uses stdin)
cli_tool = AskUserQuestionTool() # Will use input() in thread pool
result = await cli_tool.execute(
{"question": "Continue with installation?"},
context
)AskUserQuestion功能:
- 支持基于回调和基于CLI的交互
- 多轮对话-提出后续问题
- 默认答案的可选超时
- 当用户没有响应时通知代理(超时无默认值)
- 非阻塞异步执行(即使是stdin)
- 与任何UI框架灵活集成
4.MCP集成
minicode支持 模型上下文协议(MCP) 用于连接到外部工具服务器。配置格式与Claude Code兼容。
方法1:使用MCP服务器的代理(推荐)
使用MCP的最简单方法是通过Agent的内置支持:
import asyncio
from minicode import Agent
from minicode.llm import OpenAILLM
async def main():
# Configure MCP servers
mcp_servers = [
{
"name": "memory",
"command": ["npx", "-y", "@modelcontextprotocol/server-memory"],
},
{
"name": "filesystem",
"command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
},
]
# Use async context manager for automatic setup/cleanup
async with Agent(
name="assistant",
llm=OpenAILLM(api_key="your-key"),
mcp_servers=mcp_servers,
) as agent:
# MCP tools are automatically discovered and registered
async for chunk in agent.stream("Store this note: Hello World"):
if chunk.get("type") == "content":
print(chunk.get("content", ""), end="")
asyncio.run(main())方法2:配置文件
创建 .minicode/mcp.json 项目目录中的文件或 ~/.minicode/mcp.json 对于用户级配置:
{
"mcpServers": {
"memory": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"],
"env": {
"NODE_ENV": "production"
}
},
"api-server": {
"type": "http",
"url": "http://localhost:8080/mcp",
"headers": {
"Authorization": "Bearer your-token"
}
}
}
}代理自动从配置文件加载MCP服务器:
async with Agent(
name="assistant",
llm=OpenAILLM(api_key="your-key"),
# use_global_mcp=True is the default
) as agent:
# MCP servers from .minicode/mcp.json are automatically loaded
pass配置文件位置(按优先级顺序):
MINICODE_CONFIG环境变量.minicode/mcp.json在当前目录中(项目级别)~/.minicode/mcp.json(用户级配置)
要禁用自动配置加载,请执行以下操作:
agent = Agent(
name="assistant",
llm=my_llm,
use_global_mcp=False, # Don't load from config files
)方法3:程序化全局配置
以编程方式将MCP服务器添加到全局配置中:
from minicode import add_global_mcp_server, Agent
# Add stdio server
add_global_mcp_server(
name="memory",
command="npx",
args=["-y", "@modelcontextprotocol/server-memory"],
env={"NODE_ENV": "production"},
)
# Add HTTP server
add_global_mcp_server(
name="api-server",
url="http://localhost:8080/mcp",
headers={"Authorization": "Bearer token"},
)
# Agent will automatically use these servers
async with Agent(name="assistant", llm=my_llm) as agent:
pass方法4:直接使用MCPClient
要获得更多控制,请直接使用MCPClient:
from minicode import MCPClient
mcp = MCPClient()
# Add stdio server
await mcp.add_server(
name="memory",
command=["npx", "-y", "@modelcontextprotocol/server-memory"],
)
# Add HTTP server
await mcp.add_server(
name="api",
url="http://localhost:8080/mcp",
headers={"Authorization": "Bearer token"},
)
# Get tools and use with agent
tools = mcp.get_tools()
agent = Agent(name="assistant", llm=my_llm, tools=tools)
# Don't forget to cleanup
await mcp.disconnect_all()MCP服务器配置
| 字段 | 类型 | 描述 |
|---|---|---|
name | string | 服务器的唯一标识符 |
type | 字符串 | "stdio" (默认)或 "http" |
command | string | 要运行的命令(仅限stdio) |
args | list | 命令参数(仅限stdio) |
url | string | 服务器URL(仅限http) |
env | dict | 环境变量(仅限stdio) |
headers | dict | HTTP标头(仅限HTTP) |
热门MCP服务器
@modelcontextprotocol/server-memory-知识图存储@modelcontextprotocol/server-filesystem-文件系统访问@modelcontextprotocol/server-github-GitHub集成@modelcontextprotocol/server-postgres-PostgreSQL数据库@modelcontextprotocol/server-sqlite-SQLite数据库
看 MCP服务器 更多选择。
5.技能体系
技能为特定任务提供专门的指导和工作流程。使用 SkillTool 获取技能:
from minicode.tools.builtin import SkillTool
# Create skill tool (automatically discovers skills)
skill_tool = SkillTool()
# Add to agent
agent.add_tool(skill_tool)
# The agent can now invoke skills by name
# For example: {"skill": "data-analysis"}技能档案应存放在:
.minicode/skills/(项目特定)~/.minicode/skills/(用户范围)- 或设置
MINICODE_SKILLS_DIR用于指定自定义目录的环境变量
技能格式:
每个技能都是一个单独的目录 SKILL.md 文件(不区分大小写。, skill.md 也可以,但建议大写):
.minicode/skills/
├── my-skill/ # Directory name is for human readability
│ ├── SKILL.md # Core skill definition (required)
│ ├── example.py # Additional files can be referenced
│ └── docs/ # Additional directories can be included
│ └── guide.md
└── another-skill/
└── SKILL.mdSKILL.md格式:
---
name: my_skill
description: This skill does something useful. Use it when you need to process text input.
---
# Skill Content
This is the main skill content in Markdown format.
You can reference other files in this skill directory:
- See [example.py](./example.py) for implementation details
- Check [guide.md](./docs/guide.md) for usage guide
The agent will selectively read referenced files based on the skill description.必需的YAML元数据字段:
name:唯一、简短、人类可读的标识符description:技能的自然语言描述以及何时使用
6.代理说明
代理指令允许您定义指导代理行为的自定义指令。这些指令会自动注入到用户消息中。
文件位置(按优先级顺序):
MINICODE_AGENT_INSTRUCTIONS环境变量(文件路径,或“0”/“false”/“no”/“off”禁用).minicode/AGENT.md或.minicode/agent.md(项目级)~/.minicode/AGENT.md或~/.minicode/agent.md(用户级别)
如果两者都有 AGENT.md 和 agent.md 存在于同一目录中, AGENT.md 优先(带警告)。
示例 .minicode/AGENT.md:
# Project Guidelines
- Always use Google-style docstrings for code comments
- All generated code must be production-ready
- Ask for clarification if requirements are unclear
- Place test files in the `tests/` directory用途:
# Enabled by default
agent = Agent(
name="assistant",
llm=my_llm,
# use_agent_instructions=True is the default
)
# Disable agent instructions
agent = Agent(
name="assistant",
llm=my_llm,
use_agent_instructions=False,
)环境变量控制:
# Use a custom file
export MINICODE_AGENT_INSTRUCTIONS=/path/to/custom/instructions.md
# Disable agent instructions
export MINICODE_AGENT_INSTRUCTIONS=false例子
请参阅 examples/ 完整示例目录:
- basic_agent.py -带有文件工具的交互式代理
- custom_llm.py -创建自定义LLM实现
- custom_tool.py -创建自定义工具
- mcp_example.py -MCP集成示例
- web_tools_example.py -WebSearch和WebFetch使用示例
- notebook_edit_example.py -Jupyter笔记本编辑示例
- todowrite_example.py -任务管理和跟踪示例
- 背景_过程_示例.py -后台流程管理示例
- askuserquestion_example.py -用户交互和问题处理示例
项目结构
minicode/
├── src/minicode/
│ ├── __init__.py # Main package exports
│ ├── agent.py # Core Agent implementation
│ ├── llm/
│ │ ├── base.py # BaseLLM abstract class
│ │ └── openai.py # OpenAI implementation
│ ├── tools/
│ │ ├── base.py # BaseTool abstract class
│ │ ├── registry.py # Tool registry
│ │ └── builtin/ # Built-in tools
│ ├── mcp/
│ │ ├── client.py # MCP client
│ │ └── transport.py # Transport layer
│ ├── skills/
│ │ └── loader.py # Skills loader
│ └── session/
│ ├── message.py # Message types
│ └── prompt.py # Prompt management
├── examples/ # Example scripts
└── tests/ # Test suite发展
设置
# Clone the repository
git clone https://github.com/WalterSumbon/minicode-sdk.git
cd minicode
# Install in development mode
pip install -e ".[dev]"运行测试
# Run all unit tests (excludes integration tests)
pytest
# Run with coverage
pytest --cov=minicode
# Run integration tests (makes real API calls)
pytest -m integration
# Run specific test file
pytest tests/test_web_tools.py -v看 测试/README.md 获取详细的测试文档。
代码风格
# Format code
black src/
# Lint code
ruff check src/
# Type check
mypy src/设计原则
- 简单干净 -代码应该易于理解和修改
- 异步优先 -内置async/await以实现高效操作
- 类型安全 -完整的类型注释,以获得更好的IDE支持
- 可扩展 -易于添加自定义LLM、工具和集成
- 最小依赖性 -仅包括基本套餐
与opencode的比较
| 特性 | 开放代码(TypeScript) | 迷你代码(Python) |
|---|---|---|
| 语言 | TypeScript | Python |
| LLM支持 | 多个提供商 | 可扩展(包括OpenAI) |
| 工具系统 | ✅ | ✅ |
| MCP支持 | ✅ | ✅ |
| 技能 | ✅ | ✅ |
| async | ✅ | ✅ |
| 类型安全 | ✅ | ✅ (带类型提示) |
路线图
计划功能
- 先进工具
- ✅ AskUserQuestion-交互式用户问答,支持超时和默认答案 - ✅ Bash-执行带有超时支持和后台执行的Bash命令 - ✅ BashOutput-监控后台进程的输出 - ✅ KillShell-终止后台进程 - ✅ Glob-文件模式匹配工具 - ✅ Grep-基于ripgrep的代码搜索(带Python回退) - ✅ 编辑-文件中的精确字符串替换 - ✅ WebFetch-获取和处理web内容(HTML到Markdown/文本) - ✅ WebSearch-Web搜索集成(Exa+可配置后端) - ✅ NotebookEdit-Jupyter笔记本单元格编辑(替换/插入/删除)
- 高级功能
- ✅ 用户交互-用于代理用户通信的AskUserQuestion工具 - ✅ 后台流程管理-BashOutput和KillShell工具用于管理长时间运行的流程 - ✅ 任务管理-用于跟踪代理任务的TodoWrite工具 - 权限系统-用于工具执行确认的可选回调机制 - 文件锁定-防止并发文件修改冲突 - LSP集成-用于代码智能和诊断的语言服务器协议 - 多代理系统——任务委托和子代理管理
当前限制
- 无内置权限/确认系统(工具直接执行)
- 无并发文件操作保护
- 没有用于代码诊断的LSP集成
这些特性被有意省略,以保持微代码的简单性和重点。它们可以作为可选扩展添加,也可以根据社区需求添加到未来的版本中。
贡献
欢迎投稿!请随时提交拉取请求。
许可证
MIT许可证-有关详细信息,请参阅许可证文件。
