Skip to main content
Glama
lzyruc

enterprise-agent-mcp

by lzyruc
README.md
# EnterpriseOps Agent(企业运营智能体)

EnterpriseOps Agent 是一个面向企业知识问答、事件调查和受控业务执行的 Agent 服务。项目将通用 Agent 能力与企业级治理结合:模型负责规划和工具选择,确定性执行层负责身份、权限、审批、限流、幂等、副作用和审计。

默认 `demo` 模式不需要 API Key,可以完成全流程演示和测试;切换到 `openai` 模式后,使用 OpenAI Responses API 进行动态工具调用。

## 核心能力

- 通用 Agent 内核:OpenAI Responses Tool Calling、最大步数 Agent Loop、工具 JSON Schema、会话记忆和确定性离线规划器。
- 多入口复用:FastAPI REST、CLI 和 MCP Server 共享同一个 Agent Engine 与工具治理层。
- 混合 RAG:面向中文制度、员工手册和 Runbook,融合关键词重叠与 256 维确定性向量相似度。
- 能力化工具注册:工具声明 `read/write/destructive` 类型、确认策略、能力标签和输出预算,模型无法自行扩大权限。
- 企业工具治理链:身份绑定、RBAC、HITL、超时、全生命周期审计、用户/工具级限流、重复调用防护、输出裁剪和写操作幂等。
- 证据驱动调查:先分诊,再调用 Runbook、历史工单和制度调查角色,统一生成带引用、推理、排除项、证据强度和证据缺口的结构化报告。
- 持久化恢复:SQLite WAL 保存会话、消息、摘要、审批、工单、调查报告、工具执行状态和 Trace;审批后使用稳定幂等键恢复写操作。
- 可观测与评测:记录规划、策略、审批、工具开始/成功/失败/超时、调查 Findings 和综合结果;配套单元/集成测试与离线行为评测。

## 系统架构

```mermaid
flowchart TD
    Client[REST / CLI / MCP] --> Engine[Agent Engine]
    Engine --> Triage{请求分诊}
    Triage -->|知识问答/业务任务| Planner[Demo / OpenAI Planner]
    Planner --> Loop[Agent Tool Loop]
    Triage -->|事件调查| Dispatch[Capability Dispatcher]
    Dispatch --> Runbook[Runbook Investigator]
    Dispatch --> History[Ticket History Investigator]
    Dispatch --> PolicyAgent[Policy Investigator]
    Runbook --> Findings[Structured Findings]
    History --> Findings
    PolicyAgent --> Findings
    Findings --> Synthesis[Evidence-grounded Synthesis]
    Loop --> Runtime[Governed Tool Runtime]
    Runbook --> Runtime
    History --> Runtime
    PolicyAgent --> Runtime
    Runtime --> Chain[Identity → RBAC → HITL → Timeout → Audit → Rate Limit → Repeat Guard → Output Budget → Idempotency]
    Chain --> Tools[Enterprise Tools / RAG]
    Tools --> DB[(SQLite WAL)]
    Synthesis --> DB
```

所有工具入口都经过 `ToolRuntime`,而不是在 Prompt 中约定安全规则。即使模型伪造 `creator_id`、调用未授权写工具或重复触发已审批操作,执行层仍会绑定可信身份、进行权限判断并控制副作用。

## 证据驱动调查

对“排查 API 延迟异常”一类请求,系统执行以下流程:

1. Triage 根据请求信号和已注册工具能力选择调查角色,最多分派三个调查器。
2. 每个调查器只调用其能力范围内的只读工具,并把不同工具结果转换为统一 `Evidence`。
3. 每个分支输出 `Finding`,必须包含状态、摘要、推理、证据 ID、排除项和自评强度。
4. Synthesis 只允许引用 Findings 中实际存在的证据,同时明确置信度和证据缺口。
5. 完整 `InvestigationReport` 按 `trace_id` 持久化,可通过 API 复查。

结构化报告不会把用户输入或模型常识冒充成现场证据。当系统只有 Runbook、没有实时指标和日志时,会明确输出“尚不能确认具体根因”。

## 工具治理链

```text
Identity Binding
  → Authorization (RBAC + risk policy)
  → Human Approval Gate
  → Timeout
  → Audit Start/End
  → Per-user/Per-tool Rate Limit
  → Duplicate Read Guard
  → Output Budget
  → Idempotent Write Execution
  → Tool Handler
```

关键约束:

- `employee/manager/admin` 三级 RBAC 在服务端执行,未注册策略默认拒绝。
- P1 工单和敏感更新在写入前持久化审批请求;拒绝不会产生业务副作用。
- 审批恢复使用 `approval:{approval_id}` 作为稳定幂等键,相同写操作只返回首次结果,不会重复创建工单。
- 完全相同的只读调用在同一 Agent 运行中只执行一次,防止模型陷入无效循环。
- 超大结果保留原始业务值,但只向模型上下文注入受限预览,降低上下文膨胀风险。
- 限流拒绝、工具异常和超时也会进入审计 Trace;写工具超时时以 `outcome=unknown` 标记,禁止盲目重试。

## 项目结构

