确定性代理控制协议

一个治理网关,用于管理AI代理的行为,确保每个动作都是有界、可审计、可逆和可解释的。适用于AI编码代理、DevOps部署和基础设施管理。

  • by elliot35
  • TypeScript
  • 本地部署
  • 82 星标
  • 更新于
在 GitHub 查看 elliot35/deterministic-agent-control-protocol

使用说明

自进化确定性代理控制协议

AI代理的治理网关——使每个动作都有界、可审计、可逆和可解释。

透明地工作 光标, 克劳德代码, 法典,以及任何MCP兼容代理。还支持shell命令管理和一种语言-抽象HTTP API。

🛡️ 治理在行动


1. Set Up Governance Rule
Enable the governance rule in Cursor's settings to protect your workspace.

2. Block Secrets Exfiltration
Agent attempts to read .env and write secrets — blocked instantly.

3. Block Credential Scanning
Agent tries to search for credentials and secrets files — denied by policy.

https://github.com/user-attachments/assets/ec7a9524-1527-4e51-b837-7e05a24b189d


目录


运作原理

代理从不直接执行工具。每个动作都通过控制平面进行评估、执行和审计:

flowchart LR
    A["Agent"] -->|"action request"| CP["Control Protocol"]
    CP -->|"evaluate against policy"| D{"Decision"}
    D -->|"allow"| E["Agent Executes Action"]
    D -->|"deny"| F["Blocked + Reason Logged"]
    D -->|"gate"| G["Human Approval Required"]
    E -->|"record result"| L["Evidence Ledger"]
    G -->|"approved"| E

协议 不执行 行动本身。它根据政策对它们进行评估,执行会话级预算,要求人工批准有风险的操作,并将所有内容记录在防篡改的审计分类账中。


核心原则

原理 说明
有界的 代理只能在允许的范围内执行允许的操作
会话感知 整个交互过程中的预算、费率限制和升级规则
可审计的 使用SHA-256哈希链记录在防篡改账本中的每个操作
可逆的 撤销已执行操作的补偿计划
可解释的 完整报告——允许、拒绝、封闭的内容以及原因

快速开始

安装

npm i @det-acp/core

建立治理(一个命令)

npx det-acp init cursor        # Cursor
npx det-acp init codex         # Codex CLI
npx det-acp init claude-code   # Claude Code

这将生成具有合理默认值的所有必需文件(策略、MCP配置、治理规则)。编辑 policy.yaml 自定义——其他一切都是自动处理的。

# Use your own policy instead of the default
npx det-acp init cursor --policy ./my-policy.yaml

运行后 init,重新启动代理以获取MCP服务器。

定义策略

创建 agent.policy.yaml:

version: "1.0"
name: "my-agent"

capabilities:
  - tool: "file:read"
    scope:
      paths: ["./src/**"]
  - tool: "file:write"
    scope:
      paths: ["./src/**"]
  - tool: "command:run"
    scope:
      binaries: ["npm", "node", "tsc"]

limits:
  max_runtime_ms: 1800000
  max_files_changed: 50

gates:
  - action: "file:delete"
    approval: "human"
    risk_level: "high"

evidence:
  require: ["checksums", "diffs"]
  format: "jsonl"

forbidden:
  - pattern: "**/.env"
  - pattern: "rm -rf"

session:
  max_actions: 100
  max_denials: 10
  rate_limit:
    max_per_minute: 30
  escalation:
    - after_actions: 50
      require: human_checkin
    - after_minutes: 15
      require: human_checkin

用作图书馆

import { AgentGateway } from '@det-acp/core';

const gateway = await AgentGateway.create({
  ledgerDir: './ledgers',
  onStateChange: (sessionId, from, to) => console.log(`${from} -> ${to}`),
});

// Create a session
const session = await gateway.createSession('./agent.policy.yaml', {
  agent: 'my-coding-agent',
});

// Evaluate an action (does NOT execute it)
const verdict = await gateway.evaluate(session.id, {
  tool: 'file:read',
  input: { path: './src/index.ts' },
});

if (verdict.decision === 'allow') {
  // Execute the action yourself
  const content = fs.readFileSync('./src/index.ts', 'utf-8');

  // Record the result
  await gateway.recordResult(session.id, verdict.actionId, {
    success: true,
    output: content,
    durationMs: 5,
  });
}

// Terminate and get report
const report = await gateway.terminateSession(session.id, 'task complete');
console.log(`Allowed: ${report.allowed}, Denied: ${report.denied}`);

代理集成

流行AI代理的现成指南。每个集成都包括策略、配置模板、治理规则、测试沙箱和分步说明。

