Python的MCP代码模式
轻量级库,用于以最小的上下文开销调用MCP工具。
实施Anthropic的原则 使用MCP执行代码 Cloudflare的 代码模式 文章。
双重用途:库+MCP服务器
mcp编码模式可用于 双向:
1.作为Python库
直接集成到Python应用程序中:```python
from mcp_codemode import mcp
result = await mcp.filesystem.read_file(path="/etc/hosts")
### 2.作为MCP服务器(元MCP模式)
将codemode本身配置为MCP服务器,提供对整个MCP目录的高效访问:```json
{
"mcpServers": {
"codemode": {
"command": "python",
"args": ["-m", "mcp_codemode.server_main"],
"transport": "stdio"
}
}
}
然后使用以下工具 search_tools, execute_code等,通过最小的界面与所有配置的服务器进行交互!
看 MCP_SERVER_USAGE.md 了解完整细节。
问题
传统的MCP用法将所有工具定义加载到LLM上下文中:
- 50个工具x 200个代币= 10000个代币 在做任何工作之前
- 多步操作需要通过LLM进行往返
- 大型数据集不必要地膨胀了上下文
解决方案
LLM更擅长编写代码,而不是直接调用工具。
该库提供:
- 渐进式披露 -按需加载工具
- 延迟加载 -仅在需要时加载架构
- 本地处理 -无上下文开销的多步骤操作
- 类型安全性 -JSON模式的Pydantic验证
- IDE支持 -生成用于自动补全的.pyi存根
影响
上下文使用率降低98-99%```
Traditional: ~10,000 tokens (all tools loaded)
Code Mode: ~200 tokens (lazy loading + local processing)
## 快速开始
### 安装```bash
uv add mcp-codemode-py
# or
pip install mcp-codemode-py
基本用法```python
from mcp_codemode import mcp
Direct tool call - schema loads automatically
result = await mcp.filesystem.read_file(path="/etc/hosts")
Multi-step with local processing (no context overhead!)
files = await mcp.filesystem.list_directory(path="/var/log")
large_files = [f for f in files if f['size'] > 1_000_000]
for file in large_files[:10]:
content = await mcp.filesystem.read_file(path=file['path'])
Process locally - doesn't bloat context
Only return what matters
return {"count": len(large_files), "sample": large_files[:3]}
### 发现API```python
# Discover servers
servers = await mcp.list_servers()
# Discover tools on a server
tools = await mcp.github.list_tools()
# Search across everything
results = await mcp.search("create issue")
# -> [SearchResult(server="github", tool="create_issue", score=0.95)]
# Use the results
await mcp.github.create_issue(repo="...", title="...", body="...")
命令行界面```bash
Generate .pyi stub files for IDE support
mcp-codemode stub-gen
List available servers
mcp-codemode list
Search for tools
mcp-codemode search "file operations"
List tools for a server
mcp-codemode tools github --detailed
## 配置
创建 `.codemode/config.json` 在您的项目中:```json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"],
"transport": "stdio"
},
"github": {
"command": "mcp-server-github",
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
},
"transport": "stdio"
}
}
}
基于文件的发现
非常适合Claude Code-使用本机文件工具探索工具:```bash
Generate stubs
mcp-codemode stub-gen
创建结构:```
.codemode/
stubs/
filesystem/
__init__.pyi
read_file.pyi
write_file.pyi
github/
create_issue.pyi
list_repos.pyi
然后自然地探索:
- 全局:
**/*.pyi->查找所有工具 - grep:
create.*issue->按关键字搜索 - 阅读:查看带有类型提示的工具架构
设计理念
发现的三个层次```
Level 0: Start with just mcp object (0 tokens)
|
Level 1: Discover servers when needed (~20 tokens)
|
Level 2: Discover tools on server (~50 tokens)
|
Level 3: Load schema on tool call (0 context tokens)
### Pydantic的类型安全```python
# Automatic validation from JSON Schema
await mcp.filesystem.read_file(path="/etc/hosts") # OK
# Validation catches errors
await mcp.filesystem.read_file(path=123) # ValueError
懒惰的一切
- 模式仅在调用工具时加载
- 缓存可防止冗余获取
- 背景存根生成(可选)
例子
看 examples/ 目录:
basic_usage.py-核心API模式claude_code_workflow.py-Claude代码集成
建筑```
+------------------+
| Your Code |
+--------+---------+
|
+--------v---------+
| MCP Code Mode | <- Pydantic validation
| | <- Lazy loading
| | <- Progressive disclosure
+--------+---------+
|
+--------v---------+
| MCP SDK | <- Official MCP client
+--------+---------+
|
+--------v---------+
| MCP Servers | <- filesystem, github, etc.
+------------------+
## 主要特点
### 混合动力探索
- **程序化**: `await mcp.search("create issue")`
- **基于文件**:生成存根,使用文件工具浏览
- **工作**:选择适合您工作流程的内容
### 基于文本的搜索
简单、轻便的匹配(无嵌入):```python
results = await mcp.search("file operations")
# Matches against tool names and descriptions
自动树桩生成
在回购中导入时:```python
from mcp_codemode import mcp
Background: generates .codemode/stubs/ automatically
或手动:```bash
mcp-codemode stub-gen
基于会话的缓存
- 会话期间工具不会更改
- 无限期缓存架构
- 无陈旧数据问题
整合
使用克劳德代码```python
from mcp_codemode import mcp
Claude Code naturally:
1. Uses Glob to find available tools
2. Uses Grep to search by keyword
3. Uses Read to view schemas
4. Calls tools with validation
result = await mcp.github.create_issue(...)
### 使用Anthropic SDK```python
from anthropic import Anthropic
from mcp_codemode import mcp
client = Anthropic()
# Claude writes code that uses mcp
code = """
files = await mcp.filesystem.list_directory(path='/var/log')
large = [f for f in files if f['size'] > 1_000_000]
return large[:5]
"""
# Execute in your environment
# (with mcp available)
当前状态
版本0.2.0-生产就绪
已实施:
- 具有Pydantic验证的核心代理对象
- 渐进式发现(3个级别)
- 基于文本的搜索
- 短路发生器
- CLI工具
- 官方MCP SDK集成
- 配置管理
- 综合测试(30项测试通过)
- MCP服务器模式 配备6个用于元MCP模式的工具
MCP服务器模式
当用作MCP服务器时,codemode提供了6个工具,可以访问整个MCP目录:
- 搜索工具 -在所有服务器上搜索相关工具
- list_server -列出已配置的MCP服务器
- list_tools -列出特定服务器上的工具
- get_tool_schema -获取工具的完整架构
- execute_code -执行Python代码并访问所有服务器(效率最高!)
- call_tool -直接工具调用
为什么用作MCP服务器?
- 大规模上下文缩减:上下文中有6个工具,而单个服务器中有100多个工具
- execute_code工具:编写在一次调用中使用多个服务器的代码
- 渐进式披露:按需发现和使用工具
- 统一接口:所有MCP服务器的一个配置点
execute_code示例:```python
One tool call that uses multiple servers!
{
"tool": "execute_code",
"arguments": {
"code": "files = await mcp.filesystem.list_directory(path='.')\nlarge = [f for f in files if f['size'] > 1_000_000]\nissue = await mcp.github.create_issue(repo='user/repo', title=f'{len(large)} large files')\nreturn {'issue': issue['number']}"
}
}
```
看 MCP_SERVER_USAGE.md 获取完整文档。
条款
该库实现了以下原则:
- Anthropic:使用MCP执行代码
- 代币减少98.7%
- 渐进式披露
- 本地数据处理
- Cloudflare:代码模式
- LLM比工具调用更擅长代码
- 单执行沙盒
- 生成TypeScript API
设计决策
为什么是Pydantic?
- Python生态系统中无处不在
- 从JSON模式自动验证
- IDE支持的类型提示
为什么是基于文本的搜索?
- 轻量级(无重依赖性)
- 对于典型用例来说,速度足够快
- 如果需要,可以稍后升级到嵌入
为什么选择混合发现?
- 程序化:始终新鲜,无处不在
- 基于文件:对Claude Code来说很自然,IDE支持很强
- 两者皆有:选择的灵活性
为什么是.codemode/?
- 与MCP配置明确分离
- 包含存根和缓存
- 容易感染
许可证
麻省理工学院
致谢
基于以下研究和文章:
- 人类学(使用MCP执行代码)
- Cloudflare(代码模式)
使用 模型上下文协议 通过Anthropic。
