Metadata-Version: 2.4
Name: mcp-governor
Version: 1.0.0
Summary: Enterprise MCP Governor — unified AI tool governance: auth, injection scanning, PII masking, audit logging.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Requires-Python: >=3.11
Requires-Dist: cryptography>=49.0.0
Requires-Dist: fastapi>=0.100.0
Requires-Dist: fastmcp>=3.4.2
Requires-Dist: httpx>=0.28.1
Requires-Dist: prometheus-client>=0.25.0
Requires-Dist: pyahocorasick>=2.3.1
Requires-Dist: pyjwt>=2.13.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: uvicorn>=0.20.0
Provides-Extra: demo
Requires-Dist: langfuse<3.0.0,>=2.0.0; extra == 'demo'
Requires-Dist: openai>=1.0.0; extra == 'demo'
Requires-Dist: python-dotenv>=1.0.0; extra == 'demo'
Requires-Dist: uvicorn>=0.20.0; extra == 'demo'
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Provides-Extra: enterprise
Provides-Extra: grpc
Requires-Dist: grpcio-tools>=1.60.0; extra == 'grpc'
Requires-Dist: grpcio>=1.60.0; extra == 'grpc'
Requires-Dist: protobuf>=5.26.0; extra == 'grpc'
Description-Content-Type: text/markdown

# MCP Governor

> **AI 工具的统一治理中枢** — 让企业安全、合规、可控地接入 AI Agent 能力

[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](LICENSE)

## Why MCP Governor?

你的 AI Agent 正在调用内部 ERP、CRM、外部地图 API，但你可能不知道：

- 🔓 **谁能调什么？** — Agent 有没有越权访问不该看的数据？
- 🔓 **数据安全吗？** — 客户手机号、身份证在 AI 调用中是否被泄露？
- 🔓 **出了事能追溯吗？** — AI 调用出问题了，你知道是谁、调了什么、为什么被拦截吗？

MCP Governor 解决这三个问题。它是 AI Agent 与企业**内外部资源**之间的安全网关，统一整合 REST/gRPC/OpenAPI/MCP 多协议接入，并提供注入防护、PII 脱敏、审计追溯。

**企事业单位 AI 治理最短路径：3 行命令部署，10 分钟接入，零代码安全合规。**

## Quick Start

```bash
git clone https://github.com/OntarioLT/mcp-governor.git
cd mcp-governor
cp .env.example .env && vim .env   # 填入 LLM_API_KEY
docker compose up -d
curl http://localhost:8080/health  # → {"status": "ok"}
```

> 支持 DeepSeek / Qwen / Mimo / Ollama / OpenAI / Gemini 等所有 OpenAI 兼容 LLM。

## Core Capabilities

### 🛡️ 安全治理

| 能力 | 说明 |
|------|------|
| **注入防护** | 848 条 Aho-Corasick 规则（7 类别），覆盖 prompt 注入、间接注入、编码绕过、中文越狱 |
| **PII 脱敏** | 自动识别并屏蔽身份证、手机号、银行卡、邮箱（中文正则，< 3ms） |
| **审计追溯** | 结构化审计日志 + Agent 身份 + Langfuse LLM 调用追踪（Enterprise: Ed25519 签名链） |
| **零信任鉴权** | JWT + API Key + OAuth 2.1/OIDC + OPA 策略引擎，按 Agent/角色控制工具访问 |
| **Agent 隔离** | 按 Agent 名称（allowed_tools）和角色（OPA Rego 策略）双重过滤，最小权限原则 |

### 🔌 协议适配

| 能力 | 说明 |
|------|------|
| **REST → MCP** | 零配置将 REST API 动态代理为 MCP tools |
| **gRPC → MCP** | .proto 反射生成 manifest + 运行时 gRPC 代理 |
| **OpenAPI → MCP** | 一键转换 OpenAPI 3.x 文档为 MCP manifest |
| **Streamable HTTP** | MCP 2025-03-26 标准传输，向后兼容 SSE |
| **10+ 预配置集成** | 高德/钉钉/微信/飞书/GitHub/Slack/Notion 等（[预配置模板](config/presets/)）|

