agent-sdk 0.9.2

Rust Agent SDK for building LLM agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! MCP client implementation.

use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::sync::Arc;

use super::protocol::JsonRpcRequest;
use super::protocol::{
    ClientCapabilities, ClientInfo, InitializeParams, InitializeResult, McpPrompt, McpResource,
    McpToolCallResult, McpToolDefinition, PREFERRED_PROTOCOL_VERSION, PromptGetParams,
    PromptGetResult, PromptsListResult, ResourceReadParams, ResourceReadResult,
    ResourcesListResult, ToolCallParams, ToolsListResult, is_known_protocol_version,
};
use super::transport::McpTransport;

/// MCP protocol revision this client advertises during `initialize`.
///
/// Retained as a public alias of [`PREFERRED_PROTOCOL_VERSION`] for backwards
/// compatibility. The revision actually used for a connection is whatever the
/// server selects during the handshake — see [`McpClient::protocol_version`].
pub const MCP_PROTOCOL_VERSION: &str = PREFERRED_PROTOCOL_VERSION;

/// MCP client for communicating with MCP servers.
///
/// The client handles the MCP protocol, including initialization,
/// tool discovery, and tool execution.
///
/// # Example
///
/// ```ignore
/// use agent_sdk::mcp::{McpClient, StdioTransport};
///
/// // Spawn server and create client
/// let transport = StdioTransport::spawn("npx", &["-y", "mcp-server"]).await?;
/// let client = McpClient::new(transport, "my-server".to_string()).await?;
///
/// // List available tools
/// let tools = client.list_tools().await?;
///
/// // Call a tool
/// let result = client.call_tool("tool_name", json!({"arg": "value"})).await?;
/// ```
pub struct McpClient<T: McpTransport> {
    transport: Arc<T>,
    server_name: String,
    server_info: Option<InitializeResult>,
    /// Protocol revision selected by the server during `initialize`.
    negotiated_version: Option<String>,
}

impl<T: McpTransport> McpClient<T> {
    /// Create a new MCP client and initialize the connection.
    ///
    /// # Arguments
    ///
    /// * `transport` - The transport to use for communication
    /// * `server_name` - A name to identify this server connection
    ///
    /// # Errors
    ///
    /// Returns an error if initialization fails.
    pub async fn new(transport: Arc<T>, server_name: String) -> Result<Self> {
        let mut client = Self {
            transport,
            server_name,
            server_info: None,
            negotiated_version: None,
        };

        client.initialize().await?;

        Ok(client)
    }

    /// Create a client without initialization.
    ///
    /// Use this if you need to control when initialization happens.
    #[must_use]
    pub const fn new_uninitialized(transport: Arc<T>, server_name: String) -> Self {
        Self {
            transport,
            server_name,
            server_info: None,
            negotiated_version: None,
        }
    }

    /// Initialize the MCP connection.
    ///
    /// This must be called before using other methods.
    ///
    /// # Errors
    ///
    /// Returns an error if the server rejects initialization.
    pub async fn initialize(&mut self) -> Result<&InitializeResult> {
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.initialize", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.initialize_inner().await;

        #[cfg(feature = "otel")]
        finish_mcp_span(
            &mut span,
            &result,
            "initialize",
            &self.server_name,
            started_at,
        );

        result?;

        self.server_info
            .as_ref()
            .context("Server info not available")
    }

    async fn initialize_inner(&mut self) -> Result<()> {
        let params = InitializeParams {
            protocol_version: PREFERRED_PROTOCOL_VERSION.to_string(),
            capabilities: ClientCapabilities::default(),
            client_info: ClientInfo {
                name: "agent-sdk".to_string(),
                version: env!("CARGO_PKG_VERSION").to_string(),
            },
        };

        let request = JsonRpcRequest::new("initialize", Some(serde_json::to_value(&params)?), 0);

        let response = self.transport.send(request).await?;

        let result: InitializeResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse initialize response")?
            .context("Initialize response missing result")?;

        // Honour the revision the server actually selected. The server may
        // downgrade to an older revision (e.g. a legacy `2024-11-05` server);
        // we adapt to its choice rather than insisting on our preference. An
        // unrecognised revision is not fatal — proceed but log it.
        let negotiated = result.protocol_version.clone();
        if !is_known_protocol_version(&negotiated) {
            log::warn!(
                "MCP server '{}' negotiated unknown protocol revision '{}' (advertised '{}')",
                self.server_name,
                negotiated,
                PREFERRED_PROTOCOL_VERSION,
            );
        }
        // Inform the transport so out-of-band carriers (HTTP header) can use it.
        self.transport.set_protocol_version(&negotiated).await;
        self.negotiated_version = Some(negotiated);

        // Send initialized notification (fire-and-forget)
        let notification = JsonRpcRequest::new("notifications/initialized", None, 0);
        let _ = self.transport.send_notification(notification).await;

        self.server_info = Some(result);
        Ok(())
    }

