feat: harden community production foundation through story 1.5

This commit is contained in:
bsodfather committed 2026-08-14 00:21:59 +03:00
1 parent c30461cc92
commit f6fc2e5c9b
161 files changed
+16758 -2515

No files matched your search

+56 -59
View File
@@ -14,7 +14,7 @@ use axum::{
};
use crank_core::{
ApprovalRequest, ApprovalRequestId, ApprovalRequestStatus, AuthProfile, CoordinationStateStore,
InvocationLevel, InvocationSource, InvocationStatus, OperationApprovalMode,
CorrelationContext, InvocationLevel, InvocationSource, InvocationStatus, OperationApprovalMode,
PlatformApiKeyScope, SecretId,
};
use crank_registry::{
@@ -64,10 +64,12 @@ use crate::{
mod invocation_history;
mod metrics;
mod stages;
mod tool_resolution;
use self::metrics::{ActiveStreamGuard, McpRequestMetrics};
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;
pub(super) use invocation_history::{InvocationRecord, persist_invocation};
@@ -298,13 +300,13 @@ async fn readiness(State(state): State<Arc<AppState>>) -> Response {
"checks": { "postgres": "ready" }
}))
.into_response(),
Err(error) => (
Err(_) => (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({
"service": "mcp-server",
"status": "not_ready",
"checks": { "postgres": "not_ready" },
"error": error.to_string()
"error": "database is unavailable"
})),
)
.into_response(),
@@ -363,7 +365,7 @@ async fn approve_request(
payload,
PlatformApiKeyScope::Approve,
ApprovalRequestStatus::Approved,
Some(request_context.request_id),
Some(request_context.correlation),
)
.await
}
@@ -425,7 +427,7 @@ async fn decide_approval_request(
payload: ApprovalDecisionPayload,
required_scope: PlatformApiKeyScope,
status: ApprovalRequestStatus,
execution_request_id: Option<String>,
execution_correlation: Option<CorrelationContext>,
) -> Response {
let agent_path = AgentRoutePath {
workspace_slug: path.workspace_slug,
@@ -496,7 +498,7 @@ async fn decide_approval_request(
&state,
&agent_path,
claimed,
execution_request_id.as_deref(),
execution_correlation.as_ref(),
)
.await
{
@@ -719,11 +721,12 @@ async fn mcp_post(
let mut request_metrics = McpRequestMetrics::invalid();
let response = rejection.into_response();
request_metrics.complete(&response);
return with_request_id_header(response, &request_context.request_id);
return with_request_id_header(response, request_context.request_id());
}
};
let mut request_metrics = McpRequestMetrics::new(&message);
let transport_request_id = request_context.request_id;
let transport_correlation = request_context.correlation;
let transport_request_id = transport_correlation.request_id().to_string();
info!(
name: "mcp.request.received",
request_id = %transport_request_id,
@@ -733,7 +736,8 @@ async fn mcp_post(
"mcp request received"
);
let response = mcp_post_response(&path, state, &headers, &message, &transport_request_id).await;
let response =
mcp_post_response(&path, state, &headers, &message, &transport_correlation).await;
request_metrics.complete(&response);
with_request_id_header(response, &transport_request_id)
}
@@ -743,7 +747,7 @@ async fn mcp_post_response(
state: Arc<AppState>,
headers: &HeaderMap,
message: &Value,
transport_request_id: &str,
transport_correlation: &CorrelationContext,
) -> Response {
if let Err(status) = validate_origin(&state.allowed_origins, headers) {
return status.into_response();
@@ -851,10 +855,10 @@ async fn mcp_post_response(
};
let tool_call_params: ToolCallParams = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(error) => {
Err(_) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, error.to_string()),
jsonrpc_error(request_id(message), -32602, "invalid tool call parameters"),
response_mode,
None,
Some(&session.protocol_version),
@@ -883,7 +887,7 @@ async fn mcp_post_response(
&catalog,
&tool_call_params.name,
arguments,
transport_request_id,
transport_correlation,
)
.await
}
@@ -925,8 +929,9 @@ pub(super) async fn handle_tool_call(
resolved: ResolvedToolCall,
arguments: Value,
confirmation_token: Option<String>,
transport_request_id: &str,
transport_correlation: &CorrelationContext,
) -> Response {
let transport_request_id = transport_correlation.request_id().as_str();
if !credential_allows_security_level(credential, resolved.tool.operation.security_level) {
return tool_error_response(
message,
@@ -940,6 +945,7 @@ pub(super) async fn handle_tool_call(
serialize_security_level(resolved.tool.operation.security_level),
),
transport_request_id,
transport_correlation.trace_id().as_str(),
false,
Some("Используйте ключ агента с достаточным уровнем доступа."),
),
@@ -956,7 +962,7 @@ pub(super) async fn handle_tool_call(
arguments,
confirmation_token,
},
transport_request_id,
transport_correlation,
)
.await
}
@@ -1076,8 +1082,9 @@ async fn handle_base_tool_call(
message: &Value,
response_mode: ResponseMode,
execution: ToolCallExecution,
transport_request_id: &str,
transport_correlation: &CorrelationContext,
) -> Response {
let transport_request_id = transport_correlation.request_id().as_str();
let tool = execution.tool;
let arguments = execution.arguments;
let operation = runtime_operation(&tool);
@@ -1096,7 +1103,7 @@ async fn handle_base_tool_call(
response_mode,
&tool,
&arguments,
transport_request_id,
transport_correlation,
)
.instrument(approval_span.clone())
.await;
@@ -1116,16 +1123,17 @@ async fn handle_base_tool_call(
StageOutcome::Allowed.record(&approval_span);
}
let mut runtime_request_context = RuntimeRequestContext::from_request_id(transport_request_id)
.with_response_cache_scope(
tool.workspace_id.as_str().to_owned(),
tool.agent_id.as_str().to_owned(),
)
.with_metering_context(
tool.workspace_id.clone(),
Some(tool.agent_id.clone()),
InvocationSource::AgentToolCall,
);
let mut runtime_request_context =
RuntimeRequestContext::from_correlation(transport_correlation)
.with_response_cache_scope(
tool.workspace_id.as_str().to_owned(),
tool.agent_id.as_str().to_owned(),
)
.with_metering_context(
tool.workspace_id.clone(),
Some(tool.agent_id.clone()),
InvocationSource::AgentToolCall,
);
if let Some(token) = execution.confirmation_token {
runtime_request_context = runtime_request_context.with_confirmation_token(token);
}
@@ -1155,6 +1163,7 @@ async fn handle_base_tool_call(
&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,
@@ -1176,10 +1185,11 @@ async fn handle_base_tool_call(
&tool,
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: &error.to_string(),
message: runtime_error_code(&error),
status_code: None,
error_kind: Some(runtime_error_code(&error)),
duration: started_at.elapsed(),
@@ -1193,7 +1203,11 @@ async fn handle_base_tool_call(
message,
response_mode,
&session.protocol_version,
tool_error_contract_from_runtime(&error, transport_request_id),
tool_error_contract_from_runtime(
&error,
transport_request_id,
transport_correlation.trace_id().as_str(),
),
)
}
}
@@ -1211,7 +1225,7 @@ async fn maybe_handle_approval_policy(
response_mode: ResponseMode,
tool: &PublishedAgentTool,
arguments: &Value,
transport_request_id: &str,
transport_correlation: &CorrelationContext,
) -> Option<ApprovalPolicyResult> {
let policy = tool.operation.execution_config.approval_policy.as_ref()?;
if !policy.required {
@@ -1227,7 +1241,7 @@ async fn maybe_handle_approval_policy(
response_mode,
tool,
arguments,
transport_request_id,
transport_correlation,
)
.await
}
@@ -1238,7 +1252,7 @@ async fn maybe_handle_approval_policy(
tool,
arguments,
policy.elicitation_message.as_deref(),
transport_request_id,
transport_correlation,
)),
}
}
@@ -1250,8 +1264,9 @@ async fn maybe_create_custom_pending_approval(
response_mode: ResponseMode,
tool: &PublishedAgentTool,
arguments: &Value,
transport_request_id: &str,
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()));
@@ -1298,6 +1313,7 @@ async fn maybe_create_custom_pending_approval(
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,
@@ -1326,8 +1342,9 @@ fn handle_elicitation_approval(
tool: &PublishedAgentTool,
arguments: &Value,
elicitation_message: Option<&str>,
transport_request_id: &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,
@@ -1337,6 +1354,7 @@ fn handle_elicitation_approval(
"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.",
@@ -1375,10 +1393,10 @@ async fn handle_initialize(
) -> Response {
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
Ok(value) => value,
Err(error) => {
Err(_error) => {
return transport_response(
StatusCode::OK,
jsonrpc_error(request_id(message), -32602, error.to_string()),
jsonrpc_error(request_id(message), -32602, "invalid initialize parameters"),
response_mode,
None,
Some(DEFAULT_PROTOCOL_VERSION),
@@ -1513,10 +1531,10 @@ async fn require_initialized_session(
Ok(session)
}
fn internal_jsonrpc_error(message: &Value, error: impl std::fmt::Display) -> Response {
fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
transport_response(
StatusCode::INTERNAL_SERVER_ERROR,
jsonrpc_error(request_id(message), -32603, error.to_string()),
jsonrpc_error(request_id(message), -32603, "internal server error"),
ResponseMode::Json,
None,
Some(DEFAULT_PROTOCOL_VERSION),
@@ -1614,26 +1632,5 @@ fn add_millis(timestamp: OffsetDateTime, millis: u64) -> OffsetDateTime {
timestamp + delta
}
pub(super) fn resolve_generated_tool(
tools: &[PublishedAgentTool],
tool_name: &str,
) -> Option<ResolvedToolCall> {
for tool in tools {
if tool.tool_name == tool_name {
return Some(ResolvedToolCall { tool: tool.clone() });
}
}
None
}
pub(super) fn runtime_operation(tool: &PublishedAgentTool) -> RuntimeOperation {
let mut operation = RuntimeOperation::from(tool.operation.clone());
operation.tool_name = tool.tool_name.clone();
operation.tool_description.title = tool.tool_title.clone();
operation.tool_description.description = tool.tool_description.clone();
operation
}
#[cfg(test)]
mod tests;