Add approval mode selection
This commit is contained in:
@@ -125,6 +125,17 @@ pub(super) fn validate_approval_policy(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(message) = policy.elicitation_message.as_ref() {
|
||||
if message.chars().count() > 240 {
|
||||
return Err(ApiError::validation_with_context(
|
||||
"approval elicitation message must be at most 240 characters".to_owned(),
|
||||
json!({
|
||||
"field": "execution_config.approval_policy.elicitation_message",
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -133,7 +144,7 @@ mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crank_core::{
|
||||
ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy,
|
||||
ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy, OperationApprovalMode,
|
||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||
ResponseCachePolicy, RestTarget, Target,
|
||||
};
|
||||
@@ -272,10 +283,12 @@ mod tests {
|
||||
let mut config = cacheable_execution_config();
|
||||
config.approval_policy = Some(OperationApprovalPolicy {
|
||||
required: true,
|
||||
mode: OperationApprovalMode::Custom,
|
||||
risk_level: OperationApprovalRiskLevel::Dangerous,
|
||||
ttl_seconds: 300,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
||||
elicitation_message: None,
|
||||
});
|
||||
|
||||
validate_approval_policy(&config).unwrap();
|
||||
@@ -286,10 +299,12 @@ mod tests {
|
||||
let mut config = cacheable_execution_config();
|
||||
config.approval_policy = Some(OperationApprovalPolicy {
|
||||
required: true,
|
||||
mode: OperationApprovalMode::Custom,
|
||||
risk_level: OperationApprovalRiskLevel::Dangerous,
|
||||
ttl_seconds: 0,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
||||
elicitation_message: None,
|
||||
});
|
||||
|
||||
let error = validate_approval_policy(&config).unwrap_err();
|
||||
|
||||
@@ -21,7 +21,7 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
||||
ApprovalRequestId, ApprovalRequestStatus, ExecutionConfig, HttpMethod, InvocationSource,
|
||||
Operation, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
|
||||
Operation, OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
|
||||
OperationApprovalRiskLevel, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId,
|
||||
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
|
||||
WorkspaceId,
|
||||
|
||||
@@ -359,10 +359,12 @@ async fn tool_call_with_approval_policy_creates_pending_request() {
|
||||
let mut operation = test_operation(&upstream_base_url, "crm_requires_human_approval");
|
||||
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
|
||||
required: true,
|
||||
mode: OperationApprovalMode::Custom,
|
||||
risk_level: OperationApprovalRiskLevel::Dangerous,
|
||||
ttl_seconds: 300,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
||||
elicitation_message: None,
|
||||
});
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
@@ -445,3 +447,171 @@ async fn tool_call_with_approval_policy_creates_pending_request() {
|
||||
"ada@example.com"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn elicitation_approval_requires_client_capability() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let mut operation = test_operation(&upstream_base_url, "crm_requires_elicitation");
|
||||
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
|
||||
required: true,
|
||||
mode: OperationApprovalMode::Elicitation,
|
||||
risk_level: OperationApprovalRiskLevel::Normal,
|
||||
ttl_seconds: 300,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
||||
elicitation_message: Some("Подтвердите создание лида.".to_owned()),
|
||||
});
|
||||
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::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
publish_agent_with_bindings(
|
||||
®istry,
|
||||
"sales-elicitation-no-capability",
|
||||
vec![binding_for_operation(&operation)],
|
||||
)
|
||||
.await;
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
"sales-elicitation-no-capability",
|
||||
"mcp-elicitation-no-capability",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app(
|
||||
registry.clone(),
|
||||
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-elicitation-no-capability");
|
||||
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": 7,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "crm_requires_elicitation",
|
||||
"arguments": {
|
||||
"email": "ada@example.com"
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(tool_result["result"]["isError"], true);
|
||||
assert_eq!(
|
||||
tool_result["result"]["structuredContent"]["error"]["code"],
|
||||
"approval_elicitation_not_supported"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn elicitation_approval_uses_session_capability_without_approval_key() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let mut operation = test_operation(&upstream_base_url, "crm_requires_elicitation_supported");
|
||||
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
|
||||
required: true,
|
||||
mode: OperationApprovalMode::Elicitation,
|
||||
risk_level: OperationApprovalRiskLevel::Normal,
|
||||
ttl_seconds: 300,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
||||
elicitation_message: Some("Подтвердите создание лида.".to_owned()),
|
||||
});
|
||||
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::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
publish_agent_with_bindings(
|
||||
®istry,
|
||||
"sales-elicitation-supported",
|
||||
vec![binding_for_operation(&operation)],
|
||||
)
|
||||
.await;
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
"sales-elicitation-supported",
|
||||
"mcp-elicitation-supported",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app(
|
||||
registry.clone(),
|
||||
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-elicitation-supported");
|
||||
let initialized_session = initialize_session_with_capabilities(
|
||||
&client,
|
||||
&mcp_url,
|
||||
&api_key,
|
||||
json!({ "elicitation": {} }),
|
||||
)
|
||||
.await;
|
||||
|
||||
let tool_result = post_jsonrpc(
|
||||
&client,
|
||||
&mcp_url,
|
||||
&api_key,
|
||||
Some(&initialized_session),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 8,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "crm_requires_elicitation_supported",
|
||||
"arguments": {
|
||||
"email": "ada@example.com"
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(tool_result["result"]["isError"], false);
|
||||
assert_eq!(
|
||||
tool_result["result"]["structuredContent"]["status"],
|
||||
"elicitation_required"
|
||||
);
|
||||
assert_eq!(
|
||||
tool_result["result"]["structuredContent"]["message"],
|
||||
"Подтвердите создание лида."
|
||||
);
|
||||
assert_eq!(
|
||||
tool_result["result"]["structuredContent"]["payload_preview"]["email"],
|
||||
"ada@example.com"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -147,6 +147,15 @@ pub(super) async fn initialize_session(
|
||||
client: &reqwest::Client,
|
||||
mcp_url: &str,
|
||||
api_key: &str,
|
||||
) -> String {
|
||||
initialize_session_with_capabilities(client, mcp_url, api_key, json!({})).await
|
||||
}
|
||||
|
||||
pub(super) async fn initialize_session_with_capabilities(
|
||||
client: &reqwest::Client,
|
||||
mcp_url: &str,
|
||||
api_key: &str,
|
||||
capabilities: Value,
|
||||
) -> String {
|
||||
let initialize_response = client
|
||||
.post(mcp_url)
|
||||
@@ -157,7 +166,8 @@ pub(super) async fn initialize_session(
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2025-11-25"
|
||||
"protocolVersion": "2025-11-25",
|
||||
"capabilities": capabilities
|
||||
}
|
||||
}))
|
||||
.send()
|
||||
|
||||
@@ -689,6 +689,7 @@ async fn get_returns_not_found_for_expired_transport_session() {
|
||||
"2025-11-25",
|
||||
test_workspace_slug(),
|
||||
"sales-expired-session",
|
||||
false,
|
||||
OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(),
|
||||
Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()),
|
||||
)
|
||||
|
||||
@@ -114,6 +114,42 @@
|
||||
</label>
|
||||
|
||||
<div id="approval-config-fields" class="approval-config-fields" hidden>
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="approval-mode" data-i18n="wizard.approval.mode">Механизм подтверждения</label>
|
||||
<select id="approval-mode" class="form-select">
|
||||
<option value="custom" data-i18n="wizard.approval.mode.custom">Custom MCP Approval</option>
|
||||
<option value="elicitation" data-i18n="wizard.approval.mode.elicitation">MCP Elicitation</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="info-callout" id="approval-custom-info">
|
||||
<svg class="info-callout-icon" width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="var(--accent)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="8" cy="8" r="6.5"></circle>
|
||||
<path d="M8 11V8M8 5.5V5"></path>
|
||||
</svg>
|
||||
<div class="info-callout-body">
|
||||
<div class="info-callout-title" data-i18n="wizard.approval.custom_title">Custom MCP Approval</div>
|
||||
<div class="info-callout-text" data-i18n="wizard.approval.custom_body">Crank вернёт MCP-клиенту approval_required с approval_id, approval_url и ссылками approve/deny. Ваш MCP-клиент должен обработать этот ответ, показать пользователю подтверждение и отправить решение на endpoint подтверждения. Для endpoint-а подтверждения нужен отдельный ключ подтверждения агента.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="info-callout" id="approval-elicitation-info" hidden>
|
||||
<svg class="info-callout-icon" width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="var(--accent)" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="8" cy="8" r="6.5"></circle>
|
||||
<path d="M8 11V8M8 5.5V5"></path>
|
||||
</svg>
|
||||
<div class="info-callout-body">
|
||||
<div class="info-callout-title" data-i18n="wizard.approval.elicitation_title">MCP Elicitation</div>
|
||||
<div class="info-callout-text" data-i18n="wizard.approval.elicitation_body">Crank запросит подтверждение через стандартный MCP Elicitation. MCP-клиент должен поддерживать capability elicitation. Отдельный ключ подтверждения не используется: ответ пользователя возвращается по текущей MCP-сессии.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="approval-elicitation-message-group" hidden>
|
||||
<label class="form-label" for="approval-elicitation-message" data-i18n="wizard.approval.elicitation_message">Сообщение для MCP-клиента</label>
|
||||
<textarea id="approval-elicitation-message" class="form-textarea" rows="3" maxlength="240" data-i18n-ph="wizard.approval.elicitation_message_placeholder" placeholder="Подтвердите выполнение операции."></textarea>
|
||||
<div class="form-hint" data-i18n="wizard.approval.elicitation_message_hint">Короткое протокольное сообщение. Внешний вид окна подтверждения всё равно определяет MCP-клиент.</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="approval-ttl-seconds" data-i18n="wizard.approval.ttl">Сколько ждать подтверждение</label>
|
||||
<select id="approval-ttl-seconds" class="form-select">
|
||||
|
||||
@@ -598,6 +598,16 @@ var TRANSLATIONS = {
|
||||
'wizard.approval.subtitle': 'Enable this for actions that must not run without an explicit user decision.',
|
||||
'wizard.approval.required_label': 'Require confirmation before execution',
|
||||
'wizard.approval.required_desc': 'The MCP client receives a pending request, and the action runs only after confirmation through a separate approval endpoint.',
|
||||
'wizard.approval.mode': 'Confirmation mechanism',
|
||||
'wizard.approval.mode.custom': 'Custom MCP Approval',
|
||||
'wizard.approval.mode.elicitation': 'MCP Elicitation',
|
||||
'wizard.approval.custom_title': 'Custom MCP Approval',
|
||||
'wizard.approval.custom_body': 'Crank returns approval_required to the MCP client with approval_id, approval_url and approve/deny links. Your MCP client must handle this response, show confirmation to the user and send the decision to the approval endpoint. The approval endpoint requires a separate agent approval key.',
|
||||
'wizard.approval.elicitation_title': 'MCP Elicitation',
|
||||
'wizard.approval.elicitation_body': 'Crank asks for confirmation through standard MCP Elicitation. The MCP client must support the elicitation capability. No separate approval key is used: the user decision returns through the current MCP session.',
|
||||
'wizard.approval.elicitation_message': 'Message for the MCP client',
|
||||
'wizard.approval.elicitation_message_placeholder': 'Confirm operation execution.',
|
||||
'wizard.approval.elicitation_message_hint': 'Short protocol message. The MCP client still controls the confirmation UI.',
|
||||
'wizard.approval.ttl': 'How long to wait for confirmation',
|
||||
'wizard.approval.show_payload': 'Show request parameters',
|
||||
'wizard.approval.payload_mode': 'How to show parameters',
|
||||
@@ -1453,6 +1463,16 @@ var TRANSLATIONS = {
|
||||
'wizard.approval.subtitle': 'Включайте для действий, которые нельзя выполнять без явного решения пользователя.',
|
||||
'wizard.approval.required_label': 'Требовать подтверждение перед выполнением',
|
||||
'wizard.approval.required_desc': 'MCP клиент получит ожидающий запрос, а действие выполнится только после подтверждения через отдельный эндпоинт подтверждения.',
|
||||
'wizard.approval.mode': 'Механизм подтверждения',
|
||||
'wizard.approval.mode.custom': 'Custom MCP Approval',
|
||||
'wizard.approval.mode.elicitation': 'MCP Elicitation',
|
||||
'wizard.approval.custom_title': 'Custom MCP Approval',
|
||||
'wizard.approval.custom_body': 'Crank вернёт MCP-клиенту approval_required с approval_id, approval_url и ссылками approve/deny. Ваш MCP-клиент должен обработать этот ответ, показать пользователю подтверждение и отправить решение на endpoint подтверждения. Для endpoint-а подтверждения нужен отдельный ключ подтверждения агента.',
|
||||
'wizard.approval.elicitation_title': 'MCP Elicitation',
|
||||
'wizard.approval.elicitation_body': 'Crank запросит подтверждение через стандартный MCP Elicitation. MCP-клиент должен поддерживать capability elicitation. Отдельный ключ подтверждения не используется: ответ пользователя возвращается по текущей MCP-сессии.',
|
||||
'wizard.approval.elicitation_message': 'Сообщение для MCP-клиента',
|
||||
'wizard.approval.elicitation_message_placeholder': 'Подтвердите выполнение операции.',
|
||||
'wizard.approval.elicitation_message_hint': 'Короткое протокольное сообщение. Внешний вид окна подтверждения всё равно определяет MCP-клиент.',
|
||||
'wizard.approval.ttl': 'Сколько ждать подтверждение',
|
||||
'wizard.approval.show_payload': 'Показывать параметры запроса',
|
||||
'wizard.approval.payload_mode': 'Как показывать параметры',
|
||||
|
||||
@@ -43,10 +43,14 @@ function buildApprovalPolicy() {
|
||||
|
||||
return {
|
||||
required: true,
|
||||
mode: textValue('approval-mode') || 'custom',
|
||||
risk_level: 'normal',
|
||||
ttl_seconds: normalizeApprovalTtlSeconds(textValue('approval-ttl-seconds')),
|
||||
show_payload_preview: checkedValue('approval-show-payload-preview'),
|
||||
payload_preview_mode: textValue('approval-payload-preview-mode') || 'summary',
|
||||
elicitation_message: textValue('approval-mode') === 'elicitation'
|
||||
? (textValue('approval-elicitation-message') || null)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -186,6 +190,8 @@ function setApprovalPolicyEditor(policy) {
|
||||
var enabled = !!(policy && policy.required);
|
||||
var required = document.getElementById('approval-required');
|
||||
if (required) required.checked = enabled;
|
||||
setValue('approval-mode', policy && policy.mode ? policy.mode : 'custom');
|
||||
setValue('approval-elicitation-message', policy && policy.elicitation_message ? policy.elicitation_message : '');
|
||||
setValue('approval-ttl-seconds', policy && policy.ttl_seconds ? String(policy.ttl_seconds) : '300');
|
||||
var showPayload = document.getElementById('approval-show-payload-preview');
|
||||
if (showPayload) {
|
||||
@@ -199,13 +205,22 @@ function updateApprovalPolicyUi() {
|
||||
var enabled = checkedValue('approval-required');
|
||||
var toggle = document.getElementById('approval-required-toggle');
|
||||
var fields = document.getElementById('approval-config-fields');
|
||||
var mode = textValue('approval-mode') || 'custom';
|
||||
var customInfo = document.getElementById('approval-custom-info');
|
||||
var elicitationInfo = document.getElementById('approval-elicitation-info');
|
||||
var elicitationMessage = document.getElementById('approval-elicitation-message-group');
|
||||
if (toggle) toggle.classList.toggle('on', enabled);
|
||||
if (fields) fields.hidden = !enabled;
|
||||
if (customInfo) customInfo.hidden = mode !== 'custom';
|
||||
if (elicitationInfo) elicitationInfo.hidden = mode !== 'elicitation';
|
||||
if (elicitationMessage) elicitationMessage.hidden = mode !== 'elicitation';
|
||||
}
|
||||
|
||||
function bindApprovalPolicyControls() {
|
||||
[
|
||||
'approval-required',
|
||||
'approval-mode',
|
||||
'approval-elicitation-message',
|
||||
'approval-ttl-seconds',
|
||||
'approval-show-payload-preview',
|
||||
'approval-payload-preview-mode',
|
||||
|
||||
@@ -827,6 +827,7 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
|
||||
await page.evaluate(() => window.CrankWizardShell.doGoToStep(3));
|
||||
await expect(page.locator('#approval-required')).toBeChecked();
|
||||
await expect(page.locator('#approval-config-fields')).toBeVisible();
|
||||
await expect(page.locator('#approval-mode')).toHaveValue('custom');
|
||||
await expect(page.locator('#approval-risk-level')).toHaveCount(0);
|
||||
await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180');
|
||||
await expect(page.locator('#approval-payload-preview-mode')).toHaveValue('masked_json');
|
||||
@@ -857,10 +858,12 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
|
||||
streaming: null,
|
||||
approval_policy: {
|
||||
required: true,
|
||||
mode: 'custom',
|
||||
risk_level: 'normal',
|
||||
ttl_seconds: 180,
|
||||
show_payload_preview: true,
|
||||
payload_preview_mode: 'masked_json',
|
||||
elicitation_message: null,
|
||||
},
|
||||
});
|
||||
expect(updatePayload.tool_description).toEqual({
|
||||
|
||||
@@ -15,7 +15,7 @@ use axum::{
|
||||
use crank_core::{
|
||||
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore,
|
||||
InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus,
|
||||
PlatformApiKeyScope, SecretId,
|
||||
OperationApprovalMode, PlatformApiKeyScope, SecretId,
|
||||
};
|
||||
use crank_registry::{
|
||||
ApprovalRequestRecord, CreateApprovalRequest, CreateInvocationLogRequest,
|
||||
@@ -79,6 +79,8 @@ pub(super) struct AppState {
|
||||
struct InitializeParams {
|
||||
#[serde(rename = "protocolVersion")]
|
||||
protocol_version: String,
|
||||
#[serde(default)]
|
||||
capabilities: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -955,7 +957,7 @@ async fn handle_base_tool_call(
|
||||
let tool = execution.tool;
|
||||
let arguments = execution.arguments;
|
||||
let operation = runtime_operation(&tool);
|
||||
if let Some(response) = maybe_create_pending_approval(
|
||||
if let Some(response) = maybe_handle_approval_policy(
|
||||
&state,
|
||||
session,
|
||||
message,
|
||||
@@ -1052,7 +1054,7 @@ async fn handle_base_tool_call(
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_pending_approval(
|
||||
async fn maybe_handle_approval_policy(
|
||||
state: &Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
@@ -1066,6 +1068,42 @@ async fn maybe_create_pending_approval(
|
||||
return None;
|
||||
}
|
||||
|
||||
match policy.mode {
|
||||
OperationApprovalMode::Custom => {
|
||||
maybe_create_custom_pending_approval(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
transport_request_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
policy.elicitation_message.as_deref(),
|
||||
transport_request_id,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_custom_pending_approval(
|
||||
state: &Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
transport_request_id: &str,
|
||||
) -> Option<Response> {
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref()?;
|
||||
|
||||
let approval_id = ApprovalRequestId::new(format!("approval_{}", uuid::Uuid::now_v7().simple()));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = now + time::Duration::seconds(i64::from(policy.ttl_seconds));
|
||||
@@ -1145,6 +1183,54 @@ async fn maybe_create_pending_approval(
|
||||
))
|
||||
}
|
||||
|
||||
fn handle_elicitation_approval(
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
elicitation_message: Option<&str>,
|
||||
transport_request_id: &str,
|
||||
) -> Response {
|
||||
if !session.supports_elicitation {
|
||||
return tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
generic_tool_error_contract(
|
||||
"approval_elicitation_not_supported",
|
||||
"operation requires MCP Elicitation, but the MCP client did not advertise elicitation capability",
|
||||
transport_request_id,
|
||||
false,
|
||||
Some(
|
||||
"Выберите Custom MCP Approval или подключите MCP-клиент с поддержкой elicitation.",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let payload_preview = tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.and_then(|policy| policy.show_payload_preview.then(|| arguments.clone()))
|
||||
.unwrap_or(Value::Null);
|
||||
|
||||
success_tool_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
json!({
|
||||
"status": "elicitation_required",
|
||||
"message": elicitation_message.unwrap_or("Confirm operation execution."),
|
||||
"tool": tool.tool_name,
|
||||
"payload_preview": payload_preview,
|
||||
"note": "This MCP client advertised elicitation support. Full elicitation/create continuation is handled by compatible client integrations.",
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn approval_url_for(tool: &PublishedAgentTool, approval_id: &ApprovalRequestId) -> String {
|
||||
format!(
|
||||
"/v1/{}/{}/approvals/{}",
|
||||
@@ -1191,12 +1277,17 @@ async fn handle_initialize(
|
||||
};
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||
let supports_elicitation = initialize_params
|
||||
.capabilities
|
||||
.get("elicitation")
|
||||
.is_some_and(Value::is_object);
|
||||
let session_id = match state
|
||||
.sessions
|
||||
.create(
|
||||
protocol_version,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
supports_elicitation,
|
||||
now,
|
||||
Some(expires_at),
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
|
||||
use async_trait::async_trait;
|
||||
use crank_registry::PostgresPoolConfig;
|
||||
use sqlx::{
|
||||
PgPool,
|
||||
PgPool, Row,
|
||||
postgres::{PgConnectOptions, PgPoolOptions},
|
||||
query,
|
||||
};
|
||||
@@ -17,6 +17,7 @@ pub struct SessionState {
|
||||
pub id: String,
|
||||
pub protocol_version: String,
|
||||
pub initialized: bool,
|
||||
pub supports_elicitation: bool,
|
||||
pub workspace_slug: String,
|
||||
pub agent_slug: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
@@ -37,6 +38,7 @@ pub trait TransportSessionStore: Send + Sync {
|
||||
protocol_version: &str,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
supports_elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError>;
|
||||
@@ -100,6 +102,7 @@ impl TransportSessionStore for InMemorySessionStore {
|
||||
protocol_version: &str,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
supports_elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
@@ -112,6 +115,7 @@ impl TransportSessionStore for InMemorySessionStore {
|
||||
id: session_id.clone(),
|
||||
protocol_version: protocol_version.to_owned(),
|
||||
initialized: false,
|
||||
supports_elicitation,
|
||||
workspace_slug: workspace_slug.to_owned(),
|
||||
agent_slug: agent_slug.to_owned(),
|
||||
created_at: now,
|
||||
@@ -169,6 +173,7 @@ impl TransportSessionStore for PostgresTransportSessionStore {
|
||||
protocol_version: &str,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
supports_elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires_at: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
@@ -178,17 +183,19 @@ impl TransportSessionStore for PostgresTransportSessionStore {
|
||||
id,
|
||||
protocol_version,
|
||||
initialized,
|
||||
supports_elicitation,
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
created_at,
|
||||
updated_at,
|
||||
expires_at
|
||||
) values (
|
||||
$1, $2, false, $3, $4, $5::timestamptz, $5::timestamptz, $6::timestamptz
|
||||
$1, $2, false, $3, $4, $5, $6::timestamptz, $6::timestamptz, $7::timestamptz
|
||||
)",
|
||||
)
|
||||
.bind(&session_id)
|
||||
.bind(protocol_version)
|
||||
.bind(supports_elicitation)
|
||||
.bind(workspace_slug)
|
||||
.bind(agent_slug)
|
||||
.bind(now)
|
||||
@@ -203,20 +210,21 @@ impl TransportSessionStore for PostgresTransportSessionStore {
|
||||
}
|
||||
|
||||
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
let row = sqlx::query!(
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
id,
|
||||
protocol_version,
|
||||
initialized,
|
||||
supports_elicitation,
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
created_at as \"created_at!: OffsetDateTime\",
|
||||
updated_at as \"updated_at!: OffsetDateTime\",
|
||||
expires_at as \"expires_at: OffsetDateTime\"
|
||||
created_at,
|
||||
updated_at,
|
||||
expires_at
|
||||
from mcp_transport_sessions
|
||||
where id = $1",
|
||||
session_id,
|
||||
)
|
||||
.bind(session_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(|error| SessionStoreError {
|
||||
@@ -224,14 +232,15 @@ impl TransportSessionStore for PostgresTransportSessionStore {
|
||||
})?;
|
||||
|
||||
let Some(session) = row.map(|row| SessionState {
|
||||
id: row.id,
|
||||
protocol_version: row.protocol_version,
|
||||
initialized: row.initialized,
|
||||
workspace_slug: row.workspace_slug,
|
||||
agent_slug: row.agent_slug,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
expires_at: row.expires_at,
|
||||
id: row.get("id"),
|
||||
protocol_version: row.get("protocol_version"),
|
||||
initialized: row.get("initialized"),
|
||||
supports_elicitation: row.get("supports_elicitation"),
|
||||
workspace_slug: row.get("workspace_slug"),
|
||||
agent_slug: row.get("agent_slug"),
|
||||
created_at: row.get("created_at"),
|
||||
updated_at: row.get("updated_at"),
|
||||
expires_at: row.get("expires_at"),
|
||||
}) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -291,6 +300,7 @@ async fn apply_postgres_migrations(pool: &PgPool) -> Result<(), SessionStoreErro
|
||||
id text primary key,
|
||||
protocol_version text not null,
|
||||
initialized boolean not null default false,
|
||||
supports_elicitation boolean not null default false,
|
||||
workspace_slug text not null,
|
||||
agent_slug text not null,
|
||||
created_at timestamptz not null,
|
||||
@@ -304,6 +314,13 @@ async fn apply_postgres_migrations(pool: &PgPool) -> Result<(), SessionStoreErro
|
||||
details: error.to_string(),
|
||||
})?;
|
||||
|
||||
query("alter table mcp_transport_sessions add column if not exists supports_elicitation boolean not null default false")
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|error| SessionStoreError {
|
||||
details: error.to_string(),
|
||||
})?;
|
||||
|
||||
query(
|
||||
"alter table mcp_transport_sessions add column if not exists expires_at timestamptz null",
|
||||
)
|
||||
|
||||
@@ -32,6 +32,7 @@ async fn postgres_transport_sessions_survive_store_reconnect() {
|
||||
"2025-11-25",
|
||||
"default",
|
||||
"sales",
|
||||
false,
|
||||
created_at,
|
||||
Some(created_at + time::Duration::days(30)),
|
||||
)
|
||||
@@ -73,6 +74,7 @@ async fn postgres_transport_sessions_evict_expired_rows_on_read() {
|
||||
"2025-11-25",
|
||||
"default",
|
||||
"sales",
|
||||
false,
|
||||
timestamp("2026-05-01T10:00:00Z"),
|
||||
Some(timestamp("2026-05-01T10:00:01Z")),
|
||||
)
|
||||
|
||||
@@ -13,7 +13,7 @@ async fn creates_and_reads_transport_sessions() {
|
||||
let created_at = timestamp("2026-05-01T10:00:00Z");
|
||||
|
||||
let session_id = store
|
||||
.create("2025-11-25", "default", "sales", created_at, None)
|
||||
.create("2025-11-25", "default", "sales", false, created_at, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let session = store.get(&session_id).await.unwrap().unwrap();
|
||||
@@ -23,6 +23,7 @@ async fn creates_and_reads_transport_sessions() {
|
||||
assert_eq!(session.workspace_slug, "default");
|
||||
assert_eq!(session.agent_slug, "sales");
|
||||
assert!(!session.initialized);
|
||||
assert!(!session.supports_elicitation);
|
||||
assert_eq!(session.created_at, created_at);
|
||||
assert_eq!(session.updated_at, created_at);
|
||||
}
|
||||
@@ -34,7 +35,7 @@ async fn marks_transport_sessions_initialized() {
|
||||
let initialized_at = timestamp("2026-05-01T10:00:05Z");
|
||||
|
||||
let session_id = store
|
||||
.create("2025-11-25", "default", "sales", created_at, None)
|
||||
.create("2025-11-25", "default", "sales", false, created_at, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -61,6 +62,7 @@ async fn drops_expired_in_memory_transport_sessions_on_read() {
|
||||
"2025-11-25",
|
||||
"default",
|
||||
"sales",
|
||||
false,
|
||||
created_at,
|
||||
Some(expires_at),
|
||||
)
|
||||
|
||||
@@ -43,10 +43,10 @@ pub mod domain {
|
||||
};
|
||||
pub use crate::operation::{
|
||||
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalPayloadPreviewMode,
|
||||
OperationApprovalPolicy, OperationApprovalRiskLevel, OperationSafetyClass,
|
||||
OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget, RetryPolicy,
|
||||
Samples, Target, ToolDescription, ToolExample, WizardState,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
|
||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, ResponseCachePolicy,
|
||||
RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample, WizardState,
|
||||
};
|
||||
pub use crate::protocol::{AuthKind, ExportMode, HttpMethod, Protocol};
|
||||
pub use crate::secret::{Secret, SecretKind, SecretStatus, SecretVersion};
|
||||
@@ -133,10 +133,10 @@ pub use observability::{
|
||||
};
|
||||
pub use operation::{
|
||||
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalPayloadPreviewMode,
|
||||
OperationApprovalPolicy, OperationApprovalRiskLevel, OperationSafetyClass,
|
||||
OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget, RetryPolicy, Samples,
|
||||
Target, ToolDescription, ToolExample, WizardState,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
|
||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget,
|
||||
RetryPolicy, Samples, Target, ToolDescription, ToolExample, WizardState,
|
||||
};
|
||||
pub use protocol::{AuthKind, ExportMode, HttpMethod, Protocol};
|
||||
pub use secret::{Secret, SecretKind, SecretStatus, SecretVersion};
|
||||
|
||||
@@ -121,13 +121,25 @@ pub enum OperationApprovalPayloadPreviewMode {
|
||||
MaskedJson,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OperationApprovalMode {
|
||||
#[default]
|
||||
Custom,
|
||||
Elicitation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OperationApprovalPolicy {
|
||||
pub required: bool,
|
||||
#[serde(default)]
|
||||
pub mode: OperationApprovalMode,
|
||||
pub risk_level: OperationApprovalRiskLevel,
|
||||
pub ttl_seconds: u32,
|
||||
pub show_payload_preview: bool,
|
||||
pub payload_preview_mode: OperationApprovalPayloadPreviewMode,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub elicitation_message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
Reference in New Issue
Block a user