use std::collections::BTreeMap;
use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::format::FormatId;
pub const MAX_IR_TEMPERATURE: f64 = 2.0;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, strum_macros::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum Role {
System,
Developer,
User,
Assistant,
Tool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InstructionBlock {
pub role: Role,
pub content: Vec<ContentBlock>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Message {
pub role: Role,
pub content: Vec<ContentBlock>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phase: Option<String>,
}
impl Message {
pub fn new(role: Role, content: Vec<ContentBlock>) -> Self {
Self {
role,
content,
phase: None,
}
}
pub fn text(role: Role, text: impl Into<String>) -> Self {
Self::new(role, vec![ContentBlock::Text { text: text.into() }])
}
pub fn text_content(&self, separator: &str) -> Option<String> {
let parts = self
.content
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => Some(text.as_str()),
ContentBlock::Refusal { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>();
if parts.is_empty() {
None
} else {
Some(parts.join(separator))
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
Text {
text: String,
},
Reasoning {
text: String,
signature: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
details: Vec<Value>,
},
Image {
source: ImageSource,
},
Audio {
source: MediaSource,
},
Video {
source: MediaSource,
},
File {
source: FileSource,
},
ToolCall(ToolCall),
ToolResult(ToolResult),
Mcp(McpContent),
Refusal {
text: String,
},
Unknown {
provider: FormatId,
raw: Value,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ImageSource {
Url {
url: String,
detail: Option<String>,
},
Base64 {
media_type: Option<String>,
data: String,
},
Raw(Value),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum FileSource {
FileId(String),
FileData {
data: String,
filename: Option<String>,
},
Raw(Value),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum MediaSource {
Url {
url: String,
media_type: Option<String>,
},
Base64 {
media_type: Option<String>,
data: String,
},
Raw(Value),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
pub id: String,
pub name: String,
pub arguments: Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolResult {
pub tool_call_id: String,
pub content: Vec<ContentBlock>,
pub is_error: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolDefinition {
pub name: String,
pub description: Option<String>,
pub parameters: Value,
pub strict: Option<bool>,
}
#[derive(Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Tool {
Mcp(McpToolset),
Provider {
provider: FormatId,
raw: Value,
},
#[serde(untagged)]
Function(ToolDefinition),
}
impl<'de> Deserialize<'de> for Tool {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum TaggedTool {
Mcp(McpToolset),
Provider { provider: FormatId, raw: Value },
Function(ToolDefinition),
}
let value = Value::deserialize(deserializer)?;
if value.get("type").is_none() {
return serde_json::from_value(value)
.map(Self::Function)
.map_err(serde::de::Error::custom);
}
let tool = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
Ok(match tool {
TaggedTool::Mcp(mcp) => Self::Mcp(mcp),
TaggedTool::Provider { provider, raw } => Self::Provider { provider, raw },
TaggedTool::Function(function) => Self::Function(function),
})
}
}
impl fmt::Debug for Tool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Function(definition) => f.debug_tuple("Function").field(definition).finish(),
Self::Mcp(mcp) => f.debug_tuple("Mcp").field(mcp).finish(),
Self::Provider { provider, .. } => f
.debug_struct("Provider")
.field("provider", provider)
.finish_non_exhaustive(),
}
}
}
impl From<ToolDefinition> for Tool {
fn from(definition: ToolDefinition) -> Self {
Self::Function(definition)
}
}
impl Tool {
pub fn function(&self) -> Option<&ToolDefinition> {
match self {
Self::Function(definition) => Some(definition),
_ => None,
}
}
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct McpToolset {
pub name: String,
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization_token: Option<String>,
#[serde(default, skip_serializing_if = "McpToolConfig::is_empty")]
pub default_config: McpToolConfig,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub configs: BTreeMap<String, McpToolConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub require_approval: Option<bool>,
}
impl fmt::Debug for McpToolset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self {
name,
url: _,
authorization_token,
default_config,
configs,
require_approval,
} = self;
f.debug_struct("McpToolset")
.field("name", name)
.field("url", &"[REDACTED]")
.field(
"authorization_token",
&authorization_token.as_ref().map(|_| "[REDACTED]"),
)
.field("default_config", default_config)
.field("configs", configs)
.field("require_approval", require_approval)
.finish()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct McpToolConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub defer_loading: Option<bool>,
}
impl McpToolConfig {
fn is_empty(&self) -> bool {
self.enabled.is_none() && self.defer_loading.is_none()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct McpListedTool {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub input_schema: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub annotations: Option<Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum McpContent {
Listing {
server_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
tools: Vec<McpListedTool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
error: Option<String>,
},
Call {
server_name: String,
call: ToolCall,
},
Result(ToolResult),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ToolChoice {
Auto,
Required,
None,
Tool {
name: String,
},
Raw(Value),
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SamplingParams {
pub temperature: Option<f64>,
pub top_p: Option<f64>,
pub top_k: Option<i64>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct OutputParams {
pub max_output_tokens: Option<u64>,
pub response_format: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub is_schema_enforced: Option<bool>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ReasoningParams {
pub effort: Option<String>,
pub raw: Option<Value>,
}
pub const ANTHROPIC_REQUEST_KEY: &str = "switchyard_anthropic_request";
#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderExtensions {
pub fields: Map<String, Value>,
}
impl fmt::Debug for ProviderExtensions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProviderExtensions")
.field("field_count", &self.fields.len())
.finish_non_exhaustive()
}
}
#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PreservationMetadata {
pub requests: BTreeMap<FormatId, Value>,
pub responses: BTreeMap<FormatId, Value>,
}
impl fmt::Debug for PreservationMetadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PreservationMetadata")
.field("request_formats", &self.requests.keys())
.field("response_formats", &self.responses.keys())
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LlmRequest {
pub model: Option<String>,
pub instructions: Vec<InstructionBlock>,
pub messages: Vec<Message>,
#[serde(skip)]
pub temporary_note_count: usize,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub is_compaction: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub has_compaction: bool,
pub tools: Vec<Tool>,
pub tool_choice: Option<ToolChoice>,
pub sampling: SamplingParams,
pub output: OutputParams,
pub reasoning: ReasoningParams,
pub stream: bool,
pub extensions: ProviderExtensions,
pub preservation: PreservationMetadata,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Usage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider_cost: Option<f64>,
pub input_tokens: Option<u64>,
#[serde(flatten)]
pub cache: Option<Box<InputCacheUsage>>,
pub output_tokens: Option<u64>,
pub total_tokens: Option<u64>,
pub reasoning_tokens: Option<u64>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct InputCacheUsage {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_creation_1h_input_tokens: Option<u64>,
pub cached_input_tokens: Option<u64>,
pub cache_creation_input_tokens: Option<u64>,
}
impl Usage {
pub fn cache_details(
cached_input_tokens: Option<u64>,
cache_creation_input_tokens: Option<u64>,
) -> Option<Box<InputCacheUsage>> {
if cached_input_tokens.is_none() && cache_creation_input_tokens.is_none() {
return None;
}
Some(Box::new(InputCacheUsage {
cache_creation_1h_input_tokens: None,
cached_input_tokens,
cache_creation_input_tokens,
}))
}
pub fn cached_input_tokens(&self) -> Option<u64> {
self.cache
.as_ref()
.and_then(|cache| cache.cached_input_tokens)
}
pub fn cache_creation_input_tokens(&self) -> Option<u64> {
self.cache
.as_ref()
.and_then(|cache| cache.cache_creation_input_tokens)
}
pub fn set_cached_input_tokens(&mut self, value: u64) {
self.cache
.get_or_insert_with(|| Box::new(InputCacheUsage::default()))
.cached_input_tokens = Some(value);
}
pub fn set_cache_creation_input_tokens(&mut self, value: u64) {
self.cache
.get_or_insert_with(|| Box::new(InputCacheUsage::default()))
.cache_creation_input_tokens = Some(value);
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
EndTurn,
MaxTokens,
ToolUse,
ContentFilter,
Error,
Unknown,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UrlCitation {
pub start_index: usize,
pub end_index: usize,
pub url: String,
pub title: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResponseOutput {
pub role: Role,
pub content: Vec<ContentBlock>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub url_citations: Vec<UrlCitation>,
pub stop_reason: Option<StopReason>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AggLlmResponse {
pub id: Option<String>,
pub model: Option<String>,
pub outputs: Vec<ResponseOutput>,
pub usage: Usage,
pub extensions: ProviderExtensions,
pub preservation: PreservationMetadata,
}
impl AggLlmResponse {
pub fn first_output(&self) -> Option<&ResponseOutput> {
self.outputs.first()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn serde_uses_python_friendly_dictionary_shapes() -> Result<(), serde_json::Error> {
let request: LlmRequest = serde_json::from_value(json!({
"model": "auto",
"messages": [{
"role": "user",
"content": [{"type": "text", "text": "hello"}]
}]
}))?;
assert_eq!(request.messages[0], Message::text(Role::User, "hello"));
let tool_call = ContentBlock::ToolCall(ToolCall {
id: "call-1".to_string(),
name: "lookup".to_string(),
arguments: json!({"query": "rust"}),
});
assert_eq!(
serde_json::to_value(tool_call)?,
json!({
"type": "tool_call",
"id": "call-1",
"name": "lookup",
"arguments": {"query": "rust"}
})
);
Ok(())
}
#[test]
fn tool_deserialization_rejects_invalid_tagged_definitions() {
for definition in [
json!({"type": "mcp", "name": "inv", "parameters": {}}),
json!({"type": "provider", "provider": "x", "name": "n", "parameters": {}}),
json!({"type": "unknown", "name": "n", "parameters": {}}),
json!({"type": null, "name": "n", "parameters": {}}),
] {
assert!(serde_json::from_value::<Tool>(definition).is_err());
}
let error = serde_json::from_value::<Tool>(json!({
"type": "mcp", "name": "inv", "url": "https://example.invalid/mcp",
"authorization_token": 5, "parameters": {}
}))
.expect_err("an invalid credential must not become a function")
.to_string();
assert!(error.contains("string"), "field error was lost: {error}");
}
#[test]
fn tool_catalog_preserves_function_json_and_backend_history() -> Result<(), serde_json::Error> {
let function = json!({"name": "lookup", "description": null, "parameters": {"type": "object"}, "strict": null});
let definitions = json!([
function,
{"type": "mcp", "name": "inventory", "url": "https://example.invalid/mcp", "require_approval": false},
{"type": "provider", "provider": "openai_responses", "raw": {"type": "mcp", "connector_id": "connector_example", "server_label": "example"}},
{
"type": "mcp", "name": "configured", "url": "https://example.invalid/mcp",
"default_config": {"enabled": false, "defer_loading": true},
"configs": {"lookup": {"enabled": true}, "search": {"defer_loading": false}}
}
]);
let tools: Vec<Tool> = serde_json::from_value(definitions.clone())?;
assert!(matches!(&tools[0], Tool::Function(_)));
assert!(matches!(&tools[1], Tool::Mcp(_)));
assert!(matches!(&tools[2], Tool::Provider { .. }));
assert_eq!(serde_json::to_value(&tools)?, definitions);
let explicit_function: Tool = serde_json::from_value(json!({
"type": "function", "name": "lookup", "parameters": {"type": "object"}
}))?;
assert_eq!(explicit_function, tools[0]);
let history = json!([
{
"type": "mcp", "kind": "listing", "server_name": "inventory",
"id": "listing_1",
"tools": [{
"name": "lookup", "description": "Look up stock",
"input_schema": {"type": "object"},
"annotations": {"readOnlyHint": true}
}]
},
{"type": "mcp", "kind": "listing", "server_name": "empty", "tools": []},
{
"type": "mcp", "kind": "listing", "server_name": "unavailable",
"tools": [], "error": "Server unavailable"
},
{
"type": "mcp", "kind": "call", "server_name": "inventory",
"call": {"id": "call_1", "name": "lookup", "arguments": {}}
},
{
"type": "mcp", "kind": "result", "tool_call_id": "call_1",
"content": [{"type": "text", "text": "in stock"}], "is_error": false
}
]);
let content: Vec<ContentBlock> = serde_json::from_value(history.clone())?;
assert_eq!(serde_json::to_value(&content)?, history);
Ok(())
}
#[test]
fn mcp_credentials_are_omitted_from_debug() -> Result<(), serde_json::Error> {
let token = "synthetic-mcp-debug-secret";
let url_secret = "synthetic-mcp-url-secret";
let url = format!("https://example.invalid/mcp?api_key={url_secret}");
let mcp: McpToolset = serde_json::from_value(json!({
"name": "inventory", "url": url,
"authorization_token": token
}))?;
let raw = json!({"mcp_servers": [{"authorization_token": token}]});
let mut request = LlmRequest {
tools: vec![
Tool::Mcp(mcp.clone()),
Tool::Provider {
provider: "openai_responses".into(),
raw: json!({"type": "mcp", "authorization": token}),
},
],
..LlmRequest::default()
};
request
.preservation
.requests
.insert("anthropic_messages".into(), raw.clone());
request.extensions.fields.insert("metadata".into(), raw);
let serialized = serde_json::to_value(&request)?;
for debug in [
format!("{mcp:?}"),
format!("{mcp:#?}"),
format!("{:?}", request.tools),
format!("{:?}", request.extensions),
format!("{:?}", request.preservation),
format!("{request:?}"),
format!("{request:#?}"),
] {
assert!(!debug.contains(token), "Debug exposed an MCP credential");
assert!(
!debug.contains(url_secret),
"Debug exposed an MCP URL secret"
);
}
assert_eq!(serde_json::to_value(&request)?, serialized);
assert_eq!(serialized["tools"][0]["url"], url);
assert_eq!(serialized["tools"][0]["authorization_token"], token);
assert_eq!(serialized["tools"][1]["raw"]["authorization"], token);
Ok(())
}
}