mcpField
A
agent-godmode

agent-godmode

本地服务
github.com/mdvohra开发工具023 周前更新

关于 agent-godmode

agent-godmode 是面向 Agent 开发者的 Python 工作区工具集,可作为 MCP 服务或进程内库使用。它将文件操作和命令限制在指定根目录,并提供提示词与工具定义;LLM 和 API 密钥由应用自行管理。

主要功能

  1. 01限定工作区的文件读写
  2. 02搜索并替换文件内容
  3. 03支持筛选和深度限制的文件列表
  4. 04通过 argv 执行子进程且不调用 Shell
  5. 05版本化提示词和工具定义

适用场景

  1. 01让 MCP 客户端受控访问项目目录
  2. 02为 Python Agent 应用添加工作区工具
  3. 03在指定工作区运行测试或脚本

MCP 相关

通过 stdio MCP 服务向客户端提供 read_file、write_file、edit_file、list_files 和 run_command。相同的工作区操作也可在进程内使用。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

mcp.json · 通用配置
{
"mcpServers": {
"mdvohra-agent-godmode": {
"command": "uvx",
"args": [
"agent-godmode"
],
"env": {
"AGENT_GODMODE_ROOT": "<AGENT_GODMODE_ROOT>"
}
}
}
}
启动命令uvx agent-godmode
需要配置的环境变量
AGENT_GODMODE_ROOTAbsolute workspace root; only paths under this directory are allowed. Omit if you pass --root to the CLI.

本地服务需要在你的电脑上安装运行环境(如 Node.js 18+)。各客户端的配置文件位置不同,请参考客户端文档。

安装包
pypiagent-godmode0.1.9

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

agent-godmode

用于构建 Cursor 风格 Agent 的工作区级 MCP 工具:read_file、write_file、edit_file、run_command、list_files。包含严格且有版本控制的系统提示词(SYSTEM_PROMPT_V1)和 OpenAI 风格的工具定义,让你的应用只需一次导入,就能接入任意大模型。

大模型和 API 密钥保留在你的应用中。此软件包提供工具执行、沙箱和提示词,而非托管模型。

**OpenAI + 进程内工具:**下方的 Tier B 部分可独立使用——将 Python 代码复制到脚本、模块或 REPL 中即可,无需单独的构件。

安装

pip install agent-godmode

可编辑/开发模式:

pip install -e ".[dev]"

**从 mcp-agent-tools 迁移:**卸载旧软件包,安装 agent-godmode,将 Python 导入从 mcp_agent_tools 改为 agent_godmode,将 CLI 命令从 mcp-agent-tools 改为 agent-godmode,并将环境变量从 MCP_AGENT_TOOLS_* 改为 AGENT_GODMODE_*(例如 AGENT_GODMODE_ROOT)。

工具

所有工具都限定在单个工作区根目录内。路径相对于该根目录;只有解析后位于该目录下的路径才可使用绝对路径。相同操作既可通过 MCP(agent-godmode 服务)使用,也可在进程内通过 AgentWorkspace/WorkspaceTools 使用。

工具用途
read_file读取 UTF-8 文本文件;可选行范围和字节数上限。
write_file创建或覆盖/追加 UTF-8 文本;自动创建父目录。
edit_file在现有 UTF-8 文件中查找并替换:old_string 不能为空,可选 replace_all。当 replace_all=false 时,old_string 必须精确匹配一次(使用 read_file 获取周边内容,确保匹配唯一)。遇到无效 UTF-8 时会返回错误,而不会损坏二进制数据。
list_files列出目录条目;可选递归、glob、深度上限和点文件控制。
run_command仅通过 argv 列表运行子进程(不使用 shell);可选指定根目录下的 cwd。

对于大模型集成,工具结构和描述集中定义在 OPENAI_TOOL_DEFINITIONS 和 TOOL_DESCRIPTIONS 中;Agent 行为由 SYSTEM_PROMPT_V1 指引。

Tier A — Cursor(或任何 MCP 客户端)

1. 选择一个工作区目录(只允许访问此根目录下的路径)。

2. 添加服务条目(stdio)。以下是全局 MCP 配置示例(Windows 上的路径使用正斜杠):

