Add approval mode selection
CI / Rust Checks (push) Successful in 5m35s
CI / UI Checks (push) Successful in 5s
CI / Deployment Manifests (push) Successful in 2s
CI / Frontend E2E (push) Successful in 3m28s
CI / Deploy (push) Successful in 1m38s

This commit is contained in:
github-ops
2026-06-27 07:55:38 +00:00
parent 2b2ff92146
commit 700a684257
15 changed files with 425 additions and 31 deletions
@@ -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(()) Ok(())
} }
@@ -133,7 +144,7 @@ mod tests {
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crank_core::{ use crank_core::{
ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy, ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy, OperationApprovalMode,
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
ResponseCachePolicy, RestTarget, Target, ResponseCachePolicy, RestTarget, Target,
}; };
@@ -272,10 +283,12 @@ mod tests {
let mut config = cacheable_execution_config(); let mut config = cacheable_execution_config();
config.approval_policy = Some(OperationApprovalPolicy { config.approval_policy = Some(OperationApprovalPolicy {
required: true, required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous, risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300, ttl_seconds: 300,
show_payload_preview: true, show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson, payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
}); });
validate_approval_policy(&config).unwrap(); validate_approval_policy(&config).unwrap();
@@ -286,10 +299,12 @@ mod tests {
let mut config = cacheable_execution_config(); let mut config = cacheable_execution_config();
config.approval_policy = Some(OperationApprovalPolicy { config.approval_policy = Some(OperationApprovalPolicy {
required: true, required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous, risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 0, ttl_seconds: 0,
show_payload_preview: true, show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson, payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
}); });
let error = validate_approval_policy(&config).unwrap_err(); 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::{ use crank_core::{
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest, Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
ApprovalRequestId, ApprovalRequestStatus, ExecutionConfig, HttpMethod, InvocationSource, ApprovalRequestId, ApprovalRequestStatus, ExecutionConfig, HttpMethod, InvocationSource,
Operation, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, Operation, OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId, OperationApprovalRiskLevel, OperationId, OperationStatus, PlatformApiKey, PlatformApiKeyId,
PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription, PlatformApiKeyScope, PlatformApiKeyStatus, Protocol, RestTarget, Target, ToolDescription,
WorkspaceId, 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"); let mut operation = test_operation(&upstream_base_url, "crm_requires_human_approval");
operation.execution_config.approval_policy = Some(OperationApprovalPolicy { operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
required: true, required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous, risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300, ttl_seconds: 300,
show_payload_preview: true, show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson, payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
}); });
registry registry
.create_operation(&test_workspace_id(), &operation, Some("alice")) .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" "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(
&registry,
"sales-elicitation-no-capability",
vec![binding_for_operation(&operation)],
)
.await;
let api_key = create_platform_api_key(
&registry,
"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(
&registry,
"sales-elicitation-supported",
vec![binding_for_operation(&operation)],
)
.await;
let api_key = create_platform_api_key(
&registry,
"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"
);
}
+11 -1
View File
@@ -147,6 +147,15 @@ pub(super) async fn initialize_session(
client: &reqwest::Client, client: &reqwest::Client,
mcp_url: &str, mcp_url: &str,
api_key: &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 { ) -> String {
let initialize_response = client let initialize_response = client
.post(mcp_url) .post(mcp_url)
@@ -157,7 +166,8 @@ pub(super) async fn initialize_session(
"id": 1, "id": 1,
"method": "initialize", "method": "initialize",
"params": { "params": {
"protocolVersion": "2025-11-25" "protocolVersion": "2025-11-25",
"capabilities": capabilities
} }
})) }))
.send() .send()
@@ -689,6 +689,7 @@ async fn get_returns_not_found_for_expired_transport_session() {
"2025-11-25", "2025-11-25",
test_workspace_slug(), test_workspace_slug(),
"sales-expired-session", "sales-expired-session",
false,
OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(), OffsetDateTime::parse("2026-05-01T10:00:00Z", &Rfc3339).unwrap(),
Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()), Some(OffsetDateTime::parse("2026-05-01T10:00:01Z", &Rfc3339).unwrap()),
) )
+36
View File
@@ -114,6 +114,42 @@
</label> </label>
<div id="approval-config-fields" class="approval-config-fields" hidden> <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"> <div class="form-group">
<label class="form-label" for="approval-ttl-seconds" data-i18n="wizard.approval.ttl">Сколько ждать подтверждение</label> <label class="form-label" for="approval-ttl-seconds" data-i18n="wizard.approval.ttl">Сколько ждать подтверждение</label>
<select id="approval-ttl-seconds" class="form-select"> <select id="approval-ttl-seconds" class="form-select">
+20
View File
@@ -598,6 +598,16 @@ var TRANSLATIONS = {
'wizard.approval.subtitle': 'Enable this for actions that must not run without an explicit user decision.', '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_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.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.ttl': 'How long to wait for confirmation',
'wizard.approval.show_payload': 'Show request parameters', 'wizard.approval.show_payload': 'Show request parameters',
'wizard.approval.payload_mode': 'How to show parameters', 'wizard.approval.payload_mode': 'How to show parameters',
@@ -1453,6 +1463,16 @@ var TRANSLATIONS = {
'wizard.approval.subtitle': 'Включайте для действий, которые нельзя выполнять без явного решения пользователя.', 'wizard.approval.subtitle': 'Включайте для действий, которые нельзя выполнять без явного решения пользователя.',
'wizard.approval.required_label': 'Требовать подтверждение перед выполнением', 'wizard.approval.required_label': 'Требовать подтверждение перед выполнением',
'wizard.approval.required_desc': 'MCP клиент получит ожидающий запрос, а действие выполнится только после подтверждения через отдельный эндпоинт подтверждения.', '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.ttl': 'Сколько ждать подтверждение',
'wizard.approval.show_payload': 'Показывать параметры запроса', 'wizard.approval.show_payload': 'Показывать параметры запроса',
'wizard.approval.payload_mode': 'Как показывать параметры', 'wizard.approval.payload_mode': 'Как показывать параметры',
+15
View File
@@ -43,10 +43,14 @@ function buildApprovalPolicy() {
return { return {
required: true, required: true,
mode: textValue('approval-mode') || 'custom',
risk_level: 'normal', risk_level: 'normal',
ttl_seconds: normalizeApprovalTtlSeconds(textValue('approval-ttl-seconds')), ttl_seconds: normalizeApprovalTtlSeconds(textValue('approval-ttl-seconds')),
show_payload_preview: checkedValue('approval-show-payload-preview'), show_payload_preview: checkedValue('approval-show-payload-preview'),
payload_preview_mode: textValue('approval-payload-preview-mode') || 'summary', 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 enabled = !!(policy && policy.required);
var required = document.getElementById('approval-required'); var required = document.getElementById('approval-required');
if (required) required.checked = enabled; 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'); setValue('approval-ttl-seconds', policy && policy.ttl_seconds ? String(policy.ttl_seconds) : '300');
var showPayload = document.getElementById('approval-show-payload-preview'); var showPayload = document.getElementById('approval-show-payload-preview');
if (showPayload) { if (showPayload) {
@@ -199,13 +205,22 @@ function updateApprovalPolicyUi() {
var enabled = checkedValue('approval-required'); var enabled = checkedValue('approval-required');
var toggle = document.getElementById('approval-required-toggle'); var toggle = document.getElementById('approval-required-toggle');
var fields = document.getElementById('approval-config-fields'); 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 (toggle) toggle.classList.toggle('on', enabled);
if (fields) fields.hidden = !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() { function bindApprovalPolicyControls() {
[ [
'approval-required', 'approval-required',
'approval-mode',
'approval-elicitation-message',
'approval-ttl-seconds', 'approval-ttl-seconds',
'approval-show-payload-preview', 'approval-show-payload-preview',
'approval-payload-preview-mode', 'approval-payload-preview-mode',
+3
View File
@@ -827,6 +827,7 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
await page.evaluate(() => window.CrankWizardShell.doGoToStep(3)); await page.evaluate(() => window.CrankWizardShell.doGoToStep(3));
await expect(page.locator('#approval-required')).toBeChecked(); await expect(page.locator('#approval-required')).toBeChecked();
await expect(page.locator('#approval-config-fields')).toBeVisible(); 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-risk-level')).toHaveCount(0);
await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180'); await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180');
await expect(page.locator('#approval-payload-preview-mode')).toHaveValue('masked_json'); 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, streaming: null,
approval_policy: { approval_policy: {
required: true, required: true,
mode: 'custom',
risk_level: 'normal', risk_level: 'normal',
ttl_seconds: 180, ttl_seconds: 180,
show_payload_preview: true, show_payload_preview: true,
payload_preview_mode: 'masked_json', payload_preview_mode: 'masked_json',
elicitation_message: null,
}, },
}); });
expect(updatePayload.tool_description).toEqual({ expect(updatePayload.tool_description).toEqual({
+94 -3
View File
@@ -15,7 +15,7 @@ use axum::{
use crank_core::{ use crank_core::{
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore, ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore,
InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus, InvocationLevel, InvocationLog, InvocationLogId, InvocationSource, InvocationStatus,
PlatformApiKeyScope, SecretId, OperationApprovalMode, PlatformApiKeyScope, SecretId,
}; };
use crank_registry::{ use crank_registry::{
ApprovalRequestRecord, CreateApprovalRequest, CreateInvocationLogRequest, ApprovalRequestRecord, CreateApprovalRequest, CreateInvocationLogRequest,
@@ -79,6 +79,8 @@ pub(super) struct AppState {
struct InitializeParams { struct InitializeParams {
#[serde(rename = "protocolVersion")] #[serde(rename = "protocolVersion")]
protocol_version: String, protocol_version: String,
#[serde(default)]
capabilities: Value,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -955,7 +957,7 @@ async fn handle_base_tool_call(
let tool = execution.tool; let tool = execution.tool;
let arguments = execution.arguments; let arguments = execution.arguments;
let operation = runtime_operation(&tool); let operation = runtime_operation(&tool);
if let Some(response) = maybe_create_pending_approval( if let Some(response) = maybe_handle_approval_policy(
&state, &state,
session, session,
message, 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>, state: &Arc<AppState>,
session: &SessionState, session: &SessionState,
message: &Value, message: &Value,
@@ -1066,6 +1068,42 @@ async fn maybe_create_pending_approval(
return None; 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 approval_id = ApprovalRequestId::new(format!("approval_{}", uuid::Uuid::now_v7().simple()));
let now = OffsetDateTime::now_utc(); let now = OffsetDateTime::now_utc();
let expires_at = now + time::Duration::seconds(i64::from(policy.ttl_seconds)); 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 { fn approval_url_for(tool: &PublishedAgentTool, approval_id: &ApprovalRequestId) -> String {
format!( format!(
"/v1/{}/{}/approvals/{}", "/v1/{}/{}/approvals/{}",
@@ -1191,12 +1277,17 @@ async fn handle_initialize(
}; };
let now = OffsetDateTime::now_utc(); let now = OffsetDateTime::now_utc();
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS); 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 let session_id = match state
.sessions .sessions
.create( .create(
protocol_version, protocol_version,
&path.workspace_slug, &path.workspace_slug,
&path.agent_slug, &path.agent_slug,
supports_elicitation,
now, now,
Some(expires_at), Some(expires_at),
) )
+32 -15
View File
@@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
use async_trait::async_trait; use async_trait::async_trait;
use crank_registry::PostgresPoolConfig; use crank_registry::PostgresPoolConfig;
use sqlx::{ use sqlx::{
PgPool, PgPool, Row,
postgres::{PgConnectOptions, PgPoolOptions}, postgres::{PgConnectOptions, PgPoolOptions},
query, query,
}; };
@@ -17,6 +17,7 @@ pub struct SessionState {
pub id: String, pub id: String,
pub protocol_version: String, pub protocol_version: String,
pub initialized: bool, pub initialized: bool,
pub supports_elicitation: bool,
pub workspace_slug: String, pub workspace_slug: String,
pub agent_slug: String, pub agent_slug: String,
pub created_at: OffsetDateTime, pub created_at: OffsetDateTime,
@@ -37,6 +38,7 @@ pub trait TransportSessionStore: Send + Sync {
protocol_version: &str, protocol_version: &str,
workspace_slug: &str, workspace_slug: &str,
agent_slug: &str, agent_slug: &str,
supports_elicitation: bool,
now: OffsetDateTime, now: OffsetDateTime,
expires_at: Option<OffsetDateTime>, expires_at: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError>; ) -> Result<String, SessionStoreError>;
@@ -100,6 +102,7 @@ impl TransportSessionStore for InMemorySessionStore {
protocol_version: &str, protocol_version: &str,
workspace_slug: &str, workspace_slug: &str,
agent_slug: &str, agent_slug: &str,
supports_elicitation: bool,
now: OffsetDateTime, now: OffsetDateTime,
expires_at: Option<OffsetDateTime>, expires_at: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError> { ) -> Result<String, SessionStoreError> {
@@ -112,6 +115,7 @@ impl TransportSessionStore for InMemorySessionStore {
id: session_id.clone(), id: session_id.clone(),
protocol_version: protocol_version.to_owned(), protocol_version: protocol_version.to_owned(),
initialized: false, initialized: false,
supports_elicitation,
workspace_slug: workspace_slug.to_owned(), workspace_slug: workspace_slug.to_owned(),
agent_slug: agent_slug.to_owned(), agent_slug: agent_slug.to_owned(),
created_at: now, created_at: now,
@@ -169,6 +173,7 @@ impl TransportSessionStore for PostgresTransportSessionStore {
protocol_version: &str, protocol_version: &str,
workspace_slug: &str, workspace_slug: &str,
agent_slug: &str, agent_slug: &str,
supports_elicitation: bool,
now: OffsetDateTime, now: OffsetDateTime,
expires_at: Option<OffsetDateTime>, expires_at: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError> { ) -> Result<String, SessionStoreError> {
@@ -178,17 +183,19 @@ impl TransportSessionStore for PostgresTransportSessionStore {
id, id,
protocol_version, protocol_version,
initialized, initialized,
supports_elicitation,
workspace_slug, workspace_slug,
agent_slug, agent_slug,
created_at, created_at,
updated_at, updated_at,
expires_at expires_at
) values ( ) 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(&session_id)
.bind(protocol_version) .bind(protocol_version)
.bind(supports_elicitation)
.bind(workspace_slug) .bind(workspace_slug)
.bind(agent_slug) .bind(agent_slug)
.bind(now) .bind(now)
@@ -203,20 +210,21 @@ impl TransportSessionStore for PostgresTransportSessionStore {
} }
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> { async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
let row = sqlx::query!( let row = sqlx::query(
"select "select
id, id,
protocol_version, protocol_version,
initialized, initialized,
supports_elicitation,
workspace_slug, workspace_slug,
agent_slug, agent_slug,
created_at as \"created_at!: OffsetDateTime\", created_at,
updated_at as \"updated_at!: OffsetDateTime\", updated_at,
expires_at as \"expires_at: OffsetDateTime\" expires_at
from mcp_transport_sessions from mcp_transport_sessions
where id = $1", where id = $1",
session_id,
) )
.bind(session_id)
.fetch_optional(&self.pool) .fetch_optional(&self.pool)
.await .await
.map_err(|error| SessionStoreError { .map_err(|error| SessionStoreError {
@@ -224,14 +232,15 @@ impl TransportSessionStore for PostgresTransportSessionStore {
})?; })?;
let Some(session) = row.map(|row| SessionState { let Some(session) = row.map(|row| SessionState {
id: row.id, id: row.get("id"),
protocol_version: row.protocol_version, protocol_version: row.get("protocol_version"),
initialized: row.initialized, initialized: row.get("initialized"),
workspace_slug: row.workspace_slug, supports_elicitation: row.get("supports_elicitation"),
agent_slug: row.agent_slug, workspace_slug: row.get("workspace_slug"),
created_at: row.created_at, agent_slug: row.get("agent_slug"),
updated_at: row.updated_at, created_at: row.get("created_at"),
expires_at: row.expires_at, updated_at: row.get("updated_at"),
expires_at: row.get("expires_at"),
}) else { }) else {
return Ok(None); return Ok(None);
}; };
@@ -291,6 +300,7 @@ async fn apply_postgres_migrations(pool: &PgPool) -> Result<(), SessionStoreErro
id text primary key, id text primary key,
protocol_version text not null, protocol_version text not null,
initialized boolean not null default false, initialized boolean not null default false,
supports_elicitation boolean not null default false,
workspace_slug text not null, workspace_slug text not null,
agent_slug text not null, agent_slug text not null,
created_at timestamptz not null, created_at timestamptz not null,
@@ -304,6 +314,13 @@ async fn apply_postgres_migrations(pool: &PgPool) -> Result<(), SessionStoreErro
details: error.to_string(), 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( query(
"alter table mcp_transport_sessions add column if not exists expires_at timestamptz null", "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", "2025-11-25",
"default", "default",
"sales", "sales",
false,
created_at, created_at,
Some(created_at + time::Duration::days(30)), Some(created_at + time::Duration::days(30)),
) )
@@ -73,6 +74,7 @@ async fn postgres_transport_sessions_evict_expired_rows_on_read() {
"2025-11-25", "2025-11-25",
"default", "default",
"sales", "sales",
false,
timestamp("2026-05-01T10:00:00Z"), timestamp("2026-05-01T10:00:00Z"),
Some(timestamp("2026-05-01T10:00:01Z")), 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 created_at = timestamp("2026-05-01T10:00:00Z");
let session_id = store let session_id = store
.create("2025-11-25", "default", "sales", created_at, None) .create("2025-11-25", "default", "sales", false, created_at, None)
.await .await
.unwrap(); .unwrap();
let session = store.get(&session_id).await.unwrap().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.workspace_slug, "default");
assert_eq!(session.agent_slug, "sales"); assert_eq!(session.agent_slug, "sales");
assert!(!session.initialized); assert!(!session.initialized);
assert!(!session.supports_elicitation);
assert_eq!(session.created_at, created_at); assert_eq!(session.created_at, created_at);
assert_eq!(session.updated_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 initialized_at = timestamp("2026-05-01T10:00:05Z");
let session_id = store let session_id = store
.create("2025-11-25", "default", "sales", created_at, None) .create("2025-11-25", "default", "sales", false, created_at, None)
.await .await
.unwrap(); .unwrap();
@@ -61,6 +62,7 @@ async fn drops_expired_in_memory_transport_sessions_on_read() {
"2025-11-25", "2025-11-25",
"default", "default",
"sales", "sales",
false,
created_at, created_at,
Some(expires_at), Some(expires_at),
) )
+8 -8
View File
@@ -43,10 +43,10 @@ pub mod domain {
}; };
pub use crate::operation::{ pub use crate::operation::{
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus, ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalPayloadPreviewMode, IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
OperationApprovalPolicy, OperationApprovalRiskLevel, OperationSafetyClass, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget, RetryPolicy, OperationSafetyClass, OperationSafetyPolicy, OperationStatus, ResponseCachePolicy,
Samples, Target, ToolDescription, ToolExample, WizardState, RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample, WizardState,
}; };
pub use crate::protocol::{AuthKind, ExportMode, HttpMethod, Protocol}; pub use crate::protocol::{AuthKind, ExportMode, HttpMethod, Protocol};
pub use crate::secret::{Secret, SecretKind, SecretStatus, SecretVersion}; pub use crate::secret::{Secret, SecretKind, SecretStatus, SecretVersion};
@@ -133,10 +133,10 @@ pub use observability::{
}; };
pub use operation::{ pub use operation::{
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus, ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalPayloadPreviewMode, IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
OperationApprovalPolicy, OperationApprovalRiskLevel, OperationSafetyClass, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget, RetryPolicy, Samples, OperationSafetyClass, OperationSafetyPolicy, OperationStatus, ResponseCachePolicy, RestTarget,
Target, ToolDescription, ToolExample, WizardState, RetryPolicy, Samples, Target, ToolDescription, ToolExample, WizardState,
}; };
pub use protocol::{AuthKind, ExportMode, HttpMethod, Protocol}; pub use protocol::{AuthKind, ExportMode, HttpMethod, Protocol};
pub use secret::{Secret, SecretKind, SecretStatus, SecretVersion}; pub use secret::{Secret, SecretKind, SecretStatus, SecretVersion};
+12
View File
@@ -121,13 +121,25 @@ pub enum OperationApprovalPayloadPreviewMode {
MaskedJson, 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)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperationApprovalPolicy { pub struct OperationApprovalPolicy {
pub required: bool, pub required: bool,
#[serde(default)]
pub mode: OperationApprovalMode,
pub risk_level: OperationApprovalRiskLevel, pub risk_level: OperationApprovalRiskLevel,
pub ttl_seconds: u32, pub ttl_seconds: u32,
pub show_payload_preview: bool, pub show_payload_preview: bool,
pub payload_preview_mode: OperationApprovalPayloadPreviewMode, 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)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]