mcp_sdk/
client.rs

1use crate::{
2    protocol::{Protocol, ProtocolBuilder, RequestOptions},
3    transport::Transport,
4    types::{
5        ClientCapabilities, Implementation, InitializeRequest, InitializeResponse,
6        LATEST_PROTOCOL_VERSION,
7    },
8};
9
10use anyhow::Result;
11use tracing::debug;
12
13#[derive(Clone)]
14pub struct Client<T: Transport> {
15    protocol: Protocol<T>,
16}
17
18impl<T: Transport> Client<T> {
19    pub fn builder(transport: T) -> ClientBuilder<T> {
20        ClientBuilder::new(transport)
21    }
22
23    pub async fn initialize(&self, client_info: Implementation) -> Result<InitializeResponse> {
24        let request = InitializeRequest {
25            protocol_version: LATEST_PROTOCOL_VERSION.to_string(),
26            capabilities: ClientCapabilities::default(),
27            client_info,
28        };
29        let response = self
30            .request(
31                "initialize",
32                Some(serde_json::to_value(request)?),
33                RequestOptions::default(),
34            )
35            .await?;
36        let response: InitializeResponse = serde_json::from_value(response)
37            .map_err(|e| anyhow::anyhow!("Failed to parse response: {}", e))?;
38
39        if response.protocol_version != LATEST_PROTOCOL_VERSION {
40            return Err(anyhow::anyhow!(
41                "Unsupported protocol version: {}",
42                response.protocol_version
43            ));
44        }
45
46        debug!(
47            "Initialized with protocol version: {}",
48            response.protocol_version
49        );
50        self.protocol.notify("notifications/initialized", None)?;
51        Ok(response)
52    }
53
54    pub async fn request(
55        &self,
56        method: &str,
57        params: Option<serde_json::Value>,
58        options: RequestOptions,
59    ) -> Result<serde_json::Value> {
60        let response = self.protocol.request(method, params, options).await?;
61        response
62            .result
63            .ok_or_else(|| anyhow::anyhow!("Request failed: {:?}", response.error))
64    }
65
66    pub async fn start(&self) -> Result<()> {
67        self.protocol.listen().await
68    }
69}
70
71pub struct ClientBuilder<T: Transport> {
72    protocol: ProtocolBuilder<T>,
73}
74
75impl<T: Transport> ClientBuilder<T> {
76    pub fn new(transport: T) -> Self {
77        Self {
78            protocol: ProtocolBuilder::new(transport),
79        }
80    }
81
82    pub fn build(self) -> Client<T> {
83        Client {
84            protocol: self.protocol.build(),
85        }
86    }
87}