## Demo

基于 LLM 的自动化演示，10 大场景展示完整安全治理链路：

| # | 场景 | 效果 |
|---|------|------|
| 1 | 统一接入 | LLM 调用内部 ERP 查询库存，返回真实数据 |
| 2 | 注入防护 | 848 条规则拦截恶意 prompt 注入攻击 |
| 3 | PII 脱敏 | 客户手机号/邮箱自动屏蔽 |
| 4 | OPA 策略 | 非 admin 角色调用 `transfer_stock` 被拦截 |
| 5 | 审计追溯 | 结构化日志含 Agent 身份 + 调用轨迹 |
| 6 | 可观测性 | Prometheus + Grafana 实时监控 |
| 7 | 多源聚合 | CRM + ERP + AMAP 距离计算，就近仓库发货 |
| 8 | Agent 隔离 | hr_agent 被拒（工具无授权），user 角色被拒（无写权限） |
| 9 | 限流 | Token Bucket 限流（per-agent + per-tool） |
| 10 | REST 虚拟化 | 零配置 REST API → MCP tools |

> 完整部署指南：[`demo/RUNBOOK_DOCKER.md`](demo/RUNBOOK_DOCKER.md)（Docker Compose）
> 本地开发：[`demo/RUNBOOK_DEV.md`](demo/RUNBOOK_DEV.md)（Python 直连）

## Architecture

### System Overview

```mermaid
graph TB
    Agent["AI Agent<br/>(DeepSeek / Qwen / Ollama / OpenAI / Gemini)"]
    Agent -->|"Streamable HTTP POST /mcp"| GW["MCP Governor :8080"]
    Agent -.->|"SSE GET /mcp (legacy)"| GW

    subgraph Gateway["MCP Governor — Request Pipeline"]
        direction TB
        AUTH["Authentication"] --> SEC["Security & Policy"] --> RATE["Rate Limit"]
    end

    GW --> Gateway

    GW --> ERP["ERP API :9003"]
    GW --> CRM["CRM API :9002"]
    GW --> EXT["External MCP"]
```

### Security Hook Chain

Every request passes through a hook chain (on_request → core route → on_response):

```
on_request:  Authentication → Security & Policy → Rate Limit
                 ↓ deny          ↓ deny/block        ↓ 429

core route → backend MCP / REST / gRPC / external

on_response: Rate Limit → Security & Policy → Authentication（reverse order）
```

Enterprise hooks (Chain Detector, Ed25519 Signer) register via Python `entry_points` — zero hardcoding in community code.

### Components

| Layer | Component | Purpose |
|-------|-----------|---------|
| L1 Edge | Higress | TLS, rate limiting, routing |
| L2 Protocol | MCP SDK + FastMCP | Streamable HTTP / SSE (legacy) |
| L3 Policy | OPA + Chain Detector | Rego policy evaluation, call chain detection |
| L4 Security | AC Scanner + PII Regex | Injection prevention, data protection |
| L5 Audit | Structured Audit Log | Agent identity + structured logging (Enterprise: Ed25519 signed chain) |

### Protocol Adapters

| Adapter | CLI Command | Input | Output |
|---------|-------------|-------|--------|
| OpenAPI → MCP | `openapi2manifest` | `.yaml` / `.json` | MCP manifest JSON |
| gRPC → MCP | `openapi2manifest` | `.proto` (proto3) | MCP manifest JSON |

## Why Us?

| | MCP Governor | ContextForge (IBM) | AgentGateway |
|---|---|---|---|
| **注入检测** | ✅ 848 规则 + Normalizer | ❌ | ❌ |
| **中文 PII 脱敏** | ✅ 身份证/手机/银行卡 | ❌ | ❌ |
| **中文生态** | ✅ 高德/钉钉/微信/飞书/10+ 模板 | ❌ | ❌ |
| **REST → MCP** | ✅ 零配置 | ⚠️ 需配置 | ❌ |
| **gRPC → MCP** | ✅ 静态 + 运行时 | ✅ | ❌ |
| **零信任鉴权** | ✅ JWT + API Key + OAuth 2.1 + OPA | ⚠️ 基础认证 | ⚠️ 基础认证 |
| **审计追溯** | ✅ 结构化日志 + Agent 身份 + Langfuse LLM 追踪（Enterprise: Ed25519 签名链） | ❌ 仅 OTLP | ❌ 仅 OTLP |
| **插件生态** | ✅ entry_points + 文档 | ✅ 40+ | ✅ |
| **企业定制** | ✅ 企业版 + 按需定制 | ❌ | ❌ |