代理 集成模式 治理级别 指南
光标 MCP代理+游标规则 软 集成/光标/
Codex CLI MCP代理+代理.md+操作系统沙盒 软件+沙盒 集成/codex/
克劳德代码 MCP代理+CLAUDE.md+settings.json 软+半硬 集成/claude代码/
开爪 HTTP API+Skill+Docker沙盒 硬 集成/openclaw/
Governance Levels Explained
  • 柔软 --LLM被指示(通过规则/指令文件)首选受管工具。在实践中是有效的,但从理论上讲,创造性的提示可以绕过它。
  • 半硬质 --软指令与代理的内置权限系统相结合,可以拒绝直接访问工具(例如,Claude Code的 settings.json).
  • 困难 --代理在物理上无法访问治理层之外的工具。通过Docker沙盒、工具允许/拒绝列表或自定义代理工具实现。

对于上面未列出的任何MCP兼容代理,请参阅 MCP代理(通用).


内置政策

生产就绪政策 examples/ --开箱即用:

策略 文件 用例 使用的工具
编码代理 coding-agent.policy.yaml 在项目上运行的AI编码代理 13个工具
DevOps部署 devops-deploy.policy.yaml 构建、测试和部署代码的部署代理 16个工具
视频升级器 video-upscaler.policy.yaml 运行升级管道的媒体处理代理 11个工具
数据分析师 data-analyst.policy.yaml 数据分析代理处理数据集并生成报告 12个工具
安全审计 security-audit.policy.yaml 安全扫描代理审计代码和依赖关系 11个工具
基础设施经理 infrastructure-manager.policy.yaml 处理IaC、部署和监控的基础设施管理代理 16个工具

通过以下方式验证任何策略: npx det-acp validate ./policy.yaml


集成模式

模式 工作原理 最适合
MCP代理 代理和MCP服务器之间的透明代理 游标、克劳德代码、任何MCP客户端
Shell代理 执行前验证的命令包装器 CLI代理、基于shell的工作流
HTTP API 用于会话管理的REST端点 任何语言、自定义集成
库SDK 用于进程内治理的TypeScript API 自定义TypeScript代理

MCP代理(通用)

适用于任何兼容MCP的客户端。

简化模式 --指向策略文件,自动配置文件系统后端:

npx det-acp proxy --policy ./policy.yaml
npx det-acp proxy --policy ./policy.yaml --dir /path/to/project
Full config mode

对于具有多个后端、SSE传输等的高级设置:

cat > mcp-proxy.config.yaml << 'EOF'
policy: ./agent.policy.yaml
ledger_dir: ./.det-acp/ledgers
transport: stdio
backends:
  - name: filesystem
    transport: stdio
    command: npx
    args: ["-y", "@modelcontextprotocol/server-filesystem", "./src"]
EOF

npx det-acp proxy ./mcp-proxy.config.yaml

Shell代理

通过策略网关执行命令:

npx det-acp exec ./agent.policy.yaml echo "hello"    # Allowed
npx det-acp exec ./agent.policy.yaml rm -rf /tmp      # Denied (forbidden)

HTTP会话服务器

npx det-acp serve --port 3100
HTTP API Examples
# Create a session
curl -X POST http://localhost:3100/sessions \
  -H "Content-Type: application/json" \
  -d '{"policy": "version: \"1.0\"\nname: test\ncapabilities:\n  - tool: file:read\n    scope:\n      paths: [\"./src/**\"]"}'

# Evaluate an action
curl -X POST http://localhost:3100/sessions/<session-id>/evaluate \
  -H "Content-Type: application/json" \
  -d '{"action": {"tool": "file:read", "input": {"path": "./src/index.ts"}}}'

# Record result
curl -X POST http://localhost:3100/sessions/<session-id>/record \
  -H "Content-Type: application/json" \
  -d '{"actionId": "<action-id>", "result": {"success": true, "output": "..."}}'

# Terminate session
curl -X POST http://localhost:3100/sessions/<session-id>/terminate

CLI参考

npx det-acp init <agent>                  # Set up governance (cursor, codex, claude-code)
npx det-acp init <agent> --policy <file>  # Use custom policy
npx det-acp validate <policy-file>        # Validate a policy
npx det-acp proxy --policy <policy-file>  # Start MCP proxy (simplified)
npx det-acp proxy --policy <policy-file> --evolve  # With policy self-evolution
npx det-acp proxy <config-file>           # Start MCP proxy (full config)
npx det-acp exec <policy-file> <command>  # Execute via shell proxy
npx det-acp report <ledger-file>          # View audit report
npx det-acp serve [--port <port>]         # Start HTTP session server