{
  "mcpServers": {
    "agent-godmode": {
      "command": "agent-godmode",
      "args": [],
      "env": {
        "AGENT_GODMODE_ROOT": "D:/your/project"
      }
    }
  }
}

也可以显式指定 CLI 根目录(对该进程而言会覆盖环境变量):

{
  "mcpServers": {
    "agent-godmode": {
      "command": "agent-godmode",
      "args": ["--root", "D:/your/project"]
    }
  }
}

3. 如果客户端不会自动加载服务端的 instructions,请将 SYSTEM_PROMPT_V1(来自 agent_godmode.prompts 或下文)粘贴到宿主的系统提示词中。

环境变量
变量含义
AGENT_GODMODE_ROOT必需,除非传入 --root。工作区的绝对路径。
AGENT_GODMODE_MAX_READ_BYTES每次读取的最大字节数(默认 512000)。
AGENT_GODMODE_COMMAND_TIMEOUT子进程超时时间,单位为秒(默认 120)。
AGENT_GODMODE_MAX_COMMAND_OUTPUT_BYTES截断合并后的标准输出和标准错误(默认 256000)。
AGENT_GODMODE_LIST_MAX_ENTRIESlist_files 的条目数上限(默认 2000)。
AGENT_GODMODE_ALLOWED_COMMANDS允许作为 argv[0] 的逗号分隔基本文件名(例如 python,uv,node)。如果未设置,沙盒内的所有命令均可使用。

Tier B — Python 应用(进程内 + OpenAI)

设计说明

  • 工作区根目录 — 示例使用 D:\Avi-assign 作为占位路径;将 WORK_DIR 指向你有权访问的任意目录。
  • API 密钥策略 — 只有使用 Chat Completions 时才需要 OPENAI_API_KEY。导入时会设置 client = OpenAI() if HAS_OPENAI_KEY else None;工作区设置和**直接调用 edit_file**无需密钥。
  • 由模型编写的 I/O — 对于 write_file,只持久化模型返回的文本。对于 edit_file,模型必须从 read_file 中原样复制 old_string(参见 SYSTEM_PROMPT_V1)。
1. 安装依赖

在 shell 或任何交互式 Python 会话中:

pip install -q openai
pip install -q -e "D:/MCP"   # editable checkout; or: pip install agent-godmode

如果你的环境支持行魔法(例如 IPython 中的 %pip),也可以在那里运行相同的安装命令;不要在 %pip 所在行添加 shell 注释。

2. 导入和 API 密钥处理
import os
from pathlib import Path

# OPENAI_API_KEY is required only for steps that call Chat Completions (LLM + agent loops).
# Workspace + direct edit_file work without a key.
# Set via OS env or e.g. %env OPENAI_API_KEY sk-... in IPython
# Local-only optional override — never commit a real key:
# os.environ["OPENAI_API_KEY"] = "sk-..."

from openai import OpenAI

from agent_godmode import (
    AgentWorkspace,
    OPENAI_TOOL_DEFINITIONS,
    SYSTEM_PROMPT_V1,
    run_agent_loop,
)

HAS_OPENAI_KEY = bool(os.environ.get("OPENAI_API_KEY"))
client = OpenAI() if HAS_OPENAI_KEY else None
MODEL = "gpt-4o-mini"

if not HAS_OPENAI_KEY:
    print(
        "Note: OPENAI_API_KEY not set — Chat Completions examples will raise until you set it. "
        "Workspace + direct edit_file still work."
    )
3. 工作区初始化和种子文件
# Fixed workspace — all reads/writes/commands stay under this folder
WORK_DIR = Path(r"D:\Avi-assign")
WORK_DIR.mkdir(parents=True, exist_ok=True)
print("Workspace:", WORK_DIR.resolve())

hello = WORK_DIR / "hello.txt"
if not hello.exists():
    hello.write_text("Hello from Avi-assign workspace.\n", encoding="utf-8")

ws = AgentWorkspace(WORK_DIR)
print(ws.read_file("hello.txt"))
print("--- list_files ---")
print(ws.list_files(".", recursive=False))
4. 由 LLM 编写文件内容(不调用工具)

