ContextForge
> 一个开源注册表和代理,将MCP、A2A和REST/gRPC API与集中式治理、发现和可观察性联合起来。优化代理和工具调用,并支持插件。
ContextForge 是一个开源注册表和代理,它将工具、代理和API联合到一个干净的端点中,供您的AI客户端使用。它为您的AI基础设施提供了集中的治理、发现和可观察性:
- 工具网关 --MCP、REST、gRPC到MCP的转换和TOON压缩
- 代理网关 --A2A协议、OpenAI兼容和Anthropic代理路由
- API网关 --REST服务的速率限制、身份验证、重试和反向代理
- 插件可扩展性 --40多个插件,用于其他传输、协议和集成
- 可观测性 --使用Phoenix、Jaeger、Zipkin和其他OTLP后端进行OpenTetry跟踪
它作为一个完全兼容的MCP服务器运行,可通过PyPI或Docker部署,并可扩展到Kubernetes上的多集群环境,具有Redis支持的联盟和缓存。
目录
- 概述与目标
- 快速入门-PyPI
- 快速入门-容器
- VS代码开发容器
- 安装
- 升级
- 配置
- 跑步
- 云部署
- API 参考
- 测试
- 项目结构
- 发展
- 故障排除
- 贡献
📌 快速链接
| 资源 | 描述 |
|---|---|
| 5分钟设置 | 快速入门——uvx、Docker、Compose或本地开发 |
| 获取帮助 | 支持选项、常见问题解答、社区频道 |
| 问题指南 | 如何提交bug、请求功能、贡献 |
| 全部文件 | 完整的指南、教程、API参考资料 |
概述与目标
ContextForge 是一个开源注册表和代理,可以联合任何 模型上下文协议 (MCP)服务器、A2A服务器或REST/gRPC API,提供集中管理、发现和可观察性。它优化了代理和工具调用,并支持插件。看 项目路线图 了解更多详情。
它目前支持:
- 跨多个MCP和REST服务的联合
- A2A(代理到代理)集成 用于外部AI代理(OpenAI、Anthropic、自定义)
- gRPC到MCP的转换 通过基于自动反射的服务发现
- 将遗留API虚拟化为符合MCP的工具和服务器
- 通过HTTP、JSON-RPC、WebSocket、SSE(具有可配置的保活)、stdio和流式传输HTTP
- 用于实时管理、配置和日志监控的管理UI(具有无间隙部署支持)
- 内置身份验证、重试和速率限制,具有用户范围的OAuth令牌和无条件的X-Upstream-Authorization标头支持
- 开放遥测可观察性 与Phoenix、Jaeger、Zipkin和其他OTLP后端合作
- 通过Docker或PyPI、Redis支持的缓存和多集群联盟进行可扩展部署
有关即将推出的功能列表,请查看 ContextForge路线图
🔌 Gateway Layer with Protocol Flexibility
- 联合任何MCP服务器或REST API
- 允许您选择MCP协议版本(例如。,
2025-11-25) - 为不同的后端提供一个统一的接口
🧩 Virtualization of REST/gRPC Services
- 将非MCP服务包装为虚拟MCP服务器
- 以最少的配置注册工具、提示和资源
- gRPC到MCP的转换 通过服务器反射协议
- 自动服务发现和方法自检
🔁 REST-to-MCP Tool Adapter
-
将REST API改编为具有以下功能的工具:
-
自动JSON模式提取
- 支持标头、令牌和自定义身份验证
- 重试、超时和速率限制策略
🧠 Unified Registries
- 提示:Jinja2模板、多模式支持、回滚/版本控制
- 资源:基于URI的访问、MIME检测、缓存、SSE更新
- 工具:原生或改编,具有输入验证和并发控制
📈 Admin UI, Observability & Dev Experience
- 使用HTMX 2.0.3(捆绑)+Alpine.js构建的管理UI
- 具有过滤、搜索和导出功能的实时日志查看器
- 认证:基本、JWT或自定义方案
- 结构化日志、健康端点、指标
- 7000多个测试、Makefile目标、实时重载、预提交挂钩
🔍 OpenTelemetry Observability
- 与供应商无关的跟踪 支持开放遥测(OTLP)协议
- 多种后端支持:Phoenix(法学硕士)、Jaeger、Zipkin、Tempo、DataDog、New Relic
- 分布式跟踪 跨联邦网关和服务
- 自动仪表 工具、提示、资源和网关操作
- LLM特定指标:令牌使用、成本、模型性能
- 禁用时开销为零 优雅的退化
看 可观察性文档 用于Phoenix、Jaeger和其他后端的设置指南。
快速入门-PyPI
ContextForge发布于 PyPI 作为 mcp-contextforge-gateway.
太长,读不下去了:
(使用单个命令 紫外线)```bash
Quick start with environment variables
BASIC_AUTH_PASSWORD=pass \
MCPGATEWAY_UI_ENABLED=true \
MCPGATEWAY_ADMIN_API_ENABLED=true \
PLATFORM_ADMIN_EMAIL=admin@example.com \
PLATFORM_ADMIN_PASSWORD=changeme \
PLATFORM_ADMIN_FULL_NAME="Platform Administrator" \
uvx --from mcp-contextforge-gateway mcpgateway --host 0.0.0.0 --port 4444
Or better: use the provided .env.example
cp .env.example .env
Edit .env to customize your settings
uvx --from mcp-contextforge-gateway mcpgateway --host 0.0.0.0 --port 4444
📋 Prerequisites
- **Python≥3.11**
- **curl+jq** -仅适用于最后一个烟雾测试步骤
### 1-安装并运行(复制粘贴友好)```bash
# 1️⃣ Isolated env + install from pypi
mkdir mcpgateway && cd mcpgateway
python3 -m venv .venv && source .venv/bin/activate
pip install --upgrade pip
pip install mcp-contextforge-gateway
# 2️⃣ Copy and customize the configuration
# Download the example environment file
curl -O https://raw.githubusercontent.com/IBM/mcp-context-forge/main/.env.example
cp .env.example .env
# Edit .env to customize your settings (especially passwords!)
# Or set environment variables directly:
export MCPGATEWAY_UI_ENABLED=true
export MCPGATEWAY_ADMIN_API_ENABLED=true
export PLATFORM_ADMIN_EMAIL=admin@example.com
export PLATFORM_ADMIN_PASSWORD=changeme
export PLATFORM_ADMIN_FULL_NAME="Platform Administrator"
BASIC_AUTH_PASSWORD=pass JWT_SECRET_KEY=my-test-key-but-now-longer-than-32-bytes \
mcpgateway --host 0.0.0.0 --port 4444 & # admin/pass
# 3️⃣ Generate a bearer token & smoke-test the API
export MCPGATEWAY_BEARER_TOKEN=$(python3 -m mcpgateway.utils.create_jwt_token \
--username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes)
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
http://127.0.0.1:4444/version | jq
Windows (PowerShell) quick-start```powershell
1️⃣ Isolated env + install from PyPI
mkdir mcpgateway ; cd mcpgateway
python3 -m venv .venv ; ..venv\Scripts\Activate.ps1
pip install --upgrade pip
pip install mcp-contextforge-gateway
2️⃣ Copy and customize the configuration
Download the example environment file
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/IBM/mcp-context-forge/main/.env.example" -OutFile ".env.example"
Copy-Item .env.example .env
Edit .env to customize your settings
Or set environment variables (session-only)
$Env:MCPGATEWAY_UI_ENABLED = "true"
$Env:MCPGATEWAY_ADMIN_API_ENABLED = "true"
Note: Basic auth for API is disabled by default (API_ALLOW_BASIC_AUTH=false)
$Env:JWT_SECRET_KEY = "my-test-key-but-now-longer-than-32-bytes"
$Env:PLATFORM_ADMIN_EMAIL = "admin@example.com"
$Env:PLATFORM_ADMIN_PASSWORD = "changeme"
$Env:PLATFORM_ADMIN_FULL_NAME = "Platform Administrator"
3️⃣ Launch the gateway
mcpgateway.exe --host 0.0.0.0 --port 4444
Optional: background it
Start-Process -FilePath "mcpgateway.exe" -ArgumentList "--host 0.0.0.0 --port 4444"
4️⃣ Bearer token and smoke-test
$Env:MCPGATEWAY_BEARER_TOKEN = python3 -m mcpgateway.utils.create_jwt_token `
--username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes
curl -s -H "Authorization: Bearer $Env:MCPGATEWAY_BEARER_TOKEN" `
http://127.0.0.1:4444/version | jq
⚡ Alternative: uv (faster)```powershell
# 1️⃣ Isolated env + install from PyPI using uv
mkdir mcpgateway ; cd mcpgateway
uv venv
.\.venv\Scripts\activate
uv pip install mcp-contextforge-gateway
# Continue with steps 2️⃣-4️⃣ above...
More configuration
复制 .env.示例 到 .env 并调整任何设置(或将其用作环境变量)。
🚀 End-to-end demo (register a local MCP server)```bash
1️⃣ Spin up the sample GO MCP time server using mcpgateway.translate & docker (replace docker with podman if needed)
python3 -m mcpgateway.translate \
--stdio "docker run --rm -i ghcr.io/ibm/fast-time-server:latest -transport=stdio" \
--expose-sse \
--port 8003
Or using the official mcp-server-git using uvx:
pip install uv # to install uvx, if not already installed
python3 -m mcpgateway.translate --stdio "uvx mcp-server-git" --expose-sse --port 9000
Alternative: running the local binary
cd mcp-servers/go/fast-time-server; make build
python3 -m mcpgateway.translate --stdio "./dist/fast-time-server -transport=stdio" --expose-sse --port 8002
NEW: Expose via multiple protocols simultaneously!
python3 -m mcpgateway.translate \
--stdio "uvx mcp-server-git" \
--expose-sse \
--expose-streamable-http \
--port 9000
Now accessible via both /sse (SSE) and /mcp (streamable HTTP) endpoints
2️⃣ Register it with the gateway
curl -s -X POST -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"fast_time","url":"http://localhost:8003/sse"}' \
http://localhost:4444/gateways
3️⃣ Verify tool catalog
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" http://localhost:4444/tools | jq
4️⃣ Create a virtual server bundling those tools. Use the ID of tools from the tool catalog (Step #3) and pass them in the associatedTools list.
curl -s -X POST -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"server":{"name":"time_server","description":"Fast time tools","associated_tools":[]}}' \
http://localhost:4444/servers | jq
Example curl
curl -s -X POST -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"server":{"name":"time_server","description":"Fast time tools","associated_tools":["6018ca46d32a4ac6b4c054c13a1726a2"]}}' \
http://localhost:4444/servers | jq
5️⃣ List servers (should now include the UUID of the newly created virtual server)
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" http://localhost:4444/servers | jq
6️⃣ Client HTTP endpoint. Inspect it interactively with the MCP Inspector CLI (or use any MCP client)
npx -y @modelcontextprotocol/inspector
Transport Type: Streamable HTTP, URL: http://localhost:4444/servers/UUID_OF_SERVER_1/mcp, Header Name: "Authorization", Bearer Token
🖧 Using the stdio wrapper (mcpgateway-wrapper)```bash
export MCP_AUTH="Bearer ${MCPGATEWAY_BEARER_TOKEN}"
export MCP_SERVER_URL=http://localhost:4444/servers/UUID_OF_SERVER_1/mcp
python3 -m mcpgateway.wrapper # Ctrl-C to exit
你也可以用它运行 uv 或者在Docker/Podman内部-请参阅 容器 上面的部分。
在MCP检查器中,定义 MCP_AUTH 和 MCP_SERVER_URL env变量,然后选择 python3 作为命令,以及 -m mcpgateway.wrapper 作为论据。```bash
echo $PWD/.venv/bin/python3 # Using the Python3 full path ensures you have a working venv
export MCP_SERVER_URL='http://localhost:4444/servers/UUID_OF_SERVER_1/mcp'
export MCP_AUTH="Bearer ${MCPGATEWAY_BEARER_TOKEN}"
npx -y @modelcontextprotocol/inspector
或
将url和auth作为参数传递(无需设置环境变量)```bash
npx -y @modelcontextprotocol/inspector
command as `python`
Arguments as `-m mcpgateway.wrapper --url "http://localhost:4444/servers/UUID_OF_SERVER_1/mcp" --auth "Bearer "`
使用MCP客户端(如Claude)和stdio时:```json
{
"mcpServers": {
"mcpgateway-wrapper": {
"command": "python",
"args": ["-m", "mcpgateway.wrapper"],
"env": {
"MCP_AUTH": "Bearer your-token-here",
"MCP_SERVER_URL": "http://localhost:4444/servers/UUID_OF_SERVER_1",
"MCP_TOOL_CALL_TIMEOUT": "120"
}
}
}
}
______________________________________________________________________
## 快速入门-容器
使用GHCR的官方OCI图像 **码头工人** *或* **波德曼**.
请注意:目前arm64在生产环境中不受支持。如果你正在使用苹果Silicon芯片(M1、M2等)在MacOS上运行,你可以使用Rosetta运行容器,也可以通过PyPi安装。
### 🚀 快速入门-Docker Compose
在30秒内使用PostgreSQL和Redis运行一个完整的堆栈:```bash
# Clone and start the stack
git clone https://github.com/IBM/mcp-context-forge.git
cd mcp-context-forge
# Start with PostgreSQL (recommended for production)
docker compose up -d
# Check status
docker compose ps
# View logs
docker compose logs -f gateway
# Access Admin UI: http://localhost:8080/admin (login with PLATFORM_ADMIN_EMAIL/PASSWORD)
# Generate API token
docker compose exec gateway python3 -m mcpgateway.utils.create_jwt_token \
--username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes
您将获得:
- 🗄️ PostgreSQL -具有55+个表的生产就绪数据库
- 🚀 ContextForge -带管理UI的全功能网关
- 📊 瑞迪斯 -高性能缓存和会话存储
- 🔧 管理工具 -pgAdmin,Redis Insight用于数据库管理
- 🌐 Nginx代理 -在端口8080上缓存反向代理
启用HTTPS(可选):```bash
Start with TLS enabled (auto-generates self-signed certs)
make compose-tls
Access via HTTPS: https://localhost:8443/admin
Or bring your own certificates:
Unencrypted key:
mkdir -p certs
cp your-cert.pem certs/cert.pem && cp your-key.pem certs/key.pem
make compose-tls
Passphrase-protected key:
mkdir -p certs
cp your-cert.pem certs/cert.pem && cp your-encrypted-key.pem certs/key-encrypted.pem
echo "KEY_FILE_PASSWORD=your-passphrase" >> .env
make compose-tls
### ☸️ 快速入门-Helm(Kubernetes)
部署到具有企业级功能的Kubernetes:```bash
# Add Helm repository (when available)
# helm repo add mcp-context-forge https://ibm.github.io/mcp-context-forge
# helm repo update
# For now, use local chart
git clone https://github.com/IBM/mcp-context-forge.git
cd mcp-context-forge/charts/mcp-stack
# Install with PostgreSQL (default)
helm install mcp-gateway . \
--set mcpContextForge.secret.PLATFORM_ADMIN_EMAIL=admin@yourcompany.com \
--set mcpContextForge.secret.PLATFORM_ADMIN_PASSWORD=changeme \
--set mcpContextForge.secret.JWT_SECRET_KEY=your-secret-key
# Check deployment status
kubectl get pods -l app.kubernetes.io/name=mcp-context-forge
# Port forward to access Admin UI
kubectl port-forward svc/mcp-gateway-mcp-context-forge 4444:80
# Access: http://localhost:4444/admin
# Generate API token
kubectl exec deployment/mcp-gateway-mcp-context-forge -- \
python3 -m mcpgateway.utils.create_jwt_token \
--username admin@yourcompany.com --exp 10080 --secret your-secret-key
> SSRF注意:Helm默认为严格的SSRF设置(SSRF_ALLOW_PRIVATE_NETWORKS=false).
> 如果您在集群工具URL中注册(例如快速时间或快速测试服务),
> 只允许您的集群CIDR通过 mcpContextForge.config.SSRF_ALLOWED_NETWORKS 或者,
> 对于仅本地基准设置,临时设置 SSRF_ALLOW_PRIVATE_NETWORKS=true.
> 看 docs/docs/manage/configuration.md#ssrf-protection 和 docs/docs/deployment/helm.md.
企业特性:
- 🔄 自动缩放 -具有CPU/内存目标的HPA
- 🗄️ 数据库选择 -PostgreSQL(prod),SQLite(dev)
- 📊 可观测性 -Prometheus指标,OpenTetry跟踪
- 🔒 安全 -RBAC、网络策略、秘密管理
- 🚀 高可用性 -使用Redis集群的多副本部署
- 📈 监控 -内置Grafana仪表板和警报
🐳 Docker(单容器)```bash
docker run -d --name mcpgateway \
-p 4444:4444 \
-e MCPGATEWAY_UI_ENABLED=true \
-e MCPGATEWAY_ADMIN_API_ENABLED=true \
-e HOST=0.0.0.0 \
-e JWT_SECRET_KEY=my-test-key-but-now-longer-than-32-bytes \
-e AUTH_REQUIRED=true \
-e PLATFORM_ADMIN_EMAIL=admin@example.com \
-e PLATFORM_ADMIN_PASSWORD=changeme \
-e PLATFORM_ADMIN_FULL_NAME="Platform Administrator" \
-e DATABASE_URL=sqlite:///./mcp.db \
-e SECURE_COOKIES=false \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
Tail logs and generate API key
docker logs -f mcpgateway
docker run --rm -it ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3 \
python3 -m mcpgateway.utils.create_jwt_token --username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes
浏览至 **http://localhost:4444/admin** 并使用登录 `PLATFORM_ADMIN_EMAIL` / `PLATFORM_ADMIN_PASSWORD`.
Advanced: Persistent storage, host networking, airgapped
**持久化SQLite数据库:**```bash
mkdir -p $(pwd)/data && touch $(pwd)/data/mcp.db && chmod 777 $(pwd)/data
docker run -d --name mcpgateway --restart unless-stopped \
-p 4444:4444 -v $(pwd)/data:/data \
-e DATABASE_URL=sqlite:////data/mcp.db \
-e MCPGATEWAY_UI_ENABLED=true -e MCPGATEWAY_ADMIN_API_ENABLED=true \
-e HOST=0.0.0.0 -e JWT_SECRET_KEY=my-test-key-but-now-longer-than-32-bytes \
-e PLATFORM_ADMIN_EMAIL=admin@example.com -e PLATFORM_ADMIN_PASSWORD=changeme \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
主机联网 (访问本地MCP服务器):```bash
docker run -d --name mcpgateway --network=host \
-v $(pwd)/data:/data -e DATABASE_URL=sqlite:////data/mcp.db \
-e MCPGATEWAY_UI_ENABLED=true -e HOST=0.0.0.0 -e PORT=4444 \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
**气隙部署** (无互联网):```bash
docker build -f Containerfile.lite -t mcpgateway:airgapped .
docker run -d --name mcpgateway -p 4444:4444 \
-e MCPGATEWAY_UI_AIRGAPPED=true -e MCPGATEWAY_UI_ENABLED=true \
-e HOST=0.0.0.0 -e JWT_SECRET_KEY=my-test-key-but-now-longer-than-32-bytes \
mcpgateway:airgapped
🦭 波德曼(无根友好型)```bash
podman run -d --name mcpgateway \
-p 4444:4444 -e HOST=0.0.0.0 -e DATABASE_URL=sqlite:///./mcp.db \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
Advanced: Persistent storage, host networking
**持久化SQLite:**```bash
mkdir -p $(pwd)/data && chmod 777 $(pwd)/data
podman run -d --name mcpgateway --restart=on-failure \
-p 4444:4444 -v $(pwd)/data:/data \
-e DATABASE_URL=sqlite:////data/mcp.db \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
主机网络:```bash
podman run -d --name mcpgateway --network=host \
-v $(pwd)/data:/data -e DATABASE_URL=sqlite:////data/mcp.db \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3
______________________________________________________________________
✏️ Docker/Podman tips
- **.env文件** -把所有的 `-e FOO=` 将行放入文件中,并替换为 `--env-file .env`。请参阅提供的 .env.示例 以供参考。
- **固定标签** -使用明确的版本(例如。 `1.0.0-RC-3`)而不是 `latest` 用于可重复构建。
- **JWT代币** -在正在运行的容器中生成一个:```bash
docker exec mcpgateway python3 -m mcpgateway.utils.create_jwt_token --username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes
- 升级 -停止、删除并重新运行
-v $(pwd)/data:/data坐骑;您的数据库和配置保持不变。
🚑 Smoke-test the running container```bash
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
http://localhost:4444/health | jq
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
http://localhost:4444/tools | jq
curl -s -H "Authorization: Bearer $MCPGATEWAY_BEARER_TOKEN" \
http://localhost:4444/version | jq
______________________________________________________________________
🖧 Running ContextForge stdio wrapper
这 `mcpgateway.wrapper` 允许您通过以下方式连接到网关 **标准** 同时保持JWT身份验证。您应该从MCP客户端运行此程序。以下示例仅用于测试。```bash
# Set environment variables
export MCPGATEWAY_BEARER_TOKEN=$(python3 -m mcpgateway.utils.create_jwt_token --username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes)
export MCP_AUTH="Bearer ${MCPGATEWAY_BEARER_TOKEN}"
export MCP_SERVER_URL='http://localhost:4444/servers/UUID_OF_SERVER_1/mcp'
export MCP_TOOL_CALL_TIMEOUT=120
export MCP_WRAPPER_LOG_LEVEL=DEBUG # or OFF to disable logging
docker run --rm -i \
-e MCP_AUTH=$MCP_AUTH \
-e MCP_SERVER_URL=http://host.docker.internal:4444/servers/UUID_OF_SERVER_1/mcp \
-e MCP_TOOL_CALL_TIMEOUT=120 \
-e MCP_WRAPPER_LOG_LEVEL=DEBUG \
ghcr.io/ibm/mcp-context-forge:1.0.0-RC-3 \
python3 -m mcpgateway.wrapper
快速入门:VS代码开发容器
克隆仓库并在VS Code中打开——它将检测 .devcontainer 并提示 “在容器中重新打开”容器包含Python 3.11、Docker CLI和所有项目依赖项。
有关详细的设置、工作流和GitHub代码空间说明,请参阅 开发人员入职培训.
安装```bash
make venv install-dev # create .venv + install deps + build Admin UI
make serve # gunicorn on :4444
Rust工作区注释:
- 工作区拥有的Rust板条箱位于 `crates/` 被树根拾起 `Cargo.toml` 通过 `crates/*`.
- 跑 `cargo build`, `cargo test`,以及 `cargo check` 从repo根目录覆盖共享工作区。
- `mcp-servers/rust/` 故意留在共享工作区之外,并单独管理。
- `make venv install-dev` 创建根 `.venv`,它也被工作区的PyO3/maturin构建重用。
Alternative: UV or pip```bash
# UV (faster)
uv venv && source .venv/bin/activate
uv pip install -e '.[dev]'
# pip
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
PostgreSQL adapter setup
安装 psycopg PostgreSQL驱动程序:```bash
Install system dependencies first
Debian/Ubuntu: sudo apt-get install libpq-dev
macOS: brew install libpq
uv pip install 'psycopg[binary]' # dev (pre-built wheels)
or: uv pip install 'psycopg[c]' # production (requires compiler)
连接URL格式:```bash
DATABASE_URL=postgresql+psycopg://user:password@localhost:5432/mcp
快速Postgres容器:```bash
docker run --name mcp-postgres \
-e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=mysecretpassword \
-e POSTGRES_DB=mcp -p 5432:5432 -d postgres
______________________________________________________________________
## 升级
有关升级说明、迁移指南和回滚过程,请参阅:
- **升级指南** --一般升级程序
- **更改日志.md** --版本历史和重大更改
______________________________________________________________________
## 配置
> ⚠️ 如有需要 `.env` 变量丢失或无效,网关将在启动时快速失败,并通过Pydantic出现验证错误。
复制提供的 .env.示例 到 `.env` 并更新下面的安全敏感值。
### 🔐 必需:使用前更改
这些变量具有不安全的默认值 **必须更改** 在生产部署之前:
|变量|描述|默认值|需要操作|
|----------|-------------|---------|-----------------|
| `JWT_SECRET_KEY` |用于签名JWT令牌的密钥(32+个字符)| `my-test-key-but-now-longer-than-32-bytes` |生成方式 `openssl rand -hex 32` |
| `AUTH_ENCRYPTION_SECRET` |用于加密存储凭据的密码| `my-test-salt` |生成方式 `openssl rand -hex 32` |
| `BASIC_AUTH_USER` |HTTP基本身份验证的用户名| `admin` |生产变更|
| `BASIC_AUTH_PASSWORD` |HTTP基本身份验证密码| `changeme` |设置强密码|
| `PLATFORM_ADMIN_EMAIL` |引导管理员用户的电子邮件| `admin@example.com` |使用真实的管理员电子邮件|
| `PLATFORM_ADMIN_PASSWORD` |引导管理员用户的密码| `changeme` |设置强密码|
| `PLATFORM_ADMIN_FULL_NAME` |引导管理员的显示名称| `Admin User` |设置管理员名称|
### 🔒 安全默认值(默认安全)
默认情况下,这些设置是为了安全而启用的,只有为了向后兼容性而禁用:
|变量|描述|默认值|
|----------|-------------|---------|
| `REQUIRE_JTI` |要求在令牌中声明JTI以获得撤销支持| `true` |
| `REQUIRE_TOKEN_EXPIRATION` |要求在令牌中声明exp| `true` |
| `PUBLIC_REGISTRATION_ENABLED` |允许公共用户自行注册| `false` |
### 🛡️ 内容安全性
内容大小限制可防止DoS攻击并确保系统稳定性:
|变量|描述|默认值|
|----------|-------------|---------|
| `CONTENT_MAX_RESOURCE_SIZE` |最大资源内容大小(字节)| `102400` (100KB)|
| `CONTENT_MAX_PROMPT_SIZE` |最大提示模板大小(字节)| `10240` (10KB)|
**注:** 大小限制仅适用于新的创建/更新操作。现有内容不会进行追溯验证。
### 🌐 UAID跨网关路由安全
#### UAID安全配置
**生产要求:**
跨网关UAID路由需要明确的安全配置:
1. **配置域允许列表:**```bash
UAID_ALLOWED_DOMAINS=["gateway1.example.com", "gateway2.example.com"]
- 确保JWT信任:
- 两个网关必须信任同一个JWT发行者
- 选项A:共享密钥(相同
JWT_SECRET_KEY在所有网关上) - 选项B:联合SSO(谷歌、GitHub、Entra ID)
- 启用身份验证:```bash
AUTH_REQUIRED=true
UAID_FORWARD_AUTH=true
**身份验证流程:**
跨网关调用通过以下方式转发用户的承载令牌 `Authorization` 头球
远程网关通过现有的身份验证中间件验证令牌,保留RBAC上下文。
**安全功能:**
- ✅ 默认关闭失败:空分配列表阻止所有跨网关路由
- ✅ 承载令牌转发:跨跃点保留用户身份验证
- ✅ 审计跟踪:在标头中跟踪源网关和用户
- ✅ 清除错误消息:在启动和运行时发现配置错误
**故障排除:**
- **“UAID_ALLOWED_DOMAINS未配置”错误:** 将受信任的域添加到.env中的allowlist
- **来自远程网关的401/403:** 验证两个网关是否信任同一JWT颁发者
- **“在没有身份验证令牌的情况下继续”警告:** 检查身份验证中间件提取令牌到 `request.state.bearer_token`
有关详细的安全架构,请参阅 `docs/security/uaid-cross-gateway-auth.md`.
### ⚙️ 项目默认值(开发设置)
这些值与代码默认值不同,以提供可工作的本地/dev设置:
|变量|描述|默认值|
|----------|-------------|---------|
| `HOST` |绑定地址| `0.0.0.0` |
| `MCPGATEWAY_UI_ENABLED` |启用管理UI仪表板| `true` |
| `MCPGATEWAY_ADMIN_API_ENABLED` |启用管理API终结点| `true` |
| `DATABASE_URL` |SQLAlchemy连接URL| `sqlite:///./mcp.db` |
| `SECURE_COOKIES` |设置 `false` 适用于HTTP(非HTTPS)开发| `false` |
### 📚 完整配置参考
有关按类别(身份验证、缓存、SSO、可观察性等)组织的300多个环境变量的完整列表,请参阅 **配置参考**.
______________________________________________________________________
## 跑步
### 快速参考
|命令|服务器|端口|数据库|用例|
|---------|--------|------|----------|----------|
| `make dev` |乌维科恩| **8000** |SQLite |开发(单实例,自动重新加载)|
| `make serve` |古尼科恩| **4444** |SQLite |生产单节点(多工人)|
| `make serve-ssl` |古尼科恩| **4444** |SQLite |使用HTTPS的生产单节点|
| `make compose-up` |Docker编写+Nginx| **8080** |PostgreSQL+Redis |全栈(3个副本,负载均衡)|
| `make compose-sso` |Docker编写+密钥斗篷| **8080 / 8180** |PostgreSQL+Redis |本地SSO测试(Keycloak配置文件)|
| `make testing-up` |Docker编写+Nginx| **8080** |PostgreSQL+Redis |测试环境|
### 开发服务器(Uvicorn)```bash
make dev # Uvicorn on :8000 with auto-reload and SQLite
# or
./run.sh --reload --log debug --workers 2
> run.sh 是一个包装物 uvicorn 负载 .env,支持重新加载,并将参数传递给服务器。
关键标志:
| 标志 | 目的 | 示例 |
|---|---|---|
-e, --env FILE |
加载env文件 | --env prod.env |
-H, --host |
绑定地址 | --host 127.0.0.1 |
-p, --port |
监听端口 | --port 8080 |
-w, --workers |
炮灰工人 | --workers 4 |
-r, --reload |
自动重新加载 | --reload |
生产服务器(Gunicorn)```bash
make serve # Gunicorn on :4444 with multiple workers
make serve-ssl # Gunicorn behind HTTPS on :4444 (uses ./certs)
### Docker Compose(全栈)```bash
make compose-up # Start full stack: PostgreSQL, Redis, 3 gateway replicas, Nginx on :8080
make compose-sso # Start SSO stack with Keycloak on :8180
make sso-test-login # Run SSO smoke checks (providers + login URL + test users)
make compose-logs # Tail logs from all services
make compose-down # Stop the stack
手册(Uvicorn)```bash
uvicorn mcpgateway.main:app --host 0.0.0.0 --port 4444 --workers 4
______________________________________________________________________
## 云部署
ContextForge可以部署到任何主要的云平台:
|平台|指南|
|----------|-------|
| **亚马逊云服务** | ECS/EKS部署 |
| **Azure** | AKS部署 |
| **谷歌云** | 云运行 |
| **IBM云** | 代码引擎 |
| **Kubernetes** | Helm图表 |
| **OpenShift** | OpenShift部署 |
有关全面的部署指南,请参阅 **部署文档**.
______________________________________________________________________
## API 参考
交互式API文档在服务器运行时可用:
- **Swagger用户界面** -直接在浏览器中尝试API调用
- **ReDoc** --浏览完整的端点引用
**快速身份验证:**```bash
# Generate a JWT token
export TOKEN=$(python3 -m mcpgateway.utils.create_jwt_token \
--username admin@example.com --exp 10080 --secret my-test-key-but-now-longer-than-32-bytes)
# Test API access
curl -H "Authorization: Bearer $TOKEN" http://localhost:4444/health
有关涵盖所有端点的全面curl示例,请参阅 API使用指南.
测试```bash
make test # Run unit tests
make lint # Run all linters
make doctest # Run doctests
make coverage # Generate coverage report
看 Doctest覆盖指南 有关文档测试的详细信息。
______________________________________________________________________
## 项目结构```
mcpgateway/ # Core FastAPI application
├── main.py # Entry point
├── config.py # Pydantic Settings configuration
├── db.py # SQLAlchemy ORM models
├── schemas.py # Pydantic validation schemas
├── services/ # Business logic layer (50+ services)
├── routers/ # HTTP endpoint definitions
├── middleware/ # Cross-cutting concerns
└── transports/ # SSE, WebSocket, stdio, streamable HTTP
tests/ # Test suite (7,000+ tests)
docs/docs/ # Full documentation (MkDocs)
charts/ # Kubernetes/Helm charts
plugins/ # Plugin framework and implementations
mcp-servers/ # Sample/test MCP servers (see note below)
> 注: 这 mcp-servers/ 目录包含 不支持的示例和测试服务器,
> 大多数来自社区贡献,用于演示和整合
> 仅用于测试目的。它们通常缺乏会话管理、持久状态等,
> 多租户、身份验证和其他生产问题。他们没有通过
> 与核心ContextForge代码库相同的审查、测试和安全严谨性,以及
> 不应在生产中运行.
>
> 安全: 切勿直接在本地文件系统上运行不受信任的MCP服务器。
> 始终使用沙盒、容器或微型虚拟机(例如gVisor、Firecracker)
> 有限的能力。在注册任何远程MCP服务器时,请务必谨慎,
> 包括公共目录中的服务器--执行您自己的安全评估
> 在授予网关访问权限之前。
有关完整结构,请参见 贡献.md 或奔跑 tree -L 2.
发展```bash
make dev # Dev server with auto-reload (:8000)
make test # Run test suite
make lint # Run all linters
make coverage # Generate coverage report
```
跑 make 查看所有可用目标。
有关开发工作流程,请参阅:
- 开发人员工作站设置
- 建筑与包装
故障排除
常见问题和解决方案:
| 问题 | 快速修复 |
|---|---|
| macOS上的SQLite“磁盘I/O错误” | 避免iCloud同步目录;使用 ~/mcp-context-forge/data |
| WSL2上无法访问端口4444 | 在Docker桌面中配置WSL集成 |
| 网关立即退出 | 复制 .env.example 到 .env 并配置所需的变量 |
ModuleNotFoundError |
快跑 make install-dev |
有关详细的故障排除指南,请参阅 故障排除文档.
贡献
- 分叉仓库,创建一个功能分支。
- 跑
make lint并修复任何问题。 - 保持
make test绿色。 - 打开一个带有签名承诺的PR(
git commit -s).
看 贡献.md 获取完整指南和 问题指南#2502 了解如何归档错误、请求功能和查找要处理的问题。
更新日志
完整的更新日志可以在这里找到: 更改日志.md
许可证
根据 Apache许可证2.0 -看 许可证
核心作者和维护者
- 米哈伊·克里维蒂 -杰出工程师,Agent AI
特别感谢我们的贡献者帮助我们改进ContextForge:
