Add approval mode selection
This commit is contained in:
@@ -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