    /// Get the server name.
    #[must_use]
    pub fn server_name(&self) -> &str {
        &self.server_name
    }

    /// Get server info if initialized.
    #[must_use]
    pub const fn server_info(&self) -> Option<&InitializeResult> {
        self.server_info.as_ref()
    }

    /// The MCP protocol revision negotiated with the server.
    ///
    /// Returns `None` until [`McpClient::initialize`] has completed. This is
    /// the revision the *server* selected, which may be older than
    /// [`PREFERRED_PROTOCOL_VERSION`] if the server is on a legacy build.
    #[must_use]
    pub fn protocol_version(&self) -> Option<&str> {
        self.negotiated_version.as_deref()
    }

    /// List available tools from the server.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn list_tools(&self) -> Result<Vec<McpToolDefinition>> {
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.tools/list", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.list_tools_inner().await;

        #[cfg(feature = "otel")]
        {
            use opentelemetry::KeyValue;
            use opentelemetry::trace::Span;
            if let Ok(ref tools) = result {
                span.set_attribute(KeyValue::new(
                    "mcp.tools.count",
                    i64::try_from(tools.len()).unwrap_or(0),
                ));
            }
            finish_mcp_span(
                &mut span,
                &result,
                "tools/list",
                &self.server_name,
                started_at,
            );
        }