需要 OPENAI_API_KEY。 如果你只是在测试工具而不使用 API,请跳过此步骤。

if client is None:
    raise ValueError(
        "Set OPENAI_API_KEY to run this block (e.g. export OPENAI_API_KEY=... or %env in IPython). "
        "Skip if you only want workspace / edit_file demos."
    )

# 1) Context from disk (read-only)
context = ws.read_file("hello.txt")

# 2) Ask the model to author the entire new file; no static template for the body
user_prompt = (
    "Here is the current contents of hello.txt in my workspace:\n\n"
    f"---\n{context}\n---\n\n"
    "Write ONLY the body of a new Markdown file (no preamble, no code fences) "
    "with a title line and two bullet points explaining what this greeting is for."
)

resp = client.chat.completions.create(
    model=MODEL,
    messages=[
        {
            "role": "system",
            "content": "You output only the file body the user asked for. No extra commentary.",
        },
        {"role": "user", "content": user_prompt},
    ],
)

generated = (resp.choices[0].message.content or "").strip()
if not generated:
    raise RuntimeError("LLM returned empty content; nothing to write.")

# 3) Persist exactly what the LLM produced
out_rel = "llm_generated_notes.md"
ws.write_file(out_rel, generated, mode="overwrite")
print(f"Wrote {out_rel!r} ({len(generated)} chars from model)\n")
print(ws.read_file(out_rel))
5. 直接调用 edit_file(不使用 Chat Completions)

不需要 API 密钥。 如果你还没有运行工作区部分,接下来的代码行会创建 ws(使用相同的根目录)。

# Direct edit_file (no Chat Completions call).
# If `ws` is not defined yet (e.g. you skipped §3), the next few lines create it (same WORK_DIR).
from pathlib import Path

from agent_godmode import AgentWorkspace

if "ws" not in globals():
    WORK_DIR = Path(r"D:\Avi-assign")
    WORK_DIR.mkdir(parents=True, exist_ok=True)
    ws = AgentWorkspace(WORK_DIR)

demo_edit = "edit_demo.txt"
ws.write_file(
    demo_edit,
    "version: 1\nstatus: draft\nfooter: end\n",
    mode="overwrite",
)
print("--- before ---")
print(ws.read_file(demo_edit), end="")
print(ws.edit_file(demo_edit, old_string="status: draft", new_string="status: ready"))
print("--- after ---")
print(ws.read_file(demo_edit), end="")
6. Agent 循环:模型调用 write_file

需要 OPENAI_API_KEY。

if client is None:
    raise ValueError(
        "Set OPENAI_API_KEY to run this block. "
        "Skip if you only need workspace or direct edit_file."
    )


def complete(messages, tools):
    """One Chat Completions turn; return OpenAI-shaped dict for run_agent_loop."""
    resp = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        tools=tools,
        tool_choice="auto",
    )
    return resp.model_dump()


answer = run_agent_loop(
    complete,
    "Use tools only. List the workspace root, read hello.txt, then call write_file on "
    "agent_notes.txt. The `content` argument must be your own freshly written summary "
    "(several sentences) based only on what you read—do not paste boilerplate.",
    ws,
    system_prompt=SYSTEM_PROMPT_V1,
    max_turns=12,
)
print("--- final answer ---")
print(answer)
print("--- agent_notes.txt (if created by tool write_file) ---")
p = WORK_DIR / "agent_notes.txt"
print(p.read_text(encoding="utf-8") if p.exists() else "(missing)")
7. Agent 循环:模型调用 edit_file

需要 OPENAI_API_KEY 和 §6 中的 complete 函数。

from pathlib import Path

from agent_godmode import AgentWorkspace

if "ws" not in globals():
    WORK_DIR = Path(r"D:\Avi-assign")
    WORK_DIR.mkdir(parents=True, exist_ok=True)
    ws = AgentWorkspace(WORK_DIR)
if "complete" not in globals():
    raise NameError("Define `complete` in §6 (after imports) before running this block.")
if client is None:
    raise ValueError(
        "Set OPENAI_API_KEY to run this block. "
        "The direct edit_file example in §5 works without a key."
    )

