具有Stage0授权的MCP服务器
一个模型上下文协议(MCP)服务器,演示如何使用Stage0运行时策略验证来保护工具调用。此示例显示了如何防止AI代理在未经授权的操作发生之前执行这些操作。
问题场景
AI代理可以悄无声息地从安全操作升级到危险操作:
- 研究→ 出版物:代理人研究一个主题,然后未经批准发表研究结果
- 分析→ 部署:代理调查事件,然后自主部署更改
- 起草→ 执行:代理起草内容,然后执行发布工作流
- 调查→ Loop:代理不断重试失败的操作,消耗资源
Stage0解决了这个问题 通过在动作发生之前验证每个执行意图,返回外部判断: ALLOW, DENY,或 DEFER.
Stage0适合在哪里
┌─────────────────────────────────────────────────────────────────┐
│ AI Agent Runtime │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ LLM │───▶│ Tools │───▶│ Actions │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Stage0 │ ◀── External Policy Authority │
│ │ (Guard Layer) │ │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ ALLOW / DENY / │ │
│ │ DEFER │ │
│ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────┘Stage0位于工具调用和执行之间 -它不是代理人的一部分。代理无法自行批准操作。所有执行意图必须通过Stage0进行验证 /check 终点。
为什么是服务器端授权?
一个常见的错误是将授权放在代理的提示中(例如,“不允许部署”)。这种方法存在严重缺陷:
| 基于提示的授权 | 服务器端授权 |
|---|---|
| 代理可以忽略指令 | 代理 不能 绕过服务器检查 |
| 没有决策的审计跟踪 | 每次检查都记录了 request_id |
| 不同的代理=不同的行为 | 所有客户端的一致执行 |
| 可以被用户提示覆盖 | 由外部策略机构强制执行 |
| 没有加密策略证明 | policy_version 确保再现性 |
授权边界必须在服务器端工具处理程序中,不在提示中。这个存储库正好演示了这种模式。
快速开始
先决条件
- Node.js 18+
- npm或pnpm
- (可选)来自的Stage0 API密钥 信号脉冲
安装
# Clone the repository
git clone https://github.com/Starlight143/mcp-server-stage0-authorization.git
cd mcp-server-stage0-authorization
# Install dependencies
npm install
# Copy environment configuration
cp .env.example .env
# Build the TypeScript
npm run build配置API密钥(可选)
编辑 .env 并添加您的Stage0 API密钥:
STAGE0_API_KEY=your_api_key_here
STAGE0_BASE_URL=https://api.signalpulse.org备注:在没有API密钥的情况下,服务器使用模拟的Stage0响应。这对于测试集成流非常有用。
运行演示
# Demo 1: ALLOW scenario - research tool call
npm run demo:allow
# Demo 2: DENY scenario - publish tool call
npm run demo:deny
# Demo 3: DEFER scenario - loop threshold exceeded
npm run demo:defer预期输出
允许示例(研究)
======================================================================
DEMO: ALLOW Scenario - Research Tool Call
======================================================================
Scenario: An agent wants to research a topic and return
informational summary. This is a low-risk operation.
Calling Stage0 to check authorization...
Response from Stage0:
----------------------------------------------------------------------
Verdict: ALLOW
Decision: GO
Reason: Informational operation with no high-risk side effects
Request ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890
Policy Version: simulated-v1.0.0
Risk Score: 15
High Risk: false
----------------------------------------------------------------------
✅ TOOL CALL ALLOWED
The agent can proceed to execute the research tool.
This is safe because:
- No side effects (publish, deploy, etc.)
- Informational operation only
- No guardrail violationsDENY示例(发布)
======================================================================
DEMO: DENY Scenario - Publish Tool Call
======================================================================
Scenario: An agent attempts to publish content to a public
channel without proper authorization. This is a high-risk
operation that should be blocked.
Calling Stage0 to check authorization...
Response from Stage0:
----------------------------------------------------------------------
Verdict: DENY
Decision: NO_GO
Reason: HIGH severity: SIDE_EFFECTS_NEED_GUARDRAILS - 'publish'
side effect requires approval guardrails
Request ID: b2c3d4e5-f6a7-8901-bcde-f12345678901
Policy Version: simulated-v1.0.0
Risk Score: 85
High Risk: true
Issues detected:
[HIGH] SIDE_EFFECTS_NEED_GUARDRAILS: Side effects [publish] require
approval guardrails
----------------------------------------------------------------------
⛔ TOOL CALL BLOCKED
The agent is NOT allowed to execute this tool.
This is correct because:
- "publish" side effect requires approval guardrails
- No human approval was provided
- Publishing without review can cause trust/compliance issuesDEFER示例(模糊请求)
======================================================================
DEMO: DEFER Scenario - Unclear/Vague Request
======================================================================
Scenario: An agent receives a vague request without clear
success criteria or value proposition. Stage0 DEFERs to
request more context before proceeding.
Calling Stage0 to check authorization...
Response from Stage0:
----------------------------------------------------------------------
Verdict: DEFER
Decision: DEFER
Reason: UNCLEAR_VALUE_SIGNAL: Task appears under-specified
for reliable value delivery.
Request ID: c3d4e5f6-a7b8-9012-cdef-123456789012
Policy Version: simulated-v1.0.0
Risk Score: 35
Clarifying questions:
? What is the specific outcome you want to achieve?
? What constraints or requirements should be considered?
----------------------------------------------------------------------
⏸️ TOOL CALL DEFERRED
The agent should NOT proceed automatically.
Human review is required because:
- Request is too vague to evaluate value
- Success criteria are unclear
- More context is needed before execution备注:实际判决取决于您的Stage0计划和策略配置:
- 专业计划 可能会回来
DEFER对于模糊的请求clarifying_questions - 免费/新手计划 可能会回来
ALLOW澄清问题或DENY取决于策略设置 - 模拟响应(没有API密钥)显示了预期的
DEFER行为
哪里 request_id 和 policy_version 出现
每个阶段0 /check 响应包括:
| 字段 | 描述 | 位置 |
|---|---|---|
request_id | 此授权请求的唯一标识符 | 用于审核日志、调试和可追溯性 |
policy_version | 用于评估的策略包版本 | 用于合规性和可重复性 |
这些字段在API响应中返回:
{
"verdict": "DENY",
"decision": "NO_GO",
"reason": "...",
"request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"policy_version": "v1.2.3",
"risk_score": 85,
"high_risk": true
}作为MCP服务器运行
要将其用作Claude Desktop或其他MCP客户端的MCP服务器:
1.构建服务器
npm run build2.添加到Claude桌面配置
编辑Claude Desktop配置文件:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - 视窗:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"stage0-authorization": {
"command": "node",
"args": ["/dist/index.js"],
"env": {
"STAGE0_API_KEY": "your_api_key_here",
"STAGE0_BASE_URL": "https://api.signalpulse.org"
}
}
}
}替换 `` 使用克隆存储库的实际路径。
3.可用工具
| 工具 | 描述 | 风险等级 | 情境感知 |
|---|---|---|---|
research-topic | 研究和总结一个主题 | 低 | 否 |
publish-content | 将内容发布到频道 | 高 | 否 |
deploy-changes | 部署到环境 | 高 | 是(actor_role) |
managed-deploy | 使用完全授权上下文进行部署 | 高 | 是(所有字段) |
retry-workflow | 重试失败的工作流 | 中等 | 是(retry_count) |
check-authorization | 检查是否授权操作 | N/A | 可选 |
授权上下文
这 managed-deploy 该工具演示了应从上游传递的四个关键上下文字段:
| 字段 | 描述 | 示例值 |
|---|---|---|
actor_role | 执行行动的实体的作用 | admin, developer, viewer |
approval_status | 行动是否已获批准 | approved, pending, none |
environment | 目标环境 | production, staging, development |
resource_scope | 受影响的资源范围 | all, team-a, service-x |
示例:基于角色的部署控制
const context: Stage0Context = {
actor_role: 'developer', // Who is performing the action
approval_status: 'pending', // Has this been approved?
environment: 'production', // Where is this deploying?
resource_scope: 'team-a', // What resources are affected?
};
const response = await stage0.checkGoal(
'Deploy authentication service to production',
{
sideEffects: ['deploy'],
context,
successCriteria: ['Deployment completes successfully'],
}
);此上下文启用以下策略规则:
viewerrole → 拒绝所有部署developerrole → 未经批准,允许分期生产,拒绝生产adminrole → 允许所有人approval_status: approved
集成指南
要将Stage0授权添加到MCP服务器,请执行以下操作:
基本模式
import { Stage0Client, Stage0Context } from './stage0-client.js';
const stage0 = new Stage0Client();
server.tool('my-tool', 'Description', schema, async (params) => {
// 1. Check authorization before execution
const response = await stage0.checkGoal(
'Description of what this tool does',
{
sideEffects: ['publish'],
successCriteria: ['Task completes successfully'],
constraints: ['approval_required'],
}
);
// 2. Handle the verdict
if (response.verdict === 'DENY') {
return {
content: [{ type: 'text', text: `Blocked: ${response.reason}` }],
};
}
if (response.verdict === 'DEFER') {
return {
content: [{ type: 'text', text: `Deferred: ${response.reason}` }],
};
}
// 3. Execute only if ALLOWED
const result = await doSomething(params);
return {
content: [{ type: 'text', text: result }],
};
});具有授权上下文
对于特权操作,从上游传递上下文:
server.tool('deploy-service', 'Deploy a service', {
serviceName: z.string(),
environment: z.enum(['staging', 'production']),
actorRole: z.enum(['admin', 'developer', 'viewer']),
}, async ({ serviceName, environment, actorRole }) => {
const context: Stage0Context = {
actor_role: actorRole,
environment,
approval_status: 'none', // Would come from your approval system
};
const response = await stage0.checkGoal(
`Deploy ${serviceName} to ${environment}`,
{
sideEffects: ['deploy'],
context,
successCriteria: ['Deployment succeeds'],
}
);
if (response.verdict !== 'ALLOW') {
return {
content: [{
type: 'text',
text: `⛔ ${response.verdict}: ${response.reason}\n\nRequest ID: ${response.request_id}`
}],
};
}
// Execute deployment
return executeDeployment(serviceName, environment);
});为什么这很重要
| 无Stage0 | 有Stage0 |
|---|---|
| Agent执行每个计划的步骤 | Agent在执行前进行验证 |
| 无声地升级为危险行为 | 外部机构检查意图 |
| 自行批准发布/部署 | 需要人工批准 |
| 失控重试循环 | 强制执行循环阈值 |
| 仅事后检测 | 执行前预防 |
运行测试
该存储库包括全面的烟雾测试:
# Run all tests (uses simulated mode without API key)
npm test
# Run tests with real API
STAGE0_API_KEY=your_api_key npm test
# Run tests in watch mode
npm run test:watch测试包括:
- 允许/拒绝/拒绝判决场景
- 上下文传播(
actor_role,environment等等) - 错误处理和边缘情况
- 真正的API集成(当提供API密钥时)
相关示例
此示例是SignalPulse框架快速入门集合的一部分:
- OpenAI代理SDK -
- LangGraph -
- MCP 服务器 - (此回购)
许可证
麻省理工学院