        result
    }

    async fn list_tools_inner(&self) -> Result<Vec<McpToolDefinition>> {
        let request = JsonRpcRequest::new("tools/list", None, 0);

        let response = self.transport.send(request).await?;

        let result: ToolsListResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse tools/list response")?
            .context("tools/list response missing result")?;

        Ok(result.tools)
    }

    /// Call a tool on the server.
    ///
    /// # Arguments
    ///
    /// * `name` - Tool name to call
    /// * `arguments` - Tool arguments as JSON
    ///
    /// # Errors
    ///
    /// Returns an error if the tool call fails.
    pub async fn call_tool(&self, name: &str, arguments: Value) -> Result<McpToolCallResult> {
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            use opentelemetry::KeyValue;
            let mut span = start_mcp_span_with_attrs(
                "mcp.tools/call",
                vec![
                    KeyValue::new("mcp.server.name", self.server_name.clone()),
                    KeyValue::new("gen_ai.tool.name", name.to_string()),
                ],
            );
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Tool);
            span
        };

        let result = self.call_tool_inner(name, arguments).await;

        #[cfg(feature = "otel")]
        finish_mcp_call_tool_span(
            &mut span,
            &result,
            "tools/call",
            &self.server_name,
            started_at,
        );

        result
    }

    async fn call_tool_inner(&self, name: &str, arguments: Value) -> Result<McpToolCallResult> {
        let params = ToolCallParams {
            name: name.to_string(),
            arguments: Some(arguments),
        };

        let request = JsonRpcRequest::new("tools/call", Some(serde_json::to_value(&params)?), 0);

        let response = self.transport.send(request).await?;

        if let Some(ref error) = response.error {
            bail!("Tool call failed: {} (code {})", error.message, error.code);
        }

        let result: McpToolCallResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse tools/call response")?
            .context("tools/call response missing result")?;

        Ok(result)
    }

    /// Call a tool with raw Value arguments.
    ///
    /// # Arguments
    ///
    /// * `name` - Tool name to call
    /// * `arguments` - Tool arguments as optional JSON
    ///
    /// # Errors
    ///
    /// Returns an error if the tool call fails.
    pub async fn call_tool_raw(
        &self,
        name: &str,
        arguments: Option<Value>,
    ) -> Result<McpToolCallResult> {
        let args = arguments.unwrap_or_else(|| json!({}));
        self.call_tool(name, args).await
    }

    /// List resources exposed by the server (`resources/list`).
    ///
    /// Resources are addressable data (files, database rows, API payloads) the
    /// server makes available for reading. Returns an empty list if the server
    /// did not advertise the `resources` capability.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response cannot be parsed.
    pub async fn list_resources(&self) -> Result<Vec<McpResource>> {
        if !self.supports_resources() {
            return Ok(Vec::new());
        }
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.resources/list", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.list_resources_inner().await;

        #[cfg(feature = "otel")]
        finish_mcp_span(
            &mut span,
            &result,
            "resources/list",
            &self.server_name,
            started_at,
        );

        result
    }

    async fn list_resources_inner(&self) -> Result<Vec<McpResource>> {
        let request = JsonRpcRequest::new("resources/list", None, 0);
        let response = self.transport.send(request).await?;
        let result: ResourcesListResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse resources/list response")?
            .context("resources/list response missing result")?;
        Ok(result.resources)
    }

    /// Read a resource by URI (`resources/read`).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response cannot be parsed.
    pub async fn read_resource(&self, uri: &str) -> Result<ResourceReadResult> {
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.resources/read", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.read_resource_inner(uri).await;

        #[cfg(feature = "otel")]
        finish_mcp_span(
            &mut span,
            &result,
            "resources/read",
            &self.server_name,
            started_at,
        );

        result
    }

    async fn read_resource_inner(&self, uri: &str) -> Result<ResourceReadResult> {
        let params = ResourceReadParams {
            uri: uri.to_string(),
        };
        let request =
            JsonRpcRequest::new("resources/read", Some(serde_json::to_value(&params)?), 0);
        let response = self.transport.send(request).await?;
        let result: ResourceReadResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse resources/read response")?
            .context("resources/read response missing result")?;
        Ok(result)
    }

    /// List prompts exposed by the server (`prompts/list`).
    ///
    /// Returns an empty list if the server did not advertise the `prompts`
    /// capability.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response cannot be parsed.
    pub async fn list_prompts(&self) -> Result<Vec<McpPrompt>> {
        if !self.supports_prompts() {
            return Ok(Vec::new());
        }
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.prompts/list", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.list_prompts_inner().await;

        #[cfg(feature = "otel")]
        finish_mcp_span(
            &mut span,
            &result,
            "prompts/list",
            &self.server_name,
            started_at,
        );

        result
    }

    async fn list_prompts_inner(&self) -> Result<Vec<McpPrompt>> {
        let request = JsonRpcRequest::new("prompts/list", None, 0);
        let response = self.transport.send(request).await?;
        let result: PromptsListResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse prompts/list response")?
            .context("prompts/list response missing result")?;
        Ok(result.prompts)
    }

    /// Fetch and render a prompt by name (`prompts/get`).
    ///
    /// # Arguments
    ///
    /// * `name` - Prompt name to fetch.
    /// * `arguments` - Optional arguments to interpolate into the template.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response cannot be parsed.
    pub async fn get_prompt(
        &self,
        name: &str,
        arguments: Option<Value>,
    ) -> Result<PromptGetResult> {
        #[cfg(feature = "otel")]
        let started_at = std::time::Instant::now();
        #[cfg(feature = "otel")]
        let mut span = {
            use crate::observability::langfuse;
            let mut span = start_mcp_span("mcp.prompts/get", &self.server_name);
            langfuse::tag_observation(&mut span, langfuse::ObservationType::Chain);
            span
        };

        let result = self.get_prompt_inner(name, arguments).await;

        #[cfg(feature = "otel")]
        finish_mcp_span(
            &mut span,
            &result,
            "prompts/get",
            &self.server_name,
            started_at,
        );

        result
    }

    async fn get_prompt_inner(
        &self,
        name: &str,
        arguments: Option<Value>,
    ) -> Result<PromptGetResult> {
        let params = PromptGetParams {
            name: name.to_string(),
            arguments,
        };
        let request = JsonRpcRequest::new("prompts/get", Some(serde_json::to_value(&params)?), 0);
        let response = self.transport.send(request).await?;
        let result: PromptGetResult = response
            .result
            .map(serde_json::from_value)
            .transpose()
            .context("Failed to parse prompts/get response")?
            .context("prompts/get response missing result")?;
        Ok(result)
    }

    /// Whether the server advertised the `resources` capability.
    #[must_use]
    pub fn supports_resources(&self) -> bool {
        self.server_info
            .as_ref()
            .is_some_and(|info| info.capabilities.resources.is_some())
    }

    /// Whether the server advertised the `prompts` capability.
    #[must_use]
    pub fn supports_prompts(&self) -> bool {
        self.server_info
            .as_ref()
            .is_some_and(|info| info.capabilities.prompts.is_some())
    }

    /// Close the client connection.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport fails to close.
    pub async fn close(&self) -> Result<()> {
        self.transport.close().await
    }
}