**MCP Governor 的独特定位**：安全治理 + 中文生态 + 低成本。对企事业单位而言，这是开箱即用的 AI 工具治理方案。

## External Platform Integration

MCP Governor 支持 [Streamable HTTP](https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/transports/) (`POST /mcp`) 作为主传输。任何 MCP 兼容平台（DIFY、Claude Desktop、自研 Agent）可直连 Gateway。

```json
{
  "mcpServers": {
    "mcp-governor": {
      "url": "http://<gateway-host>:8080/mcp",
      "transport": "streamable-http",
      "headers": {
        "Authorization": "ApiKey <your-api-key>"
      }
    }
  }
}
```

### 认证方式

| 方式 | Header 格式 | 适用场景 |
|------|------------|---------|
| **API Key** | `Authorization: ApiKey <key>` | 外部平台对接（固定 key，不过期） |
| **JWT** | `Authorization: Bearer <token>` | 内部 Demo、有有效期的场景 |
| **OAuth 2.1** | `Authorization: Bearer <token>` | 企业 IdP 集成（Enterprise 版增加 SSO） |

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `LLM_API_KEY` | — | LLM provider API key (必填) |
| `LLM_BASE_URL` | — | LLM API base URL |
| `LLM_MODEL` | — | LLM model name |
| `JWT_SECRET_KEY` | `dev-secret-change-me` | JWT signing secret |
| `OPA_ADDR` | `http://localhost:8181` | OPA server address |
| `INJECTION_SCORE_THRESHOLD` | `0.8` | Injection detection threshold |
| `RATE_LIMIT_CAPACITY` | `100` | Token bucket capacity |
| `AUDIT_LOG_DIR` | `/var/log/mcp-governor` | Audit log directory |
| `GRPC_TARGET` | `localhost:50051` | Default gRPC backend address |
| `GRPC_PROTO_DIR` | `manifests/grpc` | Proto files directory |
| `MCP_GOVERNOR_LICENSE` | — | Enterprise license key |

### Agent Configuration (`config/agents.yaml`)

```yaml
agents:
  demo_agent:
    api_key: "<your-api-key>"
    user_id: "demo_user"
    role: "admin"             # OPA 角色控制（admin/user/viewer）
    allowed_tools:            # Agent 名称级工具权限
      - "erp.query_stock"
      - "crm.get_customer"
      - "maps_*"
    rate_limit: 1000/hour
```

## API Reference

| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/health` | Health check | No |
| GET | `/metrics` | Prometheus metrics | No |
| POST | `/mcp` | MCP JSON-RPC (Streamable HTTP) | Yes |
| GET | `/audit` | Audit logs (latest 10) | No |
| GET | `/registry` | List registered servers | No |
| POST | `/registry` | Register server | No |
| DELETE | `/registry/{id}` | Unregister server | No |

## About

> **Lei Tian — AI Architect by profession, Traveler & Poet by passion.**

MCP Governor follows an **Open-Core** model:

- 🆓 **Community Edition** (this repo, Apache 2.0) — core gateway + injection detection + PII masking + REST/gRPC virtualization + audit logging
- 🏢 **Enterprise Edition** — OAuth/OIDC SSO + Ed25519 audit signing + Chain Detector + private deployment & customization + SLA support, and more...

📬 企业版咨询: 微信公众号「微碰旅行」→ 菜单栏「更多」→「企业定制」

![微信公众号二维码](assets/wemeet_travel.jpg)

Apache License 2.0 — see [LICENSE](LICENSE) for details.

Copyright 2026 Lei Tian
