Skip to main content

adk_tool/sampling/
mod.rs

1//! MCP sampling callback support for ADK agents.
2//!
3//! Handles `sampling/createMessage` requests from MCP servers by routing
4//! them through the agent's LLM provider.
5//!
6//! Enable with the `mcp-sampling` feature flag.
7//!
8//! # Metering
9//!
10//! A sampling request is a model call made on behalf of whoever triggered it, so
11//! [`LlmSamplingHandler`] calls its model through [`adk_core::generate_metered`]:
12//!
13//! | When the request arrives | It counts against |
14//! |--------------------------|-------------------|
15//! | While an [`McpToolset`](crate::McpToolset) tool call from a run is in flight on the connection | That run's budget and spend ledger ([`ModelCallScope::for_run`]); with calls from several runs in flight, the most recently started one |
16//! | Outside any run's tool call, with a scope attached ([`McpToolset::with_sampling_scope`](crate::McpToolset::with_sampling_scope) or [`AdkClientHandler::with_sampling_scope`](crate::mcp::AdkClientHandler::with_sampling_scope)) | The attached scope |
17//! | Otherwise | Nothing: the call is unmetered |
18//!
19//! A request the budget or spend ledger refuses is never sent to the model; the
20//! MCP server receives an error. A custom [`SamplingHandler`] is metered the same
21//! way when it calls its model through [`adk_core::generate_metered`] or
22//! [`adk_core::MeteredLlm`].
23//!
24//! # Overview
25//!
26//! The MCP protocol allows servers to request that the client generate a message
27//! via `sampling/createMessage`. This module defines the [`SamplingHandler`] trait
28//! for handling those requests, along with the wire types [`SamplingRequest`] and
29//! [`SamplingResponse`].
30//!
31//! # Example
32//!
33//! ```rust,ignore
34//! use adk_tool::sampling::{SamplingHandler, SamplingRequest, SamplingResponse};
35//! use adk_core::Result;
36//!
37//! struct MySamplingHandler;
38//!
39//! #[async_trait::async_trait]
40//! impl SamplingHandler for MySamplingHandler {
41//!     async fn handle_create_message(
42//!         &self,
43//!         request: SamplingRequest,
44//!     ) -> Result<SamplingResponse> {
45//!         // Route to your LLM provider or custom logic
46//!         todo!()
47//!     }
48//! }
49//! ```
50
51use adk_core::model::{FinishReason, GenerateContentConfig, LlmRequest};
52use adk_core::types::{Content, Part};
53use adk_core::{AdkError, ErrorCategory, Llm, ModelCallScope, Result};
54use futures::StreamExt;
55use serde::{Deserialize, Serialize};
56use std::sync::atomic::{AtomicU64, Ordering};
57use std::sync::{Arc, Mutex};
58use tracing::debug;
59
60/// The [`ModelCallScope`]s that sampling requests on one MCP connection count against.
61///
62/// [`McpToolset`](crate::McpToolset) tools register their run's scope for the length of
63/// each call; [`resolve`](Self::resolve) returns the most recently registered scope still
64/// in flight, or the fallback scope when no call is in flight.
65///
66/// # Example
67///
68/// ```
69/// use std::sync::Arc;
70/// use adk_core::{BudgetTracker, ModelCallScope, RunBudget};
71/// use adk_tool::sampling::SamplingScopes;
72///
73/// let scopes = Arc::new(SamplingScopes::default());
74/// assert!(scopes.resolve().is_none());
75///
76/// let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(5)));
77/// let guard = scopes.enter(ModelCallScope::new().with_budget(tracker.clone()));
78/// assert!(Arc::ptr_eq(scopes.resolve().unwrap().budget().unwrap(), &tracker));
79/// drop(guard);
80/// assert!(scopes.resolve().is_none());
81/// ```
82#[derive(Debug, Default)]
83pub struct SamplingScopes {
84    active: Mutex<Vec<(u64, ModelCallScope)>>,
85    fallback: Mutex<Option<ModelCallScope>>,
86    next_id: AtomicU64,
87}
88
89impl SamplingScopes {
90    /// Sets the scope used when no registered call is in flight.
91    pub fn set_fallback(&self, scope: Option<ModelCallScope>) {
92        *self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = scope;
93    }
94
95    /// The scope used when no registered call is in flight.
96    pub fn fallback(&self) -> Option<ModelCallScope> {
97        self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()
98    }
99
100    /// Registers `scope` until the returned guard is dropped.
101    pub fn enter(self: &Arc<Self>, scope: ModelCallScope) -> SamplingScopeGuard {
102        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
103        self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push((id, scope));
104        SamplingScopeGuard { scopes: Arc::clone(self), id }
105    }
106
107    /// The scope a sampling request arriving now counts against.
108    pub fn resolve(&self) -> Option<ModelCallScope> {
109        let active = self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
110        if let Some((_, latest)) = active.last() {
111            if active.iter().any(|(_, scope)| !scope.same_as(latest)) {
112                debug!(
113                    in_flight = active.len(),
114                    "tool calls from several runs are in flight; sampling counts against the latest"
115                );
116            }
117            return Some(latest.clone());
118        }
119        drop(active);
120        self.fallback()
121    }
122}
123
124/// Keeps a scope registered in [`SamplingScopes`] while it is alive.
125#[derive(Debug)]
126pub struct SamplingScopeGuard {
127    scopes: Arc<SamplingScopes>,
128    id: u64,
129}
130
131impl Drop for SamplingScopeGuard {
132    fn drop(&mut self) {
133        self.scopes
134            .active
135            .lock()
136            .unwrap_or_else(|poisoned| poisoned.into_inner())
137            .retain(|(id, _)| *id != self.id);
138    }
139}
140
141/// Trait for handling MCP `sampling/createMessage` requests.
142///
143/// Implementors receive the MCP sampling request and return a response.
144/// The default implementation (provided by `LlmSamplingHandler` in task 8.2)
145/// routes through the agent's LLM provider.
146///
147/// # Example
148///
149/// ```rust,ignore
150/// use adk_tool::sampling::{SamplingHandler, SamplingRequest, SamplingResponse};
151/// use adk_core::Result;
152///
153/// struct MyHandler;
154///
155/// #[async_trait::async_trait]
156/// impl SamplingHandler for MyHandler {
157///     async fn handle_create_message(
158///         &self,
159///         request: SamplingRequest,
160///     ) -> Result<SamplingResponse> {
161///         // Custom sampling logic
162///         todo!()
163///     }
164/// }
165/// ```
166#[async_trait::async_trait]
167pub trait SamplingHandler: Send + Sync {
168    /// Handle a `sampling/createMessage` request from an MCP server.
169    ///
170    /// Receives the sampling parameters and returns the generated message.
171    async fn handle_create_message(&self, request: SamplingRequest) -> Result<SamplingResponse>;
172}
173
174// ---------------------------------------------------------------------------
175// Wire types — camelCase serialization for MCP protocol compatibility
176// ---------------------------------------------------------------------------
177
178/// MCP sampling request parameters.
179///
180/// Represents the payload of a `sampling/createMessage` request from an MCP
181/// server. All optional fields use `skip_serializing_if` to produce minimal
182/// JSON on the wire.
183#[derive(Debug, Clone, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185pub struct SamplingRequest {
186    /// Conversation messages to include in the sampling context.
187    pub messages: Vec<SamplingMessage>,
188
189    /// Optional system prompt to prepend to the conversation.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub system_prompt: Option<String>,
192
193    /// Optional model preferences for provider selection.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub model_preferences: Option<ModelPreferences>,
196
197    /// Maximum number of tokens to generate.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub max_tokens: Option<u32>,
200
201    /// Sampling temperature (0.0 = deterministic, higher = more random).
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub temperature: Option<f64>,
204}
205
206/// MCP sampling response.
207///
208/// Represents the result of a `sampling/createMessage` request, returned
209/// to the MCP server.
210#[derive(Debug, Clone, Serialize, Deserialize)]
211#[serde(rename_all = "camelCase")]
212pub struct SamplingResponse {
213    /// The generated content.
214    pub content: SamplingContent,
215
216    /// Identifier of the model that produced the response.
217    pub model: String,
218
219    /// Reason the model stopped generating (e.g. "endTurn", "maxTokens").
220    pub stop_reason: String,
221}
222
223/// A message in the MCP sampling conversation context.
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct SamplingMessage {
227    /// The role of the message author (e.g. "user", "assistant").
228    pub role: String,
229
230    /// The content of the message.
231    pub content: SamplingContent,
232}
233
234/// Content within a sampling message or response.
235///
236/// Follows the MCP content format with a `type` discriminator.
237#[derive(Debug, Clone, Serialize, Deserialize)]
238#[serde(tag = "type")]
239pub enum SamplingContent {
240    /// Text content.
241    #[serde(rename = "text")]
242    Text {
243        /// The text value.
244        text: String,
245    },
246
247    /// Image content (base64-encoded).
248    #[serde(rename = "image", rename_all = "camelCase")]
249    Image {
250        /// Base64-encoded image data.
251        data: String,
252        /// MIME type of the image (e.g. "image/png").
253        mime_type: String,
254    },
255}
256
257/// Model preferences for sampling requests.
258///
259/// Allows the MCP server to express preferences about which model
260/// should handle the sampling request.
261#[derive(Debug, Clone, Serialize, Deserialize)]
262#[serde(rename_all = "camelCase")]
263pub struct ModelPreferences {
264    /// Hints about preferred models (e.g. model IDs or families).
265    #[serde(default, skip_serializing_if = "Vec::is_empty")]
266    pub hints: Vec<ModelHint>,
267
268    /// Preference for cost optimization (0.0 = cheapest, 1.0 = best quality).
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub cost_priority: Option<f64>,
271
272    /// Preference for speed optimization (0.0 = fastest, 1.0 = best quality).
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub speed_priority: Option<f64>,
275
276    /// Preference for intelligence/quality (0.0 = fastest, 1.0 = smartest).
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub intelligence_priority: Option<f64>,
279}
280
281/// A hint about a preferred model for sampling.
282#[derive(Debug, Clone, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct ModelHint {
285    /// Optional model name or identifier.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub name: Option<String>,
288}
289
290// ---------------------------------------------------------------------------
291// Convenience constructors
292// ---------------------------------------------------------------------------
293
294impl SamplingContent {
295    /// Create text content.
296    ///
297    /// # Example
298    ///
299    /// ```
300    /// use adk_tool::sampling::SamplingContent;
301    ///
302    /// let content = SamplingContent::text("Hello, world!");
303    /// ```
304    pub fn text(text: impl Into<String>) -> Self {
305        Self::Text { text: text.into() }
306    }
307
308    /// Create image content from base64-encoded data.
309    ///
310    /// # Example
311    ///
312    /// ```
313    /// use adk_tool::sampling::SamplingContent;
314    ///
315    /// let content = SamplingContent::image("iVBOR...", "image/png");
316    /// ```
317    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
318        Self::Image { data: data.into(), mime_type: mime_type.into() }
319    }
320}
321
322impl SamplingMessage {
323    /// Create a new sampling message.
324    ///
325    /// # Example
326    ///
327    /// ```
328    /// use adk_tool::sampling::{SamplingContent, SamplingMessage};
329    ///
330    /// let msg = SamplingMessage::new("user", SamplingContent::text("What is 2+2?"));
331    /// ```
332    pub fn new(role: impl Into<String>, content: SamplingContent) -> Self {
333        Self { role: role.into(), content }
334    }
335}
336
337impl SamplingResponse {
338    /// Create a new sampling response.
339    ///
340    /// # Example
341    ///
342    /// ```
343    /// use adk_tool::sampling::{SamplingContent, SamplingResponse};
344    ///
345    /// let response = SamplingResponse::new(
346    ///     SamplingContent::text("4"),
347    ///     "gemini-2.0-flash",
348    ///     "endTurn",
349    /// );
350    /// ```
351    pub fn new(
352        content: SamplingContent,
353        model: impl Into<String>,
354        stop_reason: impl Into<String>,
355    ) -> Self {
356        Self { content, model: model.into(), stop_reason: stop_reason.into() }
357    }
358}
359
360// ---------------------------------------------------------------------------
361// LlmSamplingHandler — default handler routing through the agent's LLM
362// ---------------------------------------------------------------------------
363
364/// Default sampling handler that routes requests through an LLM provider.
365///
366/// Converts [`SamplingRequest`] to an [`LlmRequest`], calls the model through
367/// [`adk_core::generate_metered`], and converts the response back to a
368/// [`SamplingResponse`]. See [Metering](self#metering) for what the call counts
369/// against.
370///
371/// # Example
372///
373/// ```rust,ignore
374/// use adk_tool::sampling::LlmSamplingHandler;
375/// use std::sync::Arc;
376///
377/// let handler = LlmSamplingHandler::new(my_llm.clone());
378/// let response = handler.handle_create_message(request).await?;
379/// ```
380pub struct LlmSamplingHandler {
381    llm: Arc<dyn Llm>,
382}
383
384impl LlmSamplingHandler {
385    /// Create a new handler that routes sampling requests to the given LLM.
386    pub fn new(llm: Arc<dyn Llm>) -> Self {
387        Self { llm }
388    }
389}
390
391#[async_trait::async_trait]
392impl SamplingHandler for LlmSamplingHandler {
393    async fn handle_create_message(&self, request: SamplingRequest) -> Result<SamplingResponse> {
394        let llm_request = sampling_request_to_llm_request(&request, self.llm.name());
395        debug!(
396            model = self.llm.name(),
397            message_count = request.messages.len(),
398            "routing sampling/createMessage to LLM"
399        );
400
401        // Counts against the run that triggered the request; a refused call is not sent.
402        let mut stream = adk_core::generate_metered(self.llm.as_ref(), llm_request, false)
403            .await
404            .map_err(|e| match e.category {
405                ErrorCategory::ResourceExhausted => e,
406                _ if e.code == adk_core::SPEND_LIMIT_EXCEEDED_CODE => e,
407                _ => AdkError::tool(format!("LLM sampling failed: {e}")),
408            })?;
409
410        // Collect the final (non-partial) response from the stream.
411        let mut last_response = None;
412        while let Some(item) = stream.next().await {
413            match item {
414                Ok(resp) => last_response = Some(resp),
415                Err(e) => return Err(AdkError::tool(format!("LLM sampling stream error: {e}"))),
416            }
417        }
418
419        let llm_response = last_response
420            .ok_or_else(|| AdkError::tool("LLM returned empty response for sampling request"))?;
421
422        // Check for LLM-level errors
423        if let Some(ref error_message) = llm_response.error_message {
424            return Err(AdkError::tool(format!("LLM sampling error: {error_message}")));
425        }
426
427        Ok(llm_response_to_sampling_response(llm_response, self.llm.name()))
428    }
429}
430
431// ---------------------------------------------------------------------------
432// Conversion functions
433// ---------------------------------------------------------------------------
434
435/// Convert a [`SamplingRequest`] into an [`LlmRequest`].
436///
437/// Preserves message count/content, system prompt, max tokens, and temperature.
438pub fn sampling_request_to_llm_request(request: &SamplingRequest, model_name: &str) -> LlmRequest {
439    let mut contents = Vec::with_capacity(request.messages.len() + 1);
440
441    // Add system prompt as the first content entry with role "system"
442    if let Some(ref system_prompt) = request.system_prompt {
443        contents.push(Content::new("system").with_text(system_prompt.clone()));
444    }
445
446    // Convert each SamplingMessage to a Content
447    for msg in &request.messages {
448        let role = match msg.role.as_str() {
449            "assistant" => "model",
450            other => other,
451        };
452        let content = match &msg.content {
453            SamplingContent::Text { text } => Content::new(role).with_text(text.clone()),
454            SamplingContent::Image { data, mime_type } => Content {
455                role: role.to_string(),
456                parts: vec![Part::InlineData {
457                    mime_type: mime_type.clone(),
458                    data: base64_decode_lossy(data),
459                    uri: None,
460                    annotations: None,
461                }],
462            },
463        };
464        contents.push(content);
465    }
466
467    let config = GenerateContentConfig {
468        temperature: request.temperature.map(|t| t as f32),
469        max_output_tokens: request.max_tokens.map(|t| t as i32),
470        ..Default::default()
471    };
472
473    LlmRequest {
474        model: model_name.to_string(),
475        contents,
476        config: Some(config),
477        tools: Default::default(),
478        previous_response_id: None,
479    }
480}
481
482/// Convert an [`LlmResponse`](adk_core::model::LlmResponse) into a [`SamplingResponse`].
483///
484/// Preserves content text, model identifier, and maps finish reason to MCP
485/// stop reason strings.
486pub fn llm_response_to_sampling_response(
487    response: adk_core::model::LlmResponse,
488    model_name: &str,
489) -> SamplingResponse {
490    let content = response
491        .content
492        .map(|c| content_to_sampling_content(&c))
493        .unwrap_or_else(|| SamplingContent::text(""));
494
495    let stop_reason = match response.finish_reason {
496        Some(FinishReason::Stop) => "endTurn".to_string(),
497        Some(FinishReason::MaxTokens) => "maxTokens".to_string(),
498        Some(FinishReason::Safety) => "safety".to_string(),
499        Some(FinishReason::Recitation) => "recitation".to_string(),
500        Some(FinishReason::Refusal) => "refusal".to_string(),
501        Some(FinishReason::MalformedToolCall) => "malformedToolCall".to_string(),
502        Some(FinishReason::Other) => "other".to_string(),
503        Some(_) => "other".to_string(),
504        None => "endTurn".to_string(),
505    };
506
507    SamplingResponse { content, model: model_name.to_string(), stop_reason }
508}
509
510/// Extract the first text or image part from a [`Content`] into [`SamplingContent`].
511fn content_to_sampling_content(content: &Content) -> SamplingContent {
512    for part in &content.parts {
513        match part {
514            Part::Text { text } => return SamplingContent::text(text.clone()),
515            Part::InlineData { mime_type, data, .. } => {
516                return SamplingContent::image(base64_encode(data), mime_type.clone());
517            }
518            _ => continue,
519        }
520    }
521    // Fallback: empty text if no text/image parts found
522    SamplingContent::text("")
523}
524
525/// Decode base64 data, returning empty vec on failure.
526fn base64_decode_lossy(input: &str) -> Vec<u8> {
527    use base64::Engine;
528    base64::engine::general_purpose::STANDARD.decode(input).unwrap_or_default()
529}
530
531/// Encode bytes to base64.
532fn base64_encode(data: &[u8]) -> String {
533    use base64::Engine;
534    base64::engine::general_purpose::STANDARD.encode(data)
535}
536
537// ---------------------------------------------------------------------------
538// Tests
539// ---------------------------------------------------------------------------
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544
545    #[test]
546    fn sampling_handler_is_send_sync() {
547        fn require_send_sync<T: Send + Sync>() {}
548        // Trait objects must be Send + Sync
549        require_send_sync::<Box<dyn SamplingHandler>>();
550    }
551
552    #[test]
553    fn sampling_request_json_round_trip() {
554        let request = SamplingRequest {
555            messages: vec![SamplingMessage::new("user", SamplingContent::text("What is 2+2?"))],
556            system_prompt: Some("You are a math tutor.".to_string()),
557            model_preferences: None,
558            max_tokens: Some(100),
559            temperature: Some(0.0),
560        };
561
562        let json = serde_json::to_string(&request).unwrap();
563        let parsed: SamplingRequest = serde_json::from_str(&json).unwrap();
564
565        assert_eq!(parsed.messages.len(), 1);
566        assert_eq!(parsed.system_prompt.as_deref(), Some("You are a math tutor."));
567        assert_eq!(parsed.max_tokens, Some(100));
568        assert_eq!(parsed.temperature, Some(0.0));
569    }
570
571    #[test]
572    fn sampling_response_json_round_trip() {
573        let response =
574            SamplingResponse::new(SamplingContent::text("4"), "gemini-2.0-flash", "endTurn");
575
576        let json = serde_json::to_string(&response).unwrap();
577        let parsed: SamplingResponse = serde_json::from_str(&json).unwrap();
578
579        assert_eq!(parsed.model, "gemini-2.0-flash");
580        assert_eq!(parsed.stop_reason, "endTurn");
581        match &parsed.content {
582            SamplingContent::Text { text } => assert_eq!(text, "4"),
583            _ => panic!("expected text content"),
584        }
585    }
586
587    #[test]
588    fn sampling_request_camel_case_serialization() {
589        let request = SamplingRequest {
590            messages: vec![],
591            system_prompt: Some("test".to_string()),
592            model_preferences: Some(ModelPreferences {
593                hints: vec![ModelHint { name: Some("gpt-4".to_string()) }],
594                cost_priority: Some(0.5),
595                speed_priority: None,
596                intelligence_priority: Some(0.8),
597            }),
598            max_tokens: Some(200),
599            temperature: Some(0.7),
600        };
601
602        let json = serde_json::to_string_pretty(&request).unwrap();
603
604        // Verify camelCase field names
605        assert!(json.contains("systemPrompt"));
606        assert!(json.contains("modelPreferences"));
607        assert!(json.contains("maxTokens"));
608        assert!(json.contains("costPriority"));
609        assert!(json.contains("intelligencePriority"));
610
611        // Verify snake_case is NOT present
612        assert!(!json.contains("system_prompt"));
613        assert!(!json.contains("model_preferences"));
614        assert!(!json.contains("max_tokens"));
615        assert!(!json.contains("cost_priority"));
616        assert!(!json.contains("intelligence_priority"));
617    }
618
619    #[test]
620    fn sampling_response_camel_case_serialization() {
621        let response = SamplingResponse::new(SamplingContent::text("hello"), "model-1", "endTurn");
622
623        let json = serde_json::to_string(&response).unwrap();
624
625        assert!(json.contains("stopReason"));
626        assert!(!json.contains("stop_reason"));
627    }
628
629    #[test]
630    fn sampling_content_text_variant() {
631        let content = SamplingContent::text("hello");
632        let json = serde_json::to_string(&content).unwrap();
633
634        assert!(json.contains(r#""type":"text"#));
635        assert!(json.contains(r#""text":"hello"#));
636
637        let parsed: SamplingContent = serde_json::from_str(&json).unwrap();
638        match parsed {
639            SamplingContent::Text { text } => assert_eq!(text, "hello"),
640            _ => panic!("expected text variant"),
641        }
642    }
643
644    #[test]
645    fn sampling_content_image_variant() {
646        let content = SamplingContent::image("base64data", "image/png");
647        let json = serde_json::to_string(&content).unwrap();
648
649        assert!(json.contains(r#""type":"image"#));
650        assert!(json.contains(r#""data":"base64data"#));
651        assert!(json.contains(r#""mimeType":"image/png"#));
652
653        let parsed: SamplingContent = serde_json::from_str(&json).unwrap();
654        match parsed {
655            SamplingContent::Image { data, mime_type } => {
656                assert_eq!(data, "base64data");
657                assert_eq!(mime_type, "image/png");
658            }
659            _ => panic!("expected image variant"),
660        }
661    }
662
663    #[test]
664    fn sampling_request_optional_fields_omitted() {
665        let request = SamplingRequest {
666            messages: vec![],
667            system_prompt: None,
668            model_preferences: None,
669            max_tokens: None,
670            temperature: None,
671        };
672
673        let json = serde_json::to_string(&request).unwrap();
674
675        // Optional None fields should be omitted
676        assert!(!json.contains("systemPrompt"));
677        assert!(!json.contains("modelPreferences"));
678        assert!(!json.contains("maxTokens"));
679        assert!(!json.contains("temperature"));
680    }
681
682    #[test]
683    fn sampling_message_deserialization_from_mcp_format() {
684        // Verify we can parse the MCP wire format from the design doc
685        let json = r#"{
686            "role": "user",
687            "content": { "type": "text", "text": "What is 2+2?" }
688        }"#;
689
690        let msg: SamplingMessage = serde_json::from_str(json).unwrap();
691        assert_eq!(msg.role, "user");
692        match &msg.content {
693            SamplingContent::Text { text } => assert_eq!(text, "What is 2+2?"),
694            _ => panic!("expected text content"),
695        }
696    }
697
698    #[test]
699    fn model_preferences_empty_hints_omitted() {
700        let prefs = ModelPreferences {
701            hints: vec![],
702            cost_priority: Some(0.5),
703            speed_priority: None,
704            intelligence_priority: None,
705        };
706
707        let json = serde_json::to_string(&prefs).unwrap();
708        assert!(!json.contains("hints"));
709        assert!(json.contains("costPriority"));
710    }
711
712    #[test]
713    fn llm_sampling_handler_is_send_sync() {
714        fn require_send_sync<T: Send + Sync>() {}
715        require_send_sync::<LlmSamplingHandler>();
716    }
717
718    #[test]
719    fn sampling_request_to_llm_request_preserves_messages() {
720        let request = SamplingRequest {
721            messages: vec![
722                SamplingMessage::new("user", SamplingContent::text("Hello")),
723                SamplingMessage::new("assistant", SamplingContent::text("Hi there")),
724                SamplingMessage::new("user", SamplingContent::text("How are you?")),
725            ],
726            system_prompt: None,
727            model_preferences: None,
728            max_tokens: None,
729            temperature: None,
730        };
731
732        let llm_req = sampling_request_to_llm_request(&request, "test-model");
733
734        // 3 messages, no system prompt
735        assert_eq!(llm_req.contents.len(), 3);
736        assert_eq!(llm_req.contents[0].role, "user");
737        assert_eq!(llm_req.contents[1].role, "model"); // assistant → model
738        assert_eq!(llm_req.contents[2].role, "user");
739
740        // Verify text content preserved
741        match &llm_req.contents[0].parts[0] {
742            Part::Text { text } => assert_eq!(text, "Hello"),
743            _ => panic!("expected text part"),
744        }
745    }
746
747    #[test]
748    fn sampling_request_to_llm_request_preserves_system_prompt() {
749        let request = SamplingRequest {
750            messages: vec![SamplingMessage::new("user", SamplingContent::text("Hi"))],
751            system_prompt: Some("You are a helpful assistant.".to_string()),
752            model_preferences: None,
753            max_tokens: None,
754            temperature: None,
755        };
756
757        let llm_req = sampling_request_to_llm_request(&request, "test-model");
758
759        // system prompt + 1 message
760        assert_eq!(llm_req.contents.len(), 2);
761        assert_eq!(llm_req.contents[0].role, "system");
762        match &llm_req.contents[0].parts[0] {
763            Part::Text { text } => assert_eq!(text, "You are a helpful assistant."),
764            _ => panic!("expected text part"),
765        }
766    }
767
768    #[test]
769    fn sampling_request_to_llm_request_preserves_config() {
770        let request = SamplingRequest {
771            messages: vec![],
772            system_prompt: None,
773            model_preferences: None,
774            max_tokens: Some(500),
775            temperature: Some(0.7),
776        };
777
778        let llm_req = sampling_request_to_llm_request(&request, "test-model");
779
780        let config = llm_req.config.unwrap();
781        assert_eq!(config.max_output_tokens, Some(500));
782        // f64 0.7 → f32 0.7 (approximate)
783        assert!((config.temperature.unwrap() - 0.7f32).abs() < 0.001);
784    }
785
786    #[test]
787    fn llm_response_to_sampling_response_preserves_text() {
788        use adk_core::model::{FinishReason, LlmResponse};
789
790        let llm_resp = LlmResponse {
791            content: Some(Content::new("model").with_text("The answer is 42.")),
792            finish_reason: Some(FinishReason::Stop),
793            ..Default::default()
794        };
795
796        let sampling_resp = llm_response_to_sampling_response(llm_resp, "gemini-2.0-flash");
797
798        assert_eq!(sampling_resp.model, "gemini-2.0-flash");
799        assert_eq!(sampling_resp.stop_reason, "endTurn");
800        match &sampling_resp.content {
801            SamplingContent::Text { text } => assert_eq!(text, "The answer is 42."),
802            _ => panic!("expected text content"),
803        }
804    }
805
806    #[test]
807    fn llm_response_to_sampling_response_maps_finish_reasons() {
808        use adk_core::model::{FinishReason, LlmResponse};
809
810        let cases = vec![
811            (Some(FinishReason::Stop), "endTurn"),
812            (Some(FinishReason::MaxTokens), "maxTokens"),
813            (Some(FinishReason::Safety), "safety"),
814            (Some(FinishReason::Recitation), "recitation"),
815            (Some(FinishReason::Refusal), "refusal"),
816            (Some(FinishReason::MalformedToolCall), "malformedToolCall"),
817            (Some(FinishReason::Other), "other"),
818            (None, "endTurn"),
819        ];
820
821        for (finish_reason, expected_stop) in cases {
822            let llm_resp = LlmResponse {
823                content: Some(Content::new("model").with_text("test")),
824                finish_reason,
825                ..Default::default()
826            };
827            let sampling_resp = llm_response_to_sampling_response(llm_resp, "model");
828            assert_eq!(sampling_resp.stop_reason, expected_stop);
829        }
830    }
831
832    #[test]
833    fn llm_response_to_sampling_response_empty_content() {
834        use adk_core::model::LlmResponse;
835
836        let llm_resp = LlmResponse { content: None, ..Default::default() };
837        let sampling_resp = llm_response_to_sampling_response(llm_resp, "model");
838
839        match &sampling_resp.content {
840            SamplingContent::Text { text } => assert_eq!(text, ""),
841            _ => panic!("expected empty text content"),
842        }
843    }
844}