#[cfg(feature = "otel")]
fn start_mcp_span(
    name: impl Into<std::borrow::Cow<'static, str>>,
    server_name: &str,
) -> opentelemetry::global::BoxedSpan {
    use opentelemetry::KeyValue;
    start_mcp_span_with_attrs(
        name,
        vec![KeyValue::new("mcp.server.name", server_name.to_string())],
    )
}

#[cfg(feature = "otel")]
fn start_mcp_span_with_attrs(
    name: impl Into<std::borrow::Cow<'static, str>>,
    attrs: Vec<opentelemetry::KeyValue>,
) -> opentelemetry::global::BoxedSpan {
    use crate::observability::{baggage, spans};
    let mut span = spans::start_client_span(name, attrs);
    baggage::copy_baggage_to_active_span(&mut span);
    span
}

#[cfg(feature = "otel")]
fn finish_mcp_span<T>(
    span: &mut opentelemetry::global::BoxedSpan,
    result: &Result<T>,
    method: &'static str,
    server_name: &str,
    started_at: std::time::Instant,
) {
    use crate::observability::{metrics, spans};
    use opentelemetry::KeyValue;
    use opentelemetry::trace::Span;

    let mut metric_attrs = vec![
        KeyValue::new("mcp.method", method),
        KeyValue::new("mcp.server.name", server_name.to_string()),
    ];
    if let Err(err) = result {
        spans::set_span_error(span, "mcp_error", &format!("{err}"));
        metric_attrs.push(KeyValue::new(
            crate::observability::attrs::ERROR_TYPE,
            "mcp_error",
        ));
    }
    let elapsed_secs = started_at.elapsed().as_secs_f64();
    metrics::Metrics::global()
        .mcp_requests_duration
        .record(elapsed_secs, &metric_attrs);
    span.end();
}

#[cfg(feature = "otel")]
fn finish_mcp_call_tool_span(
    span: &mut opentelemetry::global::BoxedSpan,
    result: &Result<super::protocol::McpToolCallResult>,
    method: &'static str,
    server_name: &str,
    started_at: std::time::Instant,
) {
    use crate::observability::{metrics, spans};
    use opentelemetry::KeyValue;
    use opentelemetry::trace::Span;

    let mut metric_attrs = vec![
        KeyValue::new("mcp.method", method),
        KeyValue::new("mcp.server.name", server_name.to_string()),
    ];
    let error_kind: Option<&'static str> = match result {
        Ok(tool_result) if tool_result.is_error => {
            let error_text = tool_result
                .content
                .iter()
                .find_map(|c| match c {
                    super::protocol::McpContent::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .unwrap_or("MCP tool returned error");
            spans::set_span_error(span, "tool_error", error_text);
            Some("tool_error")
        }
        Err(err) => {
            spans::set_span_error(span, "mcp_error", &format!("{err}"));
            Some("mcp_error")
        }
        Ok(_) => None,
    };
    if let Some(kind) = error_kind {
        metric_attrs.push(KeyValue::new(crate::observability::attrs::ERROR_TYPE, kind));
    }
    let elapsed_secs = started_at.elapsed().as_secs_f64();
    metrics::Metrics::global()
        .mcp_requests_duration
        .record(elapsed_secs, &metric_attrs);
    span.end();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mcp_protocol_version() {
        assert!(!MCP_PROTOCOL_VERSION.is_empty());
    }

    #[test]
    fn test_client_info() {
        let info = ClientInfo {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
        };

        let json = serde_json::to_string(&info).expect("serialize");
        assert!(json.contains("test"));
        assert!(json.contains("1.0.0"));
    }
}