aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,59 @@
//! Prepares MCP approval actions using current bindings without dispatching or remembering approval.
use akode_mcp::ToolInfo;
use akode_protocol::protocol::McpInvocation;
use akode_tools::FunctionCallError;
use super::McpToolApprovalRequirement;
use super::mcp_tool_approval_policy;
use super::mcp_tool_metadata;
use super::parse_mcp_tool_arguments;
use super::prepare_mcp_tool_approval;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
use crate::tools::handlers::McpHandler;
use crate::tools::sandboxing::ApprovalAction;
pub(crate) async fn prepare_approval_action(
invocation: &ToolInvocation,
advertised_tool: &ToolInfo,
) -> Result<Option<ApprovalAction>, FunctionCallError> {
let ToolPayload::Function { arguments } = &invocation.payload else {
return Err(FunctionCallError::RespondToModel(
"mcp handler received unsupported payload".into(),
));
};
let arguments = parse_mcp_tool_arguments(arguments)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
let call = invocation
.session
.prepare_mcp_call(advertised_tool)
.await
.map_err(|err| FunctionCallError::RespondToModel(format!("{err:#}")))?;
let mcp_invocation = McpInvocation {
server: advertised_tool.server_name.clone(),
tool: advertised_tool.tool.name.to_string(),
arguments,
};
let metadata = mcp_tool_metadata(call.tool_info(), call.plugin_id());
let policy = mcp_tool_approval_policy(&call);
match prepare_mcp_tool_approval(
&invocation.session,
&invocation.step_context,
&invocation.call_id,
&mcp_invocation,
&McpHandler::hook_tool_name_for(advertised_tool),
&metadata,
call.config(),
call.permission_source(),
call.server_environment_id(),
policy,
)
.await
{
McpToolApprovalRequirement::NotRequired | McpToolApprovalRequirement::Remembered => {
Ok(None)
}
McpToolApprovalRequirement::Required { action, .. } => Ok(Some(*action)),
}
}

View File

