use crank_core::{ CorrelationContext, ExecutionFailure, ExecutionLocale, RequestId, Retryability, TraceContext, }; use crank_runtime::{RuntimeError, normalize_runtime_error}; use serde::Serialize; use serde_json::{Value, json}; #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct ToolErrorContract { pub code: &'static str, pub error_code: &'static str, pub stage: &'static str, pub retryability: &'static str, pub outcome_certainty: &'static str, pub message: String, pub recoverable: bool, #[serde(skip_serializing_if = "Option::is_none")] pub suggested_action: Option<&'static str>, #[serde(skip_serializing_if = "Option::is_none")] pub upstream_status: Option, pub request_id: String, pub trace_id: String, } pub fn tool_error_contract_from_runtime( error: &RuntimeError, request_id: &str, trace_id: &str, locale: ExecutionLocale, ) -> ToolErrorContract { let correlation = correlation_from_safe_ids(request_id, trace_id); project_failure(&normalize_runtime_error(error, &correlation), locale) } pub fn tool_error_contract_from_failure( failure: &ExecutionFailure, locale: ExecutionLocale, ) -> ToolErrorContract { project_failure(failure, locale) } fn project_failure(failure: &ExecutionFailure, locale: ExecutionLocale) -> ToolErrorContract { let code = failure.error_code(); let retryability = failure.retryability(); let message = if let Some(challenge) = failure.confirmation() { confirmation_message( code.message(locale), challenge.token(), challenge.expires_in_ms(), locale, ) } else { code.message(locale).to_owned() }; ToolErrorContract { code: code.as_str(), error_code: code.as_str(), stage: failure.stage().as_str(), retryability: retryability.as_str(), outcome_certainty: failure.outcome_certainty().as_str(), message, recoverable: matches!( retryability, Retryability::Safe | Retryability::AfterDelay | Retryability::RequiresConfirmation ), suggested_action: suggested_action(retryability, locale), upstream_status: failure.upstream_status(), request_id: failure.correlation().request_id().to_string(), trace_id: failure.correlation().trace_id().to_string(), } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum McpControlError { CatalogRevisionChanged, ApprovalElicitationNotSupported, } pub fn control_tool_error_contract( error: McpControlError, request_id: &str, trace_id: &str, locale: ExecutionLocale, ) -> ToolErrorContract { let (error_code, message, recoverable, suggested_action) = match (error, locale) { (McpControlError::CatalogRevisionChanged, ExecutionLocale::Ru) => ( "agent_catalog_result_stale", "Версия каталога изменилась.", true, Some("Повторите search_tools и вызовите инструмент с новой версией каталога."), ), (McpControlError::CatalogRevisionChanged, ExecutionLocale::En) => ( "agent_catalog_result_stale", "The catalog revision changed.", true, Some("Run search_tools again and call the tool with the new catalog revision."), ), (McpControlError::ApprovalElicitationNotSupported, ExecutionLocale::Ru) => ( "approval_elicitation_not_supported", "Клиент не поддерживает MCP Elicitation, обязательный для этой операции.", false, Some("Используйте Custom MCP Approval или клиент с поддержкой elicitation."), ), (McpControlError::ApprovalElicitationNotSupported, ExecutionLocale::En) => ( "approval_elicitation_not_supported", "The client does not support MCP Elicitation required by this operation.", false, Some("Use Custom MCP Approval or an elicitation-capable client."), ), }; ToolErrorContract { code: error_code, error_code, stage: "authorization", retryability: if recoverable { "after_delay" } else { "never" }, outcome_certainty: "certain", message: message.to_owned(), recoverable, suggested_action, upstream_status: None, request_id: request_id.to_owned(), trace_id: trace_id.to_owned(), } } pub fn execution_locale(message: &Value) -> ExecutionLocale { let locale = message .pointer("/params/_meta/locale") .or_else(|| message.pointer("/params/locale")) .and_then(Value::as_str) .unwrap_or("en"); if locale.eq_ignore_ascii_case("ru") || locale.to_ascii_lowercase().starts_with("ru-") { ExecutionLocale::Ru } else { ExecutionLocale::En } } pub fn tool_error_text(error: &ToolErrorContract) -> String { match error.suggested_action { Some(action) => format!("{} {}", error.message, action), None => error.message.clone(), } } pub fn tool_error_value(error: &ToolErrorContract) -> Value { serde_json::to_value(error).unwrap_or_else(|_| { json!({ "code": "runtime_internal", "error_code": "runtime_internal", "stage": "runtime", "retryability": "never", "outcome_certainty": "certain", "message": "Внутренняя ошибка выполнения.", "recoverable": false, "request_id": error.request_id, "trace_id": error.trace_id }) }) } fn correlation_from_safe_ids(request_id: &str, trace_id: &str) -> CorrelationContext { let request_id = RequestId::parse(request_id).unwrap_or_else(|_| RequestId::generate()); let trace_context = TraceContext::from_span_parts(trace_id, "0000000000000001", false) .unwrap_or_else(|_| TraceContext::generate()); CorrelationContext::new(request_id, trace_context) } fn confirmation_message( base_message: &str, token: &str, expires_in_ms: u64, locale: ExecutionLocale, ) -> String { match locale { ExecutionLocale::Ru => format!( "{base_message} Повторите вызов с _crank_confirmation_token=\"{token}\" в течение {} секунд.", expires_in_ms / 1000 ), ExecutionLocale::En => format!( "{base_message} Repeat the call with _crank_confirmation_token=\"{token}\" within {} seconds.", expires_in_ms / 1000 ), } } const fn suggested_action( retryability: Retryability, locale: ExecutionLocale, ) -> Option<&'static str> { match (retryability, locale) { (Retryability::AfterDelay | Retryability::Safe, ExecutionLocale::Ru) => { Some("Повторите запрос позже.") } (Retryability::AfterDelay | Retryability::Safe, ExecutionLocale::En) => { Some("Retry the request later.") } (Retryability::ManualReconcile, ExecutionLocale::Ru) => { Some("Проверьте результат во внешней системе перед ручным повтором.") } (Retryability::ManualReconcile, ExecutionLocale::En) => { Some("Check the result in the external system before retrying manually.") } (Retryability::RequiresConfirmation, ExecutionLocale::Ru) => { Some("Повторите вызов с указанным токеном подтверждения.") } (Retryability::RequiresConfirmation, ExecutionLocale::En) => { Some("Repeat the call with the provided confirmation token.") } (Retryability::Never, _) => None, } }