```text
enterprise-agent/
├─ src/enterprise_agent/
│  ├─ engine.py          # 通用 Agent Loop、审批暂停/恢复
│  ├─ orchestrator.py    # Triage、调查角色、Findings、Synthesis
│  ├─ governance.py      # 可组合工具治理中间件与统一执行入口
│  ├─ planner.py         # Demo/OpenAI 双规划器
│  ├─ tools.py           # 工具元数据、Schema 和业务处理器
│  ├─ policy.py          # RBAC 与风险策略
│  ├─ retrieval.py       # 混合 RAG
│  ├─ database.py        # SQLite Schema、事务和持久化
│  ├─ api.py             # FastAPI API
│  ├─ mcp_server.py      # MCP Server
│  └─ models.py          # Pydantic 领域模型
├─ data/knowledge.json
├─ tests/
├─ evals/
├─ docs/TECHNICAL_HIGHLIGHTS.md
├─ Dockerfile
└─ docker-compose.yml
```

## 本地运行

要求 Python 3.11+。

```powershell
cd "C:\Users\Lenovo\Desktop\agent开发准备\enterprise-agent"
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -e ".[dev]"
Copy-Item .env.example .env
```

### CLI 演示

```powershell
# 知识问答
enterprise-agent "差旅报销超过 5000 元有什么规定?"

# 多路径调查
enterprise-agent "排查 API 延迟超过 2 秒的根因,并参考历史工单"

# 持久化审批与恢复
enterprise-agent "查询制度并创建 P1 工单:生产 API 大面积超时" --approve-as u-2001
```

### REST API

```powershell
uvicorn enterprise_agent.api:app --reload --port 8000
```

- Swagger:<http://localhost:8000/docs>
- 健康检查:<http://localhost:8000/health>
- 能力和治理元数据:`GET /v1/capabilities`
- 创建会话:`POST /v1/sessions`
- 执行任务:`POST /v1/sessions/{session_id}/messages`
- 审批决策:`POST /v1/approvals/{approval_id}/decision`
- 调查报告:`GET /v1/investigations/{trace_id}`
- 执行轨迹:`GET /v1/traces/{trace_id}`
- 工单查询:`GET /v1/tickets`

生产环境应设置 `APP_ENV=production` 并更换 `API_KEY`。真实部署建议在 API Gateway 接入 OIDC/SSO,由可信令牌提供用户和角色,而不是将示例 API Key 作为最终用户认证方案。

### OpenAI 模式

```dotenv
AGENT_MODE=openai
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4.1-mini
```

模型只负责规划、工具选择和参数生成;身份绑定、审批、限流、幂等和写副作用始终由服务端代码控制。

### MCP Server

```powershell
enterprise-agent-mcp
```

MCP 暴露企业知识检索、受治理 Agent 执行和审批决策。MCP 与 REST 使用同一个 `AgentEngine`,不能绕开高风险操作审批。

### Docker

```powershell
Copy-Item .env.example .env
docker compose up --build
```

## 测试与评测

```powershell
pytest -q
python evals/run.py
ruff check src tests
```

当前回归结果:

- 自动化测试:19 项通过。
- 离线行为评测:6/6 通过。
- 覆盖范围:RAG 命中、P1 审批通过/拒绝、越权审批、角色冒充、治理 Trace、结构化调查、报告持久化、身份强绑定、数据隔离、写操作幂等、限流和 API 契约。

## 生产化边界

当前仓库适合本地演示、架构验证和二次开发。正式部署时建议:

- SQLite 替换为 PostgreSQL,限流器替换为 Redis,以支持多实例一致性。
- RAG 替换为 pgvector、Milvus 或 Elasticsearch,并增加文档分块和增量索引。
- 接入 Prometheus、Loki、Tempo、Jira 或 ServiceNow,优先开放只读工具,写工具使用最小权限凭证。
- 将 Trace 导出到 OpenTelemetry 后端,并增加 Token、延迟、工具成功率和审批等待时间指标。
- 外部连接器必须设置自己的网络超时与重试策略;写操作必须携带幂等键或采用 outbox/补偿事务。

详细的架构取舍和简历表述见 [docs/TECHNICAL_HIGHLIGHTS.md](docs/TECHNICAL_HIGHLIGHTS.md)。

TDQS

C2.9/5.0

Scored across 4 tools

Disambiguation3/5

search_enterprise_policy and search_enterprise_docs both perform hybrid retrieval over enterprise content and differ only by content type (policies vs handbooks/runbooks), which an agent could easily confuse. The run/decide pair is clearly distinct, but the two search tools create meaningful overlap.

Naming Consistency5/5

All four tools use consistent snake_case verb_noun structure with a shared 'enterprise' infix (search_enterprise_policy, search_enterprise_docs, run_enterprise_agent, decide_enterprise_approval), making the pattern highly predictable.

Tool Count3/5

Four tools is on the thin side for a governed-agent workflow, and since the two search tools largely overlap, the effective surface is even smaller. It is not egregiously sparse but feels borderline for the stated scope.

Completeness3/5

The run/approve lifecycle is covered, but there is no tool to list or fetch pending approvals, so an agent receiving an approval id has no way to discover or inspect outstanding approval requests. Retrieval also lacks any get-by-id or fetch operation.

Maintenance

ActivityMaintained
ResponsivenessNo issues