@@ -0,0 +1,189 @@
use std::time::Duration;
use akode_otel::SessionTelemetry;
use akode_otel::sanitize_metric_tag_value;
use akode_protocol::mcp::CallToolResult;
use serde_json::Value as JsonValue;
use tracing::Span;
use crate::tools::ApprovalResolutionSource;
const MCP_CALL_COUNT_METRIC: &str = "codex.mcp.call";
const MCP_CALL_DURATION_METRIC: &str = "codex.mcp.call.duration_ms";
const MCP_CALL_ERROR_COUNT_METRIC: &str = "codex.mcp.call.error";
// No CallToolResult was received. This includes request setup, transport, timeout, protocol, and
// JSON-RPC failures; it does not imply that the request never reached the MCP server.
const MCP_CALL_ERROR_TYPE_MCP_REQUEST: &str = "mcp_request";
// The MCP server returned a CallToolResult with isError=true.
const MCP_CALL_ERROR_TYPE_TOOL_RESULT: &str = "tool_result";
const MCP_CALL_ERROR_CODE_UNKNOWN: &str = "unknown";
const MCP_CALL_ERROR_CODE_MAX_CHARS: usize = 256;
const MCP_CALL_ERROR_TYPE_SPAN_ATTR: &str = "error.type";
const MCP_CALL_ERROR_CODE_SPAN_ATTR: &str = "codex.mcp.error.code";
#[derive(Debug, PartialEq, Eq)]
pub(super) struct McpCallMetricOutcome {
status: &'static str,
error_type: Option<&'static str>,
error_code: Option<String>,
approval_source: Option<&'static str>,
}
impl McpCallMetricOutcome {
pub(super) fn with_request_error_code(mut self, code: Option<&str>) -> Self {
if self.error_type == Some(MCP_CALL_ERROR_TYPE_MCP_REQUEST)
&& let Some(code) = code
{
self.error_code = Some(code.to_string());
}
self
}
pub(super) fn from_status(status: &'static str) -> Self {
Self {
status,
error_type: None,
error_code: None,
approval_source: None,
}
}
pub(super) fn approval_cancelled(source: Option<ApprovalResolutionSource>) -> Self {
Self {
status: "error",
error_type: Some("approval"),
error_code: Some("cancelled".to_string()),
approval_source: Some(match source {
Some(ApprovalResolutionSource::Guardian) => "guardian",
Some(ApprovalResolutionSource::User) => "user",
Some(ApprovalResolutionSource::Hook) => "hook",
None => "unknown",
}),
}
}
}
pub(super) fn emit_mcp_call_metrics(
session_telemetry: &SessionTelemetry,
outcome: &McpCallMetricOutcome,
server_name: &str,
tool_name: &str,
duration: Option<Duration>,
) {
let tags = mcp_call_metric_tags(outcome.status, server_name, tool_name);
let tag_refs: Vec<(&str, &str)> = tags
.iter()
.map(|(key, value)| (*key, value.as_str()))
.collect();
session_telemetry.counter(MCP_CALL_COUNT_METRIC, /*inc*/ 1, &tag_refs);
if let Some(duration) = duration {
session_telemetry.record_duration(MCP_CALL_DURATION_METRIC, duration, &tag_refs);
}
let (Some(error_type), Some(error_code)) = (outcome.error_type, outcome.error_code.as_deref())
else {
return;
};
let mut error_tags = tags;
error_tags.push(("error_type", sanitize_metric_tag_value(error_type)));
error_tags.push(("error_code", error_code.to_string()));
if let Some(approval_source) = outcome.approval_source {
error_tags.push(("approval_source", approval_source.to_string()));
}
let error_tag_refs: Vec<(&str, &str)> = error_tags
.iter()
.map(|(key, value)| (*key, value.as_str()))
.collect();
session_telemetry.counter(MCP_CALL_ERROR_COUNT_METRIC, /*inc*/ 1, &error_tag_refs);
}
fn mcp_call_metric_tags(
status: &str,
server_name: &str,
tool_name: &str,
) -> Vec<(&'static str, String)> {
vec![
("status", sanitize_metric_tag_value(status)),
("server", sanitize_metric_tag_value(server_name)),
("tool", sanitize_metric_tag_value(tool_name)),
]
}
pub(super) fn mcp_call_metric_outcome(
result: &Result<CallToolResult, String>,
) -> McpCallMetricOutcome {
match result {
Ok(result) if result.is_error.unwrap_or(false) => {
let error_code = result
.structured_content
.as_ref()
.and_then(JsonValue::as_object)
.and_then(|structured_content| structured_content.get("error_code"))
.and_then(JsonValue::as_str)
.filter(|error_code| !error_code.is_empty())
.or_else(|| {
result
.meta
.as_ref()
.and_then(|meta| meta.get(super::MCP_RESULT_TELEMETRY_META_KEY))
.and_then(|telemetry| telemetry.get("error_code"))
.and_then(JsonValue::as_str)
.and_then(allowlisted_codex_telemetry_error_code)
});
let error_code: String = error_code
.unwrap_or(MCP_CALL_ERROR_CODE_UNKNOWN)
.chars()
.take(MCP_CALL_ERROR_CODE_MAX_CHARS)
.collect();
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some(sanitize_metric_tag_value(&error_code)),
approval_source: None,
}
}
Ok(_) => McpCallMetricOutcome::from_status("ok"),
Err(_) => McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_MCP_REQUEST),
error_code: Some(MCP_CALL_ERROR_CODE_UNKNOWN.to_string()),
approval_source: None,
},
}
}
fn allowlisted_codex_telemetry_error_code(code: &str) -> Option<&str> {
matches!(
code,
"kernel_start_failed"
| "kernel_exited"
| "kernel_io_error"
| "execution_timeout"
| "execution_cancelled"
| "execution_error"
| "execution_rejected"
| "execution_reset"
| "import_error"
| "syntax_error"
| "reference_error"
| "type_error"
| "uncaught_exception"
| "unhandled_rejection"
| "locator_timeout"
| "guardian_denied"
)
.then_some(code)
}
pub(super) fn record_mcp_call_outcome_span_telemetry(span: &Span, outcome: &McpCallMetricOutcome) {
let (Some(error_type), Some(error_code)) = (outcome.error_type, outcome.error_code.as_deref())
else {
return;
};
span.record(MCP_CALL_ERROR_TYPE_SPAN_ATTR, error_type);
span.record(MCP_CALL_ERROR_CODE_SPAN_ATTR, error_code);
}
#[cfg(test)]
#[path = "telemetry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,200 @@
use super::*;
use pretty_assertions::assert_eq;
fn metric_call_tool_result(
is_error: bool,
structured_content: Option<serde_json::Value>,
) -> CallToolResult {
CallToolResult {
content: Vec::new(),
structured_content,
is_error: Some(is_error),
meta: None,
}
}
#[test]
fn mcp_call_metric_tags_include_server_name() {
assert_eq!(
mcp_call_metric_tags("error", "docs server", "search docs",),
vec![
("status", "error".to_string()),
("server", "docs_server".to_string()),
("tool", "search_docs".to_string()),
],
);
}
#[test]
fn mcp_call_metric_outcome_distinguishes_request_and_tool_errors() {
assert_eq!(
mcp_call_metric_outcome(&Ok(metric_call_tool_result(
/*is_error*/ false, /*structured_content*/ None,
)),),
McpCallMetricOutcome {
status: "ok",
error_type: None,
error_code: None,
approval_source: None,
}
);
assert_eq!(
mcp_call_metric_outcome(&Ok(metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": "RATE_LIMITED"})),
)),),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some("RATE_LIMITED".to_string()),
approval_source: None,
}
);
assert_eq!(
mcp_call_metric_outcome(&Err("connection closed".to_string())),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_MCP_REQUEST),
error_code: Some(MCP_CALL_ERROR_CODE_UNKNOWN.to_string()),
approval_source: None,
}
);
}
#[test]
fn mcp_call_metric_outcome_reports_server_tool_error_codes() {
let result = Ok(metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": "arbitrary-user-value"})),
));
assert_eq!(
mcp_call_metric_outcome(&result),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some("arbitrary-user-value".to_string()),
approval_source: None,
}
);
}
#[test]
fn mcp_call_metric_outcome_reads_telemetry_without_changing_model_output() {
let mut result = CallToolResult {
content: vec![
serde_json::json!({"type": "text", "text": "browser failed"}),
serde_json::json!({"type": "text", "text": "captured output"}),
],
structured_content: None,
is_error: Some(true),
meta: None,
};
let original_output = result.as_function_call_output_payload();
result.meta = Some(serde_json::json!({
"codex/telemetry": {"error_code": "locator_timeout"},
}));
assert_eq!(result.as_function_call_output_payload(), original_output);
assert_eq!(
mcp_call_metric_outcome(&Ok(result)),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some("locator_timeout".to_string()),
approval_source: None,
}
);
}
#[test]
fn mcp_call_metric_outcome_preserves_existing_error_code_precedence() {
let mut result = metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": "RATE_LIMITED"})),
);
result.meta = Some(serde_json::json!({
"codex/telemetry": {"error_code": "locator_timeout"},
}));
for (structured_content, expected_code) in [
(result.structured_content.clone(), "RATE_LIMITED"),
(None, "locator_timeout"),
] {
result.structured_content = structured_content;
assert_eq!(
mcp_call_metric_outcome(&Ok(result.clone())),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some(expected_code.to_string()),
approval_source: None,
}
);
}
}
#[test]
fn mcp_call_metric_outcome_ignores_invalid_telemetry_codes() {
for metadata in [
serde_json::json!({"codex/telemetry": "invalid"}),
serde_json::json!({"codex/telemetry": {"error_code": 42}}),
serde_json::json!({"codex/telemetry": {"error_code": "Bearer credential-sentinel"}}),
serde_json::json!({"codex/telemetry": {"error_code": "locator_timeout:secret-sentinel"}}),
] {
let mut result = metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": ""})),
);
result.meta = Some(metadata);
assert_eq!(
mcp_call_metric_outcome(&Ok(result)),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some(MCP_CALL_ERROR_CODE_UNKNOWN.to_string()),
approval_source: None,
}
);
}
}
#[test]
fn mcp_call_metric_outcome_bounds_and_sanitizes_error_code() {
let raw_error_code = format!("BAD CODE {}", "x".repeat(300));
let result = metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": raw_error_code})),
);
assert_eq!(
mcp_call_metric_outcome(&Ok(result)),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_TOOL_RESULT),
error_code: Some(format!("BAD_CODE_{}", "x".repeat(247))),
approval_source: None,
}
);
}
#[test]
fn caller_error_code_only_applies_to_request_failures() {
assert_eq!(
mcp_call_metric_outcome(&Err("deadline".to_string()))
.with_request_error_code(Some("request_timeout")),
McpCallMetricOutcome {
status: "error",
error_type: Some(MCP_CALL_ERROR_TYPE_MCP_REQUEST),
error_code: Some("request_timeout".to_string()),
approval_source: None,
}
);
let result = Ok(metric_call_tool_result(
/*is_error*/ true,
Some(serde_json::json!({"error_code": "locator_timeout"})),
));
assert_eq!(
mcp_call_metric_outcome(&result).with_request_error_code(Some("request_timeout")),
mcp_call_metric_outcome(&result)
);
}