README
🚀 文件补丁 MCP 服务器
文件补丁 MCP 服务器提供了一种通过块格式修补现有文件的方式,让 AI 代理(如 Claude)能够对项目文件进行精确修改,解决了文件修改时需重写全量内容的问题,提升了文件修改的效率和安全性。
🚀 快速开始
文件补丁 MCP 提供了一种简单的方式来通过应用块格式的补丁来修改文件。其主要优点包括:
- 可以针对文件的特定部分进行精准修改,而无需重写整个内容
- 支持在单个请求中对同一文件进行多次补丁操作
- 通过精确文本匹配和唯一性验证确保安全性
- 桌面指挥官工具
edit_block的更优替代方案,适用于大多数文件编辑任务
📦 安装指南
使用 uvx
这种方法使用 uvx(来自 uv Python 包管理器)在不进行永久安装的情况下运行服务器:
先决条件
如果你还没有安装 uvx,请从 uv 安装。
设置 MCP 客户端(Claude Desktop、Cursor 等)
将以下配置与你的现有配置文件(例如 claude_desktop_config.json)合并:
{
"mcpServers": {
"patch-file": {
"command": "uvx",
"args": [
"patch-file-mcp",
"--allowed-dir", "/Users/your-username/projects",
"--allowed-dir", "/Users/your-username/Documents/code"
]
}
}
}
⚠️ 重要提示
请将
/Users/your-username替换为你自己的实际项目和文档路径。
从源代码安装
先决条件
- Python 3.11 或更高版本
- Pip 包管理器
克隆仓库
git clone https://github.com/your-username/patch-file-mcp.git
cd patch-file-mcp
python -m venv venv
source venv/bin/activate
pip install -e .
设置 MCP 客户端(Claude Desktop、Cursor 等)
将以下配置与你的现有配置文件(例如 claude_desktop_config.json)合并:
{
"mcpServers": {
"patch-file": {
"command": "path/to/your/venv/bin/patch-file-mcp",
"args": [
"--allowed-dir", "/Users/your-username/projects",
"--allowed-dir", "/Users/your-username/Documents/code"
]
}
}
}
⚠️ 重要提示
请将
/Users/your-username替换为你自己的实际项目和文档路径。
💻 使用示例
基础用法
文件补丁 MCP 提供一个主要工具 patch_file,用于通过块格式的补丁/编辑来更新文件。
from patch_file import patch_file
# 补丁内容
patch = """--- a/message.txt
+++ b/message.txt
@@ -1,3 +1,4 @@
Hello,
-This is a test.
+This is a test from
+Claude!
"""
# 调用 patch_file 函数进行文件补丁操作
patch_file("message.txt", patch)
高级用法
patch_file 函数还支持指定编码方式和处理编码错误的方式:
from patch_file import patch_file
patch = """--- a/message.txt
+++ b/message.txt
@@ -1,3 +1,4 @@
Hello,
-This is a test.
+This is a test from
+Claude!
"""
# 指定编码方式为 utf-8,处理编码错误的方式为 ignore
patch_file("message.txt", patch, encoding='utf-8', errors='ignore')
📚 详细文档
参数说明
--allowed-dir 参数用于指定服务器可以访问的目录。你可以多次使用它来允许访问多个目录。所有允许目录中的子目录也都是允许的。这是一个可选参数。如果没有提供,则服务器只能访问运行服务器的用户的主目录。
补丁格式
补丁内容应使用标准的 diff 格式。例如:
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,4 @@
Hello,
-This is a test.
+This is a test from
+Claude!
示例说明
假设文件 message.txt 内容为:
Hello,
This is a test.
运行以下代码:
from patch_file import patch_file
patch = """--- a/message.txt
+++ b/message.txt
@@ -1,3 +1,4 @@
Hello,
-This is a test.
+This is a test from
+Claude!
"""
patch_file("message.txt", patch)
补丁应用后,文件内容将变为:
Hello,
This is a test from
Claude!
🔧 技术细节
安全考虑
- 文件操作限制:默认情况下,服务器只能访问其运行目录以及通过
--allowed-dir参数指定的目录。 - 文本匹配唯一性:每个补丁块必须唯一地对应于目标文件的内容,以避免意外的覆盖或冲突。
- 错误报告:详细的错误信息将帮助调试任何补丁应用失败的情况。
依赖项
- fastapi(>=0.68.0,<1.0.0)
- uvicorn(>=0.15.0,<1.0.0)
📄 许可证
本项目采用 MIT 许可证。
Scan to join WeChat group