use http::HeaderMap;
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolContext {
pub user_id: String,
pub session_id: String,
pub developer_id: Option<String>,
pub agent_id: String,
pub interface: String,
pub edge_node_id: Option<String>,
#[serde(skip)]
pub authorization: Option<String>,
}
impl ToolContext {
pub fn from_headers(headers: &HeaderMap) -> Self {
Self {
user_id: first(headers, &["x-marona-user-id", "x-user-id"])
.unwrap_or_else(|| "anonymous".into()),
session_id: first(
headers,
&[
"x-marona-session-id",
"x-runtime-session-id",
"x-conversation-id",
"x-session-id",
],
)
.unwrap_or_else(|| "default".into()),
developer_id: first(headers, &["x-marona-developer-id", "x-developer-id"]),
agent_id: first(headers, &["x-agent-id"]).unwrap_or_else(|| "marona".into()),
interface: first(headers, &["x-marona-interface", "x-runtime-interface"])
.unwrap_or_else(|| "api".into()),
edge_node_id: first(headers, &["x-edge-node-id"]),
authorization: first(headers, &["authorization"]),
}
}
}
impl fmt::Debug for ToolContext {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ToolContext")
.field("user_id", &self.user_id)
.field("session_id", &self.session_id)
.field("developer_id", &self.developer_id)
.field("agent_id", &self.agent_id)
.field("interface", &self.interface)
.field("edge_node_id", &self.edge_node_id)
.field(
"authorization",
&self.authorization.as_ref().map(|_| "[REDACTED]"),
)
.finish()
}
}
fn first(headers: &HeaderMap, names: &[&str]) -> Option<String> {
names.iter().find_map(|name| {
headers
.get(*name)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
})
}
#[cfg(test)]
mod tests {
use http::{HeaderMap, HeaderValue};
use super::ToolContext;
#[test]
fn derives_runtime_scope_from_neutral_marona_headers() {
let mut headers = HeaderMap::new();
headers.insert("x-marona-user-id", HeaderValue::from_static("customer_482"));
headers.insert("x-conversation-id", HeaderValue::from_static("chat_91a7"));
headers.insert("x-agent-id", HeaderValue::from_static("notes"));
headers.insert(
"authorization",
HeaderValue::from_static("Bearer developer_key"),
);
let context = ToolContext::from_headers(&headers);
assert_eq!(context.user_id, "customer_482");
assert_eq!(context.session_id, "chat_91a7");
assert_eq!(context.agent_id, "notes");
assert_eq!(
context.authorization.as_deref(),
Some("Bearer developer_key")
);
assert!(!format!("{context:?}").contains("developer_key"));
}
}