Gate MCP tool calls on human approval

This commit is contained in:
github-ops
2026-06-24 11:42:16 +00:00
parent 8a1cc1746f
commit 0d193b84dd
2 changed files with 224 additions and 7 deletions
@@ -19,9 +19,9 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
ApprovalRequestId, ApprovalRequestStatus, ExecutionConfig, HttpMethod, Operation,
OperationApprovalRiskLevel, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId,
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
WorkspaceId,
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription, WorkspaceId,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::{
@@ -625,6 +625,102 @@ async fn approval_key_lists_and_decides_pending_requests() {
assert!(pending_after["items"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn tool_call_with_approval_policy_creates_pending_request() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let mut operation = test_operation(&upstream_base_url, "crm_requires_human_approval");
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
required: true,
risk_level: OperationApprovalRiskLevel::Dangerous,
confirmation_title: "Подтвердите создание лида".to_owned(),
confirmation_body_template: "Проверьте email перед отправкой в CRM.".to_owned(),
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
});
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-gated").await;
let api_key = create_platform_api_key(
&registry,
"sales-gated",
"mcp-gated",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let approval_key =
create_approval_platform_api_key(&registry, "sales-gated", "approval-gated").await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-gated");
let initialized_session = initialize_session(&client, &mcp_url, &api_key).await;
let tool_result = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&initialized_session),
json!({
"jsonrpc": "2.0",
"id": 9,
"method": "tools/call",
"params": {
"name": "crm_requires_human_approval",
"arguments": {
"email": "ada@example.com"
}
}
}),
)
.await;
assert_eq!(
tool_result["result"]["structuredContent"]["status"],
"approval_required"
);
assert_eq!(tool_result["result"]["isError"], false);
let approval_id = tool_result["result"]["structuredContent"]["approval_id"]
.as_str()
.unwrap();
assert!(approval_id.starts_with("approval_"));
let approvals_url = format!("{}/approvals", agent_mcp_url(&base_url, "sales-gated"));
let pending = client
.get(&approvals_url)
.header(header::AUTHORIZATION, format!("Bearer {approval_key}"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
assert_eq!(pending["items"].as_array().unwrap().len(), 1);
assert_eq!(pending["items"][0]["approval"]["id"], approval_id);
assert_eq!(
pending["items"][0]["approval"]["request_payload"]["email"],
"ada@example.com"
);
}
#[tokio::test]
async fn rejects_tool_call_with_read_only_platform_api_key() {
let registry = test_registry().await;