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
@@ -0,0 +1,203 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use axum::response::Response;
|
||||
use crank_core::{
|
||||
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, CorrelationContext, InvocationLevel,
|
||||
InvocationStatus, OperationApprovalMode,
|
||||
};
|
||||
use crank_registry::{CreateApprovalRequest, PublishedAgentTool};
|
||||
use crank_trace::{DbOperation, observe_db_query};
|
||||
use serde_json::{Value, json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{
|
||||
AppState, InvocationRecord, internal_jsonrpc_error, persist_invocation_for_key,
|
||||
response::{success_tool_response, tool_error_response},
|
||||
};
|
||||
use crate::{
|
||||
approval_response::{
|
||||
approval_history_request_preview, approval_history_response_preview,
|
||||
approval_required_response,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::{McpControlError, control_tool_error_contract, execution_locale},
|
||||
transport::ResponseMode,
|
||||
};
|
||||
|
||||
pub(super) enum ApprovalPolicyResult {
|
||||
Required(Response),
|
||||
Error(Response),
|
||||
}
|
||||
|
||||
pub(super) struct ApprovalPolicyContext<'a> {
|
||||
pub state: &'a Arc<AppState>,
|
||||
pub session: &'a SessionState,
|
||||
pub message: &'a Value,
|
||||
pub response_mode: ResponseMode,
|
||||
pub tool: &'a PublishedAgentTool,
|
||||
pub arguments: &'a Value,
|
||||
pub platform_api_key_id: Option<&'a crank_core::PlatformApiKeyId>,
|
||||
pub transport_correlation: &'a CorrelationContext,
|
||||
}
|
||||
|
||||
pub(super) async fn maybe_handle_approval_policy(
|
||||
context: ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
let policy = context
|
||||
.tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()?;
|
||||
if !policy.required {
|
||||
return None;
|
||||
}
|
||||
|
||||
match policy.mode {
|
||||
OperationApprovalMode::Custom => maybe_create_custom_pending_approval(&context).await,
|
||||
OperationApprovalMode::Elicitation => Some(handle_elicitation_approval(
|
||||
context.session,
|
||||
context.message,
|
||||
context.response_mode,
|
||||
context.tool,
|
||||
context.arguments,
|
||||
policy.elicitation_message.as_deref(),
|
||||
context.transport_correlation,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_create_custom_pending_approval(
|
||||
context: &ApprovalPolicyContext<'_>,
|
||||
) -> Option<ApprovalPolicyResult> {
|
||||
let ApprovalPolicyContext {
|
||||
state,
|
||||
session,
|
||||
message,
|
||||
response_mode,
|
||||
tool,
|
||||
arguments,
|
||||
platform_api_key_id,
|
||||
transport_correlation,
|
||||
} = context;
|
||||
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_id: Some(transport_correlation.request_id().as_str().to_owned()),
|
||||
trace_id: Some(transport_correlation.trace_id().as_str().to_owned()),
|
||||
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_for_key(
|
||||
state,
|
||||
tool,
|
||||
*platform_api_key_id,
|
||||
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,
|
||||
execution_stage: Some(crank_core::ExecutionStage::Admission),
|
||||
execution_error_code: None,
|
||||
retryability: Some(crank_core::Retryability::RequiresConfirmation),
|
||||
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
||||
duration: Duration::from_millis(0),
|
||||
request_preview: approval_history_request_preview(&persisted_approval.approval),
|
||||
response_preview: approval_history_response_preview(&response_payload),
|
||||
},
|
||||
)
|
||||
.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,
|
||||
control_tool_error_contract(
|
||||
McpControlError::ApprovalElicitationNotSupported,
|
||||
transport_request_id,
|
||||
transport_correlation.trace_id().as_str(),
|
||||
execution_locale(message),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
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.",
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -22,6 +22,10 @@ pub(crate) struct InvocationRecord<'a> {
|
||||
pub(crate) message: &'a str,
|
||||
pub(crate) status_code: Option<u16>,
|
||||
pub(crate) error_kind: Option<&'a str>,
|
||||
pub(crate) execution_stage: Option<crank_core::ExecutionStage>,
|
||||
pub(crate) execution_error_code: Option<crank_core::ExecutionErrorCode>,
|
||||
pub(crate) retryability: Option<crank_core::Retryability>,
|
||||
pub(crate) outcome_certainty: Option<crank_core::OutcomeCertainty>,
|
||||
pub(crate) duration: Duration,
|
||||
pub(crate) request_preview: Value,
|
||||
pub(crate) response_preview: Value,
|
||||
@@ -31,12 +35,23 @@ pub(crate) async fn persist_invocation(
|
||||
state: &Arc<AppState>,
|
||||
tool: &PublishedAgentTool,
|
||||
record: InvocationRecord<'_>,
|
||||
) -> InvocationHistoryWriteOutcome {
|
||||
persist_invocation_for_key(state, tool, None, record).await
|
||||
}
|
||||
|
||||
pub(crate) async fn persist_invocation_for_key(
|
||||
state: &Arc<AppState>,
|
||||
tool: &PublishedAgentTool,
|
||||
platform_api_key_id: Option<&crank_core::PlatformApiKeyId>,
|
||||
record: InvocationRecord<'_>,
|
||||
) -> InvocationHistoryWriteOutcome {
|
||||
let log = InvocationLog {
|
||||
id: InvocationLogId::new(format!("log_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: tool.workspace_id.clone(),
|
||||
agent_id: Some(tool.agent_id.clone()),
|
||||
platform_api_key_id: platform_api_key_id.cloned(),
|
||||
operation_id: tool.operation.id.clone(),
|
||||
operation_version: Some(tool.operation.version),
|
||||
source: InvocationSource::AgentToolCall,
|
||||
level: record.level,
|
||||
status: record.status,
|
||||
@@ -47,6 +62,10 @@ pub(crate) async fn persist_invocation(
|
||||
status_code: record.status_code,
|
||||
duration_ms: u64::try_from(record.duration.as_millis()).unwrap_or(u64::MAX),
|
||||
error_kind: record.error_kind.map(ToOwned::to_owned),
|
||||
execution_stage: record.execution_stage,
|
||||
execution_error_code: record.execution_error_code,
|
||||
retryability: record.retryability,
|
||||
outcome_certainty: record.outcome_certainty,
|
||||
request_preview: record.request_preview,
|
||||
response_preview: record.response_preview,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct InitializeParams {
|
||||
#[serde(rename = "protocolVersion")]
|
||||
pub(super) protocol_version: String,
|
||||
#[serde(default)]
|
||||
pub(super) capabilities: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct ToolCallParams {
|
||||
pub(super) name: String,
|
||||
#[serde(default)]
|
||||
pub(super) arguments: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct ToolsListParams {
|
||||
#[serde(default)]
|
||||
pub(super) cursor: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(super) limit: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn paginate_tools_list(
|
||||
definitions: Vec<Value>,
|
||||
params: ToolsListParams,
|
||||
) -> Result<Value, &'static str> {
|
||||
const MAX_TOOLS_LIST_LIMIT: usize = 100;
|
||||
let start = match params.cursor {
|
||||
Some(cursor) if cursor.is_empty() => 0,
|
||||
Some(cursor) => cursor
|
||||
.parse::<usize>()
|
||||
.map_err(|_| "invalid tools/list cursor")?,
|
||||
None => 0,
|
||||
};
|
||||
if start > definitions.len() {
|
||||
return Err("tools/list cursor is out of range");
|
||||
}
|
||||
let limit = params
|
||||
.limit
|
||||
.unwrap_or(definitions.len())
|
||||
.clamp(1, MAX_TOOLS_LIST_LIMIT);
|
||||
let end = start.saturating_add(limit).min(definitions.len());
|
||||
let page = definitions[start..end].to_vec();
|
||||
let mut result = json!({ "tools": page });
|
||||
if end < definitions.len() {
|
||||
result["nextCursor"] = json!(end.to_string());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(super) struct ApprovalDecisionPayload {
|
||||
pub(super) approve: String,
|
||||
#[serde(default)]
|
||||
pub(super) note: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{jsonrpc_result, request_id},
|
||||
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
|
||||
pub(crate) 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(crate) 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(crate) 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),
|
||||
)
|
||||
}
|
||||
@@ -22,7 +22,7 @@ use super::{
|
||||
observe_invocation_history_outcome, tool_error_response,
|
||||
};
|
||||
use crate::jsonrpc::{CURRENT_PROTOCOL_VERSION, jsonrpc_error};
|
||||
use crate::tool_error::generic_tool_error_contract;
|
||||
use crate::tool_error::{McpControlError, control_tool_error_contract};
|
||||
use crate::transport::transport_response;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -33,13 +33,11 @@ async fn tool_error_response_includes_structured_context() {
|
||||
&message,
|
||||
ResponseMode::Json,
|
||||
CURRENT_PROTOCOL_VERSION,
|
||||
generic_tool_error_contract(
|
||||
"streaming_payload_error",
|
||||
"request root must be an object",
|
||||
control_tool_error_contract(
|
||||
McpControlError::CatalogRevisionChanged,
|
||||
"req-1",
|
||||
"0af7651916cd43dd8448eb211c80319c",
|
||||
false,
|
||||
Some("Проверьте параметры вызова инструмента."),
|
||||
crank_core::ExecutionLocale::Ru,
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -55,13 +53,16 @@ async fn tool_error_response_includes_structured_context() {
|
||||
assert_eq!(
|
||||
payload["result"]["structuredContent"]["error"],
|
||||
json!({
|
||||
"code": "streaming_payload_error",
|
||||
"error_code": "streaming_payload_error",
|
||||
"message": "request root must be an object",
|
||||
"recoverable": false,
|
||||
"code": "agent_catalog_result_stale",
|
||||
"error_code": "agent_catalog_result_stale",
|
||||
"message": "Версия каталога изменилась.",
|
||||
"stage": "authorization",
|
||||
"retryability": "after_delay",
|
||||
"outcome_certainty": "certain",
|
||||
"recoverable": true,
|
||||
"request_id": "req-1",
|
||||
"trace_id": "0af7651916cd43dd8448eb211c80319c",
|
||||
"suggested_action": "Проверьте параметры вызова инструмента."
|
||||
"suggested_action": "Повторите search_tools и вызовите инструмент с новой версией каталога."
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user