target = "edit_agent_target.txt"
ws.write_file(
    target,
    "# Demo\nThere are three erorrs in this sentance.\n",
    mode="overwrite",
)
edit_answer = run_agent_loop(
    complete,
    (
        f"Use tools only. Read `{target}`. Then use edit_file (not write_file) to fix typos: "
        "change erorrs to errors and sentance to sentence. "
        "Copy old_string exactly from read_file; use two edit_file calls or replace_all where appropriate."
    ),
    ws,
    system_prompt=SYSTEM_PROMPT_V1,
    max_turns=14,
)
print("--- agent (edit_file) answer ---")
print(edit_answer)
print("--- file after agent ---")
print(ws.read_file(target), end="")
8. 可选:不使用 run_agent_loop 的自定义工具循环

使用 OPENAI_TOOL_DEFINITIONS,通过 tools=... 调用 Chat Completions API,解析 tool_calls,并通过 ws.dispatch(name, json.loads(arguments)) 路由每次调用(需要 import json)。对于 write_file,content 字段应使用模型编写的内容;对于 edit_file,传入模型返回的 old_string、new_string 和 replace_all,保持原样。

AgentWorkspace 的可选限制
ws = AgentWorkspace(
    r"D:\Avi-assign",
    allowed_commands=frozenset({"python", "uv"}),
    command_timeout_sec=60.0,
)
较低层级(WorkspaceTools + OPENAI_TOOL_DEFINITIONS)

使用与 AgentWorkspace 相同的沙盒:通过 config_from_root(...) 和 WorkspaceTools。如果你要自行实现循环而非使用 run_agent_loop,请将 OPENAI_TOOL_DEFINITIONS 作为 tools= 传给你的提供方。

from agent_godmode import WorkspaceTools, OPENAI_TOOL_DEFINITIONS, SYSTEM_PROMPT_V1
from agent_godmode.config import config_from_root

tools = WorkspaceTools(config_from_root(r"D:\Avi-assign"))
print(tools.read_file("hello.txt"))

编写系统消息:

final_system = SYSTEM_PROMPT_V1 + "\n\n" + "Your org rules here."
导入参考
  • AgentWorkspace — 传入目录路径;仅对该目录树使用 read_file / write_file / edit_file / list_files / run_command
  • SYSTEM_PROMPT_V1、SYSTEM_PROMPT_CHANGELOG、TOOL_DESCRIPTIONS
  • OPENAI_TOOL_DEFINITIONS — 形状与 MCP 工具相同(用于聊天补全中的 tools=)
  • build_server(config) — 构建 FastMCP 应用(通过 build_server(cfg).run() 使用 stdio)
  • run_agent_loop — 使用你的 complete 可调用对象的最简多轮执行器(接受 WorkspaceConfig 或 AgentWorkspace)

安全模型

  • Python: 所有路径都解析在你传给 AgentWorkspace(...) 或 config_from_root(...) 的目录之下。
  • MCP / CLI: 通过 AGENT_GODMODE_ROOT 或 --root 执行相同规则(不可通过 .. 越界)。
  • read_file、write_file 和 edit_file 仅操作该根目录下的 UTF-8 文本路径;edit_file 要求有效的 UTF-8(严格解码)。
  • run_command 仅使用 argv(不使用 shell)。可通过 AGENT_GODMODE_ALLOWED_COMMANDS 设置可选的允许列表。
  • 子进程会继承当前环境;请避免传入你不希望子进程看到的机密信息。

CLI

agent-godmode --root D:/your/project

在 stdio 上运行 MCP 服务(Cursor 的默认方式)。

Agent 循环(概念)

  1. 系统 = SYSTEM_PROMPT_V1(+ 可选后缀)。
  2. 用户消息 + OPENAI_TOOL_DEFINITIONS → 你的大模型。
  3. 对于每个 tool_call,运行 WorkspaceTools.dispatch(或 MCP call_tool)——包括服务定义的 read_file、write_file、edit_file、list_files 和 run_command。
  4. 附加工具结果;重复执行,直到模型返回不带工具的文本。

run_agent_loop 使用你的 complete() 函数实现步骤 2–4。

许可证

MIT

MCP Badge

MCP Badge

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。