文件补丁 MCP 服务器提供了一种通过块格式修补现有文件的方式,让 AI 代理(如 Claude)能够对项目文件进行精确修改,解决了文件修改时需重写全量内容的问题,提升了文件修改的效率和安全性。
文件补丁 MCP 提供了一种简单的方式来通过应用块格式的补丁来修改文件。其主要优点包括:
edit_block 的更优替代方案,适用于大多数文件编辑任务这种方法使用 uvx(来自 uv Python 包管理器)在不进行永久安装的情况下运行服务器:
如果你还没有安装 uvx,请从 uv 安装。
将以下配置与你的现有配置文件(例如 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替换为你自己的实际项目和文档路径。
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 .
将以下配置与你的现有配置文件(例如 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 参数指定的目录。本项目采用 MIT 许可证。