feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -13,32 +13,29 @@ use axum::{
|
||||
routing::{get, post},
|
||||
};
|
||||
use crank_core::{
|
||||
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore,
|
||||
CorrelationContext, InvocationLevel, InvocationSource, InvocationStatus, OperationApprovalMode,
|
||||
PlatformApiKeyScope, SecretId,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore,
|
||||
CorrelationContext, ExecutionOrigin, InvocationLevel, InvocationSource, InvocationStatus,
|
||||
PlatformApiKeyScope, SecretId, SecretStatus,
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateApprovalRequest, DecideApprovalRequest, ExpireApprovalRequest, PostgresRegistry,
|
||||
ApprovalRequestRecord, DecideApprovalRequest, ExpireApprovalRequest, PostgresRegistry,
|
||||
PublishedAgentTool,
|
||||
};
|
||||
use crank_runtime::{
|
||||
RequestRateLimiter, ResolvedAuth, RuntimeError, RuntimeExecutionRequest, RuntimeExecutor,
|
||||
RuntimeOperation, RuntimeRequestContext, SecretCrypto,
|
||||
ExecutionAuthorization, RequestRateLimiter, ResolvedAuth, RuntimeError,
|
||||
RuntimeExecutionRequest, RuntimeExecutor, RuntimeRequestContext, SecretCrypto,
|
||||
};
|
||||
use crank_trace::{DbOperation, ErrorCategory, Stage, StageOutcome, observe_db_query};
|
||||
use futures_util::stream;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::Semaphore;
|
||||
use tracing::{Instrument, info};
|
||||
use tracing::{Instrument, info, warn};
|
||||
|
||||
use crate::{
|
||||
access::{
|
||||
credential_allows_security_level, serialize_machine_access_mode, serialize_security_level,
|
||||
},
|
||||
access::credential_allows_security_level,
|
||||
approval_execution::{execute_approved_request, spawn_approval_recovery},
|
||||
approval_response::approval_required_response,
|
||||
auth::{SharedMachineCredentialVerifier, VerifiedMachineCredential},
|
||||
catalog::PublishedToolCatalog,
|
||||
jsonrpc::{
|
||||
@@ -49,10 +46,7 @@ use crate::{
|
||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||
request_context::{RequestContext, apply_request_context},
|
||||
session::{ActiveSessionMetrics, SessionState, SharedSessionStore, spawn_session_cleanup},
|
||||
tool_error::{
|
||||
ToolErrorContract, generic_tool_error_contract, runtime_error_code,
|
||||
tool_error_contract_from_runtime, tool_error_text, tool_error_value,
|
||||
},
|
||||
tool_error::{execution_locale, tool_error_contract_from_failure},
|
||||
tool_search::handle_catalog_tool_call,
|
||||
transport::{
|
||||
AllowedOrigins, ResponseMode, json_response, negotiate_post_response_mode,
|
||||
@@ -61,17 +55,30 @@ use crate::{
|
||||
with_request_id_header,
|
||||
},
|
||||
};
|
||||
mod approval_policy;
|
||||
mod invocation_history;
|
||||
mod metrics;
|
||||
mod request;
|
||||
mod response;
|
||||
mod stages;
|
||||
mod tool_resolution;
|
||||
use self::approval_policy::{
|
||||
ApprovalPolicyContext, ApprovalPolicyResult, maybe_handle_approval_policy,
|
||||
};
|
||||
use self::metrics::{ActiveStreamGuard, McpRequestMetrics};
|
||||
use self::request::{
|
||||
ApprovalDecisionPayload, InitializeParams, ToolCallParams, ToolsListParams, paginate_tools_list,
|
||||
};
|
||||
pub(super) use self::response::{
|
||||
success_tool_response, take_confirmation_token, tool_error_response,
|
||||
};
|
||||
use self::stages::{
|
||||
enforce_traced_rate_limit, require_traced_approval_access, require_traced_machine_access,
|
||||
};
|
||||
pub(super) use self::tool_resolution::{resolve_generated_tool, runtime_operation};
|
||||
#[cfg(test)]
|
||||
use invocation_history::observe_invocation_history_outcome;
|
||||
use invocation_history::persist_invocation_for_key;
|
||||
pub(super) use invocation_history::{InvocationRecord, persist_invocation};
|
||||
|
||||
const TRANSPORT_SESSION_TTL_MS: u64 = 86_400_000;
|
||||
@@ -92,28 +99,6 @@ pub(super) struct AppState {
|
||||
allowed_origins: AllowedOrigins,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct InitializeParams {
|
||||
#[serde(rename = "protocolVersion")]
|
||||
protocol_version: String,
|
||||
#[serde(default)]
|
||||
capabilities: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct ToolCallParams {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
arguments: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ApprovalDecisionPayload {
|
||||
approve: String,
|
||||
#[serde(default)]
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ResolvedToolCall {
|
||||
tool: PublishedAgentTool,
|
||||
@@ -123,6 +108,7 @@ struct ToolCallExecution {
|
||||
tool: PublishedAgentTool,
|
||||
arguments: Value,
|
||||
confirmation_token: Option<String>,
|
||||
platform_api_key_id: Option<crank_core::PlatformApiKeyId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
@@ -346,7 +332,10 @@ async fn list_pending_approvals(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(items) => Json(json!({ "items": items })).into_response(),
|
||||
Ok(items) => Json(json!({
|
||||
"items": items.into_iter().map(safe_approval_record).collect::<Vec<_>>()
|
||||
}))
|
||||
.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
}
|
||||
@@ -461,6 +450,21 @@ async fn decide_approval_request(
|
||||
};
|
||||
let approval_id = ApprovalRequestId::new(path.approval_id);
|
||||
|
||||
let expected_record = match observe_db_query(
|
||||
DbOperation::ApprovalRead,
|
||||
state.registry.get_approval_request_for_agent(
|
||||
&key.api_key.workspace_id,
|
||||
agent_id,
|
||||
&approval_id,
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => record,
|
||||
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
};
|
||||
|
||||
match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
@@ -469,9 +473,12 @@ async fn decide_approval_request(
|
||||
workspace_id: &key.api_key.workspace_id,
|
||||
agent_id,
|
||||
approval_id: &approval_id,
|
||||
operation_id: &expected_record.approval.operation_id,
|
||||
operation_version: expected_record.approval.operation_version,
|
||||
request_payload: &expected_record.approval.request_payload,
|
||||
status,
|
||||
decided_at: OffsetDateTime::now_utc(),
|
||||
decided_by_key_id: &key.api_key.id,
|
||||
decided_by_key_id: Some(&key.api_key.id),
|
||||
response_payload: Some(json!({ "approve": payload.approve })),
|
||||
decision_note: payload.note.as_deref(),
|
||||
}),
|
||||
@@ -502,11 +509,11 @@ async fn decide_approval_request(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(record) => Json(json!(record)).into_response(),
|
||||
Ok(record) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(record)).into_response(),
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => {
|
||||
terminal_decision_response(&state, &key.api_key.workspace_id, agent_id, &approval_id)
|
||||
.await
|
||||
@@ -535,7 +542,7 @@ async fn approval_record_response(
|
||||
{
|
||||
expire_approval_response(state, workspace_id, agent_id, approval_id).await
|
||||
}
|
||||
Ok(Some(record)) => Json(json!(record)).into_response(),
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
@@ -570,7 +577,7 @@ async fn terminal_decision_response(
|
||||
| ApprovalRequestStatus::Expired
|
||||
) =>
|
||||
{
|
||||
Json(json!(record)).into_response()
|
||||
Json(json!(safe_approval_record(record))).into_response()
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::CONFLICT.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
@@ -578,6 +585,17 @@ async fn terminal_decision_response(
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_approval_record(mut record: ApprovalRequestRecord) -> ApprovalRequestRecord {
|
||||
record.approval.request_payload =
|
||||
crank_core::sanitize_invocation_preview(&record.approval.request_payload);
|
||||
record.approval.response_payload = record
|
||||
.approval
|
||||
.response_payload
|
||||
.as_ref()
|
||||
.map(crank_core::sanitize_invocation_preview);
|
||||
record
|
||||
}
|
||||
|
||||
async fn expire_approval_response(
|
||||
state: &Arc<AppState>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
@@ -597,7 +615,7 @@ async fn expire_approval_response(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(record)) => Json(json!(record)).into_response(),
|
||||
Ok(Some(record)) => Json(json!(safe_approval_record(record))).into_response(),
|
||||
Ok(None) => StatusCode::CONFLICT.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
@@ -843,10 +861,39 @@ async fn mcp_post_response(
|
||||
{
|
||||
Ok(catalog) => {
|
||||
let definitions = catalog_tool_definitions(&catalog);
|
||||
let list_params: ToolsListParams = match serde_json::from_value(params(message))
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
request_id(message),
|
||||
-32602,
|
||||
"invalid tools/list parameters",
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
let page = match paginate_tools_list(definitions, list_params) {
|
||||
Ok(page) => page,
|
||||
Err(message_text) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), json!({ "tools": definitions })),
|
||||
jsonrpc_result(request_id(message), page),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
@@ -940,22 +987,38 @@ pub(super) async fn handle_tool_call(
|
||||
) -> Response {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
if !credential_allows_security_level(credential, resolved.tool.operation.security_level) {
|
||||
let failure = crank_core::ExecutionFailure::new(
|
||||
crank_core::ExecutionErrorCode::AuthorizationDenied,
|
||||
transport_correlation.clone(),
|
||||
);
|
||||
persist_invocation_for_key(
|
||||
&state,
|
||||
&resolved.tool,
|
||||
credential.platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
tool_name: &resolved.tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Warn,
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: None,
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: Duration::ZERO,
|
||||
request_preview: crank_core::sanitize_invocation_preview(&arguments),
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
return tool_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
generic_tool_error_contract(
|
||||
"machine_access_insufficient",
|
||||
format!(
|
||||
"machine access mode {} does not satisfy {} operation security",
|
||||
serialize_machine_access_mode(credential.machine_access_mode),
|
||||
serialize_security_level(resolved.tool.operation.security_level),
|
||||
),
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
false,
|
||||
Some("Используйте ключ агента с достаточным уровнем доступа."),
|
||||
),
|
||||
tool_error_contract_from_failure(&failure, execution_locale(message)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -968,6 +1031,7 @@ pub(super) async fn handle_tool_call(
|
||||
tool: resolved.tool,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
platform_api_key_id: credential.platform_api_key_id.clone(),
|
||||
},
|
||||
transport_correlation,
|
||||
)
|
||||
@@ -1016,10 +1080,7 @@ async fn resolve_runtime_auth_for_task(
|
||||
registry.get_auth_profile(workspace_id, auth_profile_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::SecretCrypto {
|
||||
operation: "load auth profile",
|
||||
details: error.to_string(),
|
||||
})?
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingAuthProfile {
|
||||
auth_profile_id: auth_profile_id.as_str().to_owned(),
|
||||
})?;
|
||||
@@ -1044,39 +1105,47 @@ async fn resolve_auth_profile(
|
||||
registry.get_secret(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::SecretCrypto {
|
||||
operation: "load secret",
|
||||
details: error.to_string(),
|
||||
})?
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecret {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
})?;
|
||||
if secret.secret.status != SecretStatus::Active {
|
||||
return Err(RuntimeError::InvalidAuthSecretValue {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
reason: "secret is not active".to_owned(),
|
||||
});
|
||||
}
|
||||
let version = observe_db_query(
|
||||
DbOperation::SecretRead,
|
||||
registry.get_current_secret_version(workspace_id, secret_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::SecretCrypto {
|
||||
operation: "load current secret version",
|
||||
details: error.to_string(),
|
||||
})?
|
||||
.map_err(|_| RuntimeError::AuthorizationStoreUnavailable)?
|
||||
.ok_or_else(|| RuntimeError::MissingSecretVersion {
|
||||
secret_id: secret_id.as_str().to_owned(),
|
||||
version: secret.secret.current_version,
|
||||
})?;
|
||||
let plaintext = secret_crypto.decrypt(
|
||||
let plaintext = secret_crypto.decrypt_for_epoch(
|
||||
&version.secret_version.key_version,
|
||||
version.master_key_epoch,
|
||||
&version.secret_version.ciphertext,
|
||||
)?;
|
||||
observe_db_query(
|
||||
if observe_db_query(
|
||||
DbOperation::SecretTouch,
|
||||
registry.touch_secret(workspace_id, secret_id, &used_at),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::SecretCrypto {
|
||||
operation: "touch secret",
|
||||
details: error.to_string(),
|
||||
})?;
|
||||
.is_err()
|
||||
{
|
||||
warn!(
|
||||
target: "crank::audit",
|
||||
action = "credential.secret.touch_failed",
|
||||
credential_type = "secret",
|
||||
credential_ref = %secret_id.as_str(),
|
||||
outcome = "metadata_touch_failed",
|
||||
"secret last-used metadata was not updated"
|
||||
);
|
||||
}
|
||||
secrets.insert(SecretId::new(secret_id.as_str()), plaintext);
|
||||
}
|
||||
|
||||
@@ -1092,6 +1161,7 @@ async fn handle_base_tool_call(
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Response {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
let platform_api_key_id = execution.platform_api_key_id;
|
||||
let tool = execution.tool;
|
||||
let arguments = execution.arguments;
|
||||
let operation = runtime_operation(&tool);
|
||||
@@ -1103,15 +1173,16 @@ async fn handle_base_tool_call(
|
||||
.is_some_and(|policy| policy.required)
|
||||
{
|
||||
let approval_span = Stage::ApprovalCheck.span();
|
||||
let response = maybe_handle_approval_policy(
|
||||
&state,
|
||||
let response = maybe_handle_approval_policy(ApprovalPolicyContext {
|
||||
state: &state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
&tool,
|
||||
&arguments,
|
||||
tool: &tool,
|
||||
arguments: &arguments,
|
||||
platform_api_key_id: platform_api_key_id.as_ref(),
|
||||
transport_correlation,
|
||||
)
|
||||
})
|
||||
.instrument(approval_span.clone())
|
||||
.await;
|
||||
if let Some(result) = response {
|
||||
@@ -1144,30 +1215,45 @@ async fn handle_base_tool_call(
|
||||
if let Some(token) = execution.confirmation_token {
|
||||
runtime_request_context = runtime_request_context.with_confirmation_token(token);
|
||||
}
|
||||
let request_preview = build_request_preview(&state.runtime, &operation, &arguments);
|
||||
let started_at = Instant::now();
|
||||
let resolved_auth =
|
||||
resolve_operation_auth(&state, &tool.workspace_id, &operation.execution_config).await;
|
||||
|
||||
let result = match resolved_auth {
|
||||
Ok(resolved_auth) => {
|
||||
state
|
||||
.runtime
|
||||
.execute_request(
|
||||
RuntimeExecutionRequest::new(&operation, &arguments)
|
||||
.with_optional_auth(resolved_auth.as_ref())
|
||||
.with_context(&runtime_request_context),
|
||||
)
|
||||
.await
|
||||
match RuntimeExecutionRequest::try_new(
|
||||
&tool.workspace_id,
|
||||
ExecutionOrigin::AgentSnapshot,
|
||||
Some(&tool.agent_id),
|
||||
&operation,
|
||||
&arguments,
|
||||
ExecutionAuthorization::Authorized,
|
||||
resolved_auth.as_ref(),
|
||||
&runtime_request_context,
|
||||
Instant::now()
|
||||
+ Duration::from_millis(operation.execution_config.timeout_ms.max(1)),
|
||||
) {
|
||||
Ok(request) => state.runtime.execute_outcome(request).await,
|
||||
Err(_) => Err(crank_core::ExecutionFailure::new(
|
||||
crank_core::ExecutionErrorCode::RuntimeInternal,
|
||||
transport_correlation.clone(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
Err(error) => Err(crank_runtime::normalize_runtime_error(
|
||||
&error,
|
||||
transport_correlation,
|
||||
)),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(output) => {
|
||||
persist_invocation(
|
||||
Ok(success) => {
|
||||
let request_preview = success.request_preview;
|
||||
let output = success.output;
|
||||
persist_invocation_for_key(
|
||||
&state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
@@ -1177,6 +1263,10 @@ async fn handle_base_tool_call(
|
||||
message: "agent tool call completed",
|
||||
status_code: None,
|
||||
error_kind: None,
|
||||
execution_stage: Some(crank_core::ExecutionStage::Runtime),
|
||||
execution_error_code: None,
|
||||
retryability: Some(crank_core::Retryability::Never),
|
||||
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview,
|
||||
response_preview: output.clone(),
|
||||
@@ -1186,21 +1276,26 @@ async fn handle_base_tool_call(
|
||||
|
||||
success_tool_response(message, response_mode, &session.protocol_version, output)
|
||||
}
|
||||
Err(error) => {
|
||||
persist_invocation(
|
||||
Err(failure) => {
|
||||
persist_invocation_for_key(
|
||||
&state,
|
||||
&tool,
|
||||
platform_api_key_id.as_ref(),
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Error,
|
||||
level: InvocationLevel::Error,
|
||||
message: runtime_error_code(&error),
|
||||
status_code: None,
|
||||
error_kind: Some(runtime_error_code(&error)),
|
||||
message: failure.error_code().as_str(),
|
||||
status_code: failure.upstream_status(),
|
||||
error_kind: Some(failure.error_code().as_str()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration: started_at.elapsed(),
|
||||
request_preview,
|
||||
request_preview: Value::Null,
|
||||
response_preview: Value::Null,
|
||||
},
|
||||
)
|
||||
@@ -1210,188 +1305,12 @@ async fn handle_base_tool_call(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
tool_error_contract_from_runtime(
|
||||
&error,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
),
|
||||
tool_error_contract_from_failure(&failure, execution_locale(message)),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ApprovalPolicyResult {
|
||||
Required(Response),
|
||||
Error(Response),
|
||||
}
|
||||
|
||||
async fn maybe_handle_approval_policy(
|
||||
state: &Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
let policy = tool.operation.execution_config.approval_policy.as_ref()?;
|
||||
if !policy.required {
|
||||
return None;
|
||||
}
|
||||
|
||||
match policy.mode {
|
||||
OperationApprovalMode::Custom => {
|
||||
maybe_create_custom_pending_approval(
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
transport_correlation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
policy.elicitation_message.as_deref(),
|
||||
transport_correlation,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_custom_pending_approval(
|
||||
state: &Arc<AppState>,
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
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));
|
||||
let approval = ApprovalRequest {
|
||||
id: approval_id,
|
||||
workspace_id: tool.workspace_id.clone(),
|
||||
agent_id: tool.agent_id.clone(),
|
||||
operation_id: tool.operation.id.clone(),
|
||||
operation_version: tool.operation.version,
|
||||
status: ApprovalRequestStatus::Pending,
|
||||
risk_level: policy.risk_level,
|
||||
request_payload: arguments.clone(),
|
||||
response_payload: None,
|
||||
created_at: now,
|
||||
expires_at,
|
||||
decided_at: None,
|
||||
decided_by_key_id: None,
|
||||
decision_note: None,
|
||||
};
|
||||
|
||||
let persisted_approval = match observe_db_query(
|
||||
DbOperation::ApprovalWrite,
|
||||
state
|
||||
.registry
|
||||
.create_approval_request(CreateApprovalRequest {
|
||||
approval: &approval,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(approval) => approval,
|
||||
Err(error) => {
|
||||
return Some(ApprovalPolicyResult::Error(internal_jsonrpc_error(
|
||||
message, error,
|
||||
)));
|
||||
}
|
||||
};
|
||||
let response_payload = approval_required_response(tool, &persisted_approval.approval, policy);
|
||||
|
||||
persist_invocation(
|
||||
state,
|
||||
tool,
|
||||
InvocationRecord {
|
||||
request_id: Some(transport_request_id),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str()),
|
||||
tool_name: &tool.tool_name,
|
||||
status: InvocationStatus::Ok,
|
||||
level: InvocationLevel::Info,
|
||||
message: "agent tool call is waiting for human approval",
|
||||
status_code: None,
|
||||
error_kind: None,
|
||||
duration: Duration::from_millis(0),
|
||||
request_preview: arguments.clone(),
|
||||
response_preview: response_payload.clone(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
Some(ApprovalPolicyResult::Required(success_tool_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
response_payload,
|
||||
)))
|
||||
}
|
||||
|
||||
fn handle_elicitation_approval(
|
||||
session: &SessionState,
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
tool: &PublishedAgentTool,
|
||||
arguments: &Value,
|
||||
elicitation_message: Option<&str>,
|
||||
transport_correlation: &CorrelationContext,
|
||||
) -> ApprovalPolicyResult {
|
||||
let transport_request_id = transport_correlation.request_id().as_str();
|
||||
if !session.supports_elicitation {
|
||||
return ApprovalPolicyResult::Error(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,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
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);
|
||||
|
||||
ApprovalPolicyResult::Required(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.",
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
async fn handle_initialize(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
@@ -1548,91 +1467,6 @@ fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Re
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
||||
let Value::Object(object) = arguments else {
|
||||
return None;
|
||||
};
|
||||
object
|
||||
.remove("_crank_confirmation_token")
|
||||
.and_then(|value| value.as_str().map(str::to_owned))
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn build_request_preview(
|
||||
runtime: &RuntimeExecutor,
|
||||
operation: &RuntimeOperation,
|
||||
arguments: &Value,
|
||||
) -> Value {
|
||||
match runtime.prepare_request(operation, arguments) {
|
||||
Ok(prepared) => json!({
|
||||
"path": prepared.path_params,
|
||||
"query": prepared.query_params,
|
||||
"headers": prepared.headers,
|
||||
"body": prepared.body.unwrap_or(Value::Null)
|
||||
}),
|
||||
Err(_) => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn success_tool_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
output: Value,
|
||||
) -> Response {
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn tool_error_response(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
protocol_version: &str,
|
||||
error: ToolErrorContract,
|
||||
) -> Response {
|
||||
let error_message = tool_error_text(&error);
|
||||
let error_value = tool_error_value(&error);
|
||||
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(protocol_version),
|
||||
)
|
||||
}
|
||||
|
||||
fn add_millis(timestamp: OffsetDateTime, millis: u64) -> OffsetDateTime {
|
||||
let delta = time::Duration::milliseconds(i64::try_from(millis).unwrap_or(i64::MAX));
|
||||
|
||||
|
||||
Reference in new issue
Block a user