Skip to main content

adk_server/rest/controllers/
debug.rs

1use crate::ServerConfig;
2use axum::{
3    Extension, Json,
4    extract::{Path, State},
5    http::StatusCode,
6};
7use serde::Serialize;
8use std::collections::HashMap;
9
10#[derive(Clone)]
11pub struct DebugController {
12    config: ServerConfig,
13}
14
15impl DebugController {
16    pub fn new(config: ServerConfig) -> Self {
17        Self { config }
18    }
19}
20
21#[derive(Serialize)]
22pub struct GraphResponse {
23    #[serde(rename = "dotSrc")]
24    pub dot_src: String,
25}
26
27fn authorize_path_user_id(
28    request_context: &Option<adk_core::RequestContext>,
29    user_id: &str,
30) -> Result<(), StatusCode> {
31    match request_context {
32        Some(context) if context.user_id != user_id => Err(StatusCode::FORBIDDEN),
33        _ => Ok(()),
34    }
35}
36
37/// Returns the attributes of the span recorded for an ADK event ID (ADK-Go compatible).
38///
39/// Mounted when no `RequestContextExtractor` is configured, or when
40/// `SecurityConfig::expose_admin_debug` is set. Only the span's `gcp.vertex.agent.event_id`
41/// is matched, so a session ID or any other attribute value answers `404 Not Found`. An
42/// authenticated caller is answered `403 Forbidden` unless the span's `adk.user_id` is
43/// theirs; the owner reads every attribute, the `gcp.vertex.agent.llm_request` and
44/// `gcp.vertex.agent.llm_response` payloads included.
45pub async fn get_trace_by_event_id(
46    State(controller): State<DebugController>,
47    Extension(request_context): Extension<Option<adk_core::RequestContext>>,
48    Path(event_id): Path<String>,
49) -> Result<Json<HashMap<String, String>>, StatusCode> {
50    if request_context.is_some() && !controller.config.security.expose_admin_debug {
51        return Err(StatusCode::NOT_FOUND);
52    }
53
54    // The exporter also answers a span ID, so the event ID itself is checked.
55    let attributes = controller
56        .config
57        .span_exporter
58        .as_ref()
59        .and_then(|exporter| exporter.get_trace_by_event_id(&event_id))
60        .filter(|attributes| {
61            attributes.get("gcp.vertex.agent.event_id").is_some_and(|id| id == &event_id)
62        })
63        .ok_or(StatusCode::NOT_FOUND)?;
64
65    if let Some(context) = &request_context
66        && attributes.get("adk.user_id") != Some(&context.user_id)
67    {
68        return Err(StatusCode::FORBIDDEN);
69    }
70
71    Ok(Json(attributes))
72}
73
74// Convert ADK exporter format to UI-compatible SpanData format
75// Field names must match adk-web Trace.ts interface exactly
76fn convert_to_span_data(attributes: &HashMap<String, String>) -> serde_json::Value {
77    let start_time: u64 = attributes.get("start_time").and_then(|s| s.parse().ok()).unwrap_or(0);
78    let end_time: u64 = attributes.get("end_time").and_then(|s| s.parse().ok()).unwrap_or(0);
79
80    // Build JSON object - omit parent_span_id entirely to prevent nesting
81    let mut obj = serde_json::json!({
82        "name": attributes.get("span_name").map_or("unknown", |v| v.as_str()),
83        "span_id": attributes.get("span_id").map_or("", |v| v.as_str()),
84        "trace_id": attributes.get("trace_id").map_or("", |v| v.as_str()),
85        "start_time": start_time,
86        "end_time": end_time,
87        "attributes": attributes,
88        "invoc_id": attributes.get("gcp.vertex.agent.invocation_id").map_or("", |v| v.as_str())
89    });
90
91    // Add LLM request/response if present (for UI display)
92    if let Some(llm_req) = attributes.get("gcp.vertex.agent.llm_request") {
93        obj["gcp.vertex.agent.llm_request"] = serde_json::Value::String(llm_req.clone());
94    }
95    if let Some(llm_resp) = attributes.get("gcp.vertex.agent.llm_response") {
96        obj["gcp.vertex.agent.llm_response"] = serde_json::Value::String(llm_resp.clone());
97    }
98
99    obj
100}
101
102// Get all spans for a session (UI-compatible format)
103pub async fn get_session_traces(
104    State(controller): State<DebugController>,
105    Extension(request_context): Extension<Option<adk_core::RequestContext>>,
106    Path(session_id): Path<String>,
107) -> Result<Json<Vec<serde_json::Value>>, StatusCode> {
108    if let Some(exporter) = &controller.config.span_exporter {
109        let traces = exporter.get_session_trace(&session_id);
110        if let Some(context) = request_context.as_ref() {
111            for trace in &traces {
112                if let Some(owner) = trace.get("adk.user_id")
113                    && owner != &context.user_id
114                {
115                    return Err(StatusCode::FORBIDDEN);
116                }
117            }
118        }
119        let span_data: Vec<serde_json::Value> = traces.iter().map(convert_to_span_data).collect();
120        return Ok(Json(span_data));
121    }
122
123    Ok(Json(Vec::new()))
124}
125
126pub async fn get_graph(
127    State(_controller): State<DebugController>,
128    Extension(request_context): Extension<Option<adk_core::RequestContext>>,
129    Path((_app_name, user_id, _session_id, _event_id)): Path<(String, String, String, String)>,
130) -> Result<Json<GraphResponse>, (StatusCode, Json<serde_json::Value>)> {
131    authorize_path_user_id(&request_context, &user_id)
132        .map_err(|s| (s, Json(serde_json::json!({"error": "forbidden"}))))?;
133
134    Err((
135        StatusCode::NOT_IMPLEMENTED,
136        Json(serde_json::json!({"error": "graph generation is not yet implemented"})),
137    ))
138}
139
140/// Get evaluation sets for an app
141pub async fn get_eval_sets(
142    State(_controller): State<DebugController>,
143    Extension(_request_context): Extension<Option<adk_core::RequestContext>>,
144    Path(_app_name): Path<String>,
145) -> Result<Json<Vec<serde_json::Value>>, (StatusCode, Json<serde_json::Value>)> {
146    Err((
147        StatusCode::NOT_IMPLEMENTED,
148        Json(serde_json::json!({"error": "eval sets are not yet implemented"})),
149    ))
150}
151
152/// Get event data by event_id - returns event with invocationId for trace linking
153///
154/// Answers `403 Forbidden` when the path user is not the authenticated caller, or
155/// when any span recorded for `session_id` belongs to a different user — traces are
156/// indexed by session ID alone, and session IDs are chosen by their creators.
157pub async fn get_event(
158    State(controller): State<DebugController>,
159    Extension(request_context): Extension<Option<adk_core::RequestContext>>,
160    Path((app_name, user_id, session_id, event_id)): Path<(String, String, String, String)>,
161) -> Result<Json<serde_json::Value>, StatusCode> {
162    authorize_path_user_id(&request_context, &user_id)?;
163
164    // Try to find trace data for this event_id
165    if let Some(exporter) = &controller.config.span_exporter {
166        let traces = exporter.get_session_trace(&session_id);
167        if traces
168            .iter()
169            .any(|trace| trace.get("adk.user_id").is_some_and(|owner| owner != &user_id))
170        {
171            return Err(StatusCode::FORBIDDEN);
172        }
173
174        // Find a trace with matching event_id
175        for attrs in traces {
176            if let Some(stored_event_id) = attrs.get("gcp.vertex.agent.event_id")
177                && stored_event_id == &event_id
178            {
179                // Found matching trace - return event-like structure
180                let invocation_id =
181                    attrs.get("gcp.vertex.agent.invocation_id").cloned().unwrap_or_default();
182
183                return Ok(Json(serde_json::json!({
184                    "id": event_id,
185                    "invocationId": invocation_id,
186                    "appName": app_name,
187                    "sessionId": session_id,
188                    "attributes": attrs,
189                    "gcp.vertex.agent.llm_request": attrs.get("gcp.vertex.agent.llm_request"),
190                    "gcp.vertex.agent.llm_response": attrs.get("gcp.vertex.agent.llm_response")
191                })));
192            }
193        }
194    }
195
196    // Event not found
197    Err(StatusCode::NOT_FOUND)
198}