政策自我进化

当一个动作 拒绝 根据策略,自进化功能可以建议允许它的最小策略更改,提示您做出决定,并可选择更新策略(在内存和/或磁盘上)。这在默认情况下保持了严格的治理,同时允许您在批准时逐步放宽政策。

它的作用

  • 分析否认 --模式匹配拒绝原因(缺少功能、范围外的路径/二进制/域、禁止的模式),并生成单个最小的策略编辑。
  • 提示您 --提出建议(例如“添加 file:read 路径能力 ./config/**?“)通过代理自己的聊天UI。
  • 三种选择:
    • 添加到策略 --将更改应用于会话的策略和 持续 将其保存到策略YAML文件中。
    • 允许一次 --应用更改 仅在内存中 对于当前会话(无磁盘写入)。
    • 拒绝 --保持挡块;没有变化。
  • 重试 --批准后,代理根据更新的策略重试原始工具调用。

拒绝预算和会话限制(例如“超出预算”、“超出费率限制”) 不 暗示性;只有权限/范围/禁止的拒绝才能触发进化。

它是如何工作的(MCP原生)

当作为MCP代理运行时(Cursor、Claude Code和Codex的默认设置),进化使用 两步异步协议 完全基于标准MCP工具调用构建——不需要终端stdin/stdout:

  1. 关于否认: 代理向代理返回拒绝,并附上结构化建议和唯一 suggestion_id.
  2. 批准时: 客服在聊天中向用户提出建议,收集他们的决定,并致电 policy_evolution_approve 随着 suggestion_id 和决定。
  3. 重试时: 代理应用策略更改。代理重试原始工具调用,现在成功。
sequenceDiagram
    participant User
    participant Agent as Agent (Cursor / Claude Code)
    participant Proxy as MCP Proxy
    participant GW as Gateway

    Agent->>Proxy: callTool("read_text_file", path)
    Proxy->>GW: evaluate()
    GW-->>Proxy: deny
    Proxy->>Proxy: suggestPolicyChange()
    Proxy-->>Agent: Denied + suggestion + suggestionId

    Agent->>User: "read_text_file denied. Add capability for path X?"
    User-->>Agent: "Yes, add to policy"

    Agent->>Proxy: callTool("policy_evolution_approve", suggestionId, "add-to-policy")
    Proxy->>Proxy: applyPolicyChange + writePolicyToFile
    Proxy-->>Agent: "Policy updated"

    Agent->>Proxy: callTool("read_text_file", path)
    Proxy->>GW: evaluate()
    GW-->>Proxy: allow
    Proxy-->>Agent: file contents

这适用于 每个MCP客户端 因为它只使用标准的MCP工具调用协议——没有读线,没有stdin冲突。

实现自我进化

MCP代理(简化模式):

npx det-acp proxy --policy ./policy.yaml --evolve

这 init 命令包括 --evolve 默认情况下,在生成的MCP配置中。

程序化(库): 通过 policyEvolution 在 GatewayConfig 对于非MCP设置(例如CLI脚本、自定义代理):

import { AgentGateway, createCliEvolutionHandler } from '@det-acp/core';

const gateway = await AgentGateway.create({
  ledgerDir: './ledgers',
  policyEvolution: {
    policyPath: './agent.policy.yaml',
    handler: createCliEvolutionHandler(),
    timeoutMs: 30_000,
  },
});

您可以插入自定义 EvolutionHandler (例如GUI对话框、webhook)而不是 createCliEvolutionHandler().

进化架构(高级)

flowchart LR
    subgraph Denial["On Deny"]
        A["Action Denied"] --> B["Suggestion Engine"]
        B --> C{"Suggestible?"}
        C -->|No| D["Keep Deny"]
        C -->|Yes| E["PolicySuggestion + ID"]
    end
    E --> F["Agent presents to user"]
    F --> G{"User Decision"}
    G -->|Add to policy| H["policy_evolution_approve → Apply + Write YAML"]
    G -->|Allow once| I["policy_evolution_approve → Apply in-memory"]
    G -->|Deny| D
    H --> J["Retry original tool call"]
    I --> J
    J --> K{"Verdict"}
    K -->|allow| L["Proceed"]
    K -->|deny| D

这 建议引擎 将拒绝原因映射到以下之一:添加功能、扩大范围(路径/二进制文件/域/方法/repo)或删除禁止的模式。在MCP代理模式下 MCP进化处理器 将建议作为结构化拒绝返回给代理,并使用 suggestion_id,然后代理呼叫 policy_evolution_approve 在收集用户的决定之后。在库模式下 策略演变经理 使用具有可配置超时的可插拔处理程序(CLI、GUI、webhook),并内联重新评估操作。


建筑

组件架构

graph TB
    subgraph External["External Systems"]
        BackendMCP["Backend MCP Servers"]
        Approvers["Human / Webhook Approvers"]
    end

    subgraph Integration["Integration Layer"]
        subgraph MCPProxyGroup["MCP Proxy Server"]
            MCPProxy["MCP Proxy"]
            subgraph McpEvo["MCP Evolution (optional)"]
                McpEvoHandler["MCP Evolution Handler"]
                EvoTool["policy_evolution_approve tool"]
            end
        end
        ShellProxy["Shell Proxy"]
        HTTPServer["HTTP Server"]
        LibrarySDK["Library SDK"]
    end

    subgraph Core["Core Engine"]
        Gateway["Agent Gateway"]
        SessionMgr["Session Manager"]
        PolicyEval["Policy Evaluator"]
        GateMgr["Gate Manager"]
        ActionReg["Action Registry"]
        subgraph Evolution["Policy Self-Evolution (optional)"]
            EvolutionMgr["Policy Evolution Manager"]
            SuggestionEngine["Suggestion Engine"]
        end
    end

    subgraph Infra["Infrastructure"]
        Ledger["Evidence Ledger<br/>(JSONL + SHA-256)"]
        Rollback["Rollback Manager"]
    end

    subgraph Tools["Tool Adapters"]
        subgraph FileTools["File Operations"]
            FR["file:read"]
            FW["file:write"]
            FD["file:delete"]
            FM["file:move"]
            FC["file:copy"]
        end
        subgraph DirTools["Directory Operations"]
            DL["directory:list"]
            DC["directory:create"]
        end
        subgraph GitTools["Git Operations"]
            GD["git:diff"]
            GA["git:apply"]
            GC["git:commit"]
            GS["git:status"]
        end
        subgraph NetTools["Network & System"]
            CR["command:run"]
            HR["http:request"]
            ND["network:dns"]
            ER["env:read"]
            AE["archive:extract"]
        end
    end

    MCPProxy --> Gateway
    ShellProxy --> Gateway
    HTTPServer --> Gateway
    LibrarySDK --> Gateway

    Gateway --> SessionMgr
    Gateway --> ActionReg
    Gateway --> GateMgr

    SessionMgr --> PolicyEval
    SessionMgr --> GateMgr
    SessionMgr --> Ledger
    SessionMgr -->|on deny| EvolutionMgr
    EvolutionMgr --> SuggestionEngine

    MCPProxy -->|on deny| McpEvoHandler
    McpEvoHandler --> SuggestionEngine
    EvoTool -->|apply change| SessionMgr

    ActionReg --> FileTools
    ActionReg --> DirTools
    ActionReg --> GitTools
    ActionReg --> NetTools

    Rollback --> ActionReg
    Rollback --> Ledger

    MCPProxy --> BackendMCP
    GateMgr --> Approvers

行动评估流程

sequenceDiagram
    participant Agent
    participant Integration
    participant Gateway as Agent Gateway
    participant Session as Session Manager
    participant Policy as Policy Evaluator
    participant Gate as Gate Manager
    participant Ledger as Evidence Ledger

    Agent ->> Integration: Action request (tool, input)
    Integration ->> Gateway: evaluate(sessionId, action)
    Gateway ->> Session: evaluate(sessionId, action)

    Session ->> Policy: evaluateSessionAction(action)

    Note right of Policy: 1. Session state check<br/>2. Rate limits & escalation<br/>3. Forbidden patterns<br/>4. Capability & scope match<br/>5. Budget limits<br/>6. Gate lookup

    Policy -->> Session: allow / deny / gate

    Session ->> Ledger: append(action:evaluate)

    alt Gate required
        Session ->> Gate: requestApproval(action, gate)
        alt Approved
            Gate -->> Session: approved
        else Pending
            Gate -->> Session: pending
            Note over Agent, Gate: Session paused until resolved
        end
    end

    Session -->> Gateway: EvaluateResponse
    Gateway -->> Integration: decision + reasons
    Integration -->> Agent: allow / deny / gate

    alt Allowed
        Note over Agent: Executes action externally
        Agent ->> Integration: recordResult(actionId, result)
        Integration ->> Gateway: recordResult(sessionId, actionId, result)
        Gateway ->> Session: recordResult(result)
        Session ->> Session: Update budget tracking
        Session ->> Ledger: append(action:result)
    end

    opt Session complete
        Agent ->> Integration: terminateSession()
        Integration ->> Gateway: terminate(sessionId)
        Gateway ->> Session: terminate(sessionId)
        Session ->> Ledger: append(session:terminate)
        Session -->> Agent: Session Report
    end

会话生命周期

stateDiagram-v2
    [*] --> Created: createSession()
    Created --> Evaluating: evaluate(action)
    Evaluating --> Allowed: policy allows
    Evaluating --> Denied: policy denies
    Evaluating --> Gated: gate required
    Gated --> Allowed: approved
    Gated --> Denied: rejected
    Allowed --> Recording: recordResult()
    Recording --> Evaluating: next action
    Denied --> Evaluating: next action
    Recording --> Terminated: terminateSession()
    Evaluating --> Terminated: terminateSession()
    Terminated --> [*]

证据台账

每个操作都会生成一个JSONL格式的不可变审计记录,该记录具有SHA-256哈希链:

{"seq":1,"ts":"...","hash":"sha256:abc...","prev":"sha256:000...","type":"session:start","data":{...}}
{"seq":2,"ts":"...","hash":"sha256:def...","prev":"sha256:abc...","type":"action:evaluate","data":{...}}
{"seq":3,"ts":"...","hash":"sha256:ghi...","prev":"sha256:def...","type":"action:result","data":{...}}

如果任何条目被篡改,哈希链就会断裂,完整性验证失败。


策略DSL参考

第节 目的
capabilities 允许的工具及其作用域路径、二进制文件或域
limits 运行时间、成本、文件更改和重试预算
gates 需要人工或webhook批准的操作
evidence 必须记录的工件(校验和、差异)
forbidden 总是被阻塞的模式
session 最大操作数、速率限制、升级规则
remediation 错误处理规则和回退链

看 示例/ 获取完整的策略文件。


内置工具适配器

文件操作

工具 描述 回滚
file:read 读取作用域路径内的文件 不适用(只读)
file:write 使用备份写入文件以进行回滚 还原以前的内容
file:delete 删除作用域路径中的文件 从备份中还原文件
file:move 在作用域路径内移动/重命名文件 将文件移回原始位置
file:copy 复制作用域路径内的文件 删除复制的文件

目录操作

工具 描述 回滚
directory:list 列出作用域路径内的文件和目录 不适用(只读)
directory:create 在作用域路径内创建目录 删除创建的目录

命令执行

工具 描述 回滚
command:run 执行允许列出的二进制文件并超时 补偿操作

Git操作

工具 描述 回滚
git:diff 获取git diff输出 不适用(只读)
git:apply 使用基于存储的回滚应用git补丁 git checkout . && git stash pop
git:commit 阶段和提交更改 git reset --soft HEAD~1
git:status 获取工作树状态 N/A(只读)

网络和HTTP

工具 描述 回滚
http:request 允许列出域的HTTP请求 补偿操作
network:dns 允许列出的域的DNS查找 N/A(只读)

环境与系统

工具 描述 回滚
env:read 通过自动编辑机密读取环境变量 N/A(只读)
archive:extract 在作用域路径中提取tar/zip存档 删除提取的文件

自定义工具适配器

扩展 ToolAdapter 基类以添加您自己的工具:

import { ToolAdapter } from '@det-acp/core';
import { z } from 'zod';

class MyCustomTool extends ToolAdapter {
  readonly name = 'custom:mytool';
  readonly description = 'My custom tool';
  readonly inputSchema = z.object({
    target: z.string().min(1),
    options: z.record(z.string()).optional(),
  });

  validate(input, policy) { /* ... */ }
  async dryRun(input, ctx) { /* ... */ }
  async execute(input, ctx) { /* ... */ }
  async rollback(input, ctx) { /* ... */ }
}

// Register it
gateway.getRegistry().register(new MyCustomTool());

每个工具适配器都遵循执行生命周期: 验证 -> 试运行 -> (闸门检查) -> 执行 -> 验证。每一步都记录在证据分类账中。


发展

npm install          # Install dependencies
npm run lint         # Type check (TypeScript strict)
npm test             # Run tests (Vitest)
npm run build        # Build

贡献

欢迎投稿!请遵循以下指南:

  1. 分叉 存储库并创建功能分支
  2. 跟随 编码标准(TypeScript严格、ESM、Zod验证)
  3. 编写测试 镜像 src/ 结构下 tests/
  4. 跑 npm test && npm run lint 在提交之前
  5. 使用 常规承诺 用于提交消息
  6. 打开PR 清晰地描述了变化

许可证

麻省理工学院


星迹