async_mcp/
client.rs

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
use crate::{
    protocol::{Protocol, ProtocolBuilder, RequestOptions},
    transport::Transport,
    types::{
        ClientCapabilities, Implementation, InitializeRequest, InitializeResponse,
        LATEST_PROTOCOL_VERSION,
    },
};

use anyhow::Result;
use tracing::debug;

#[derive(Clone)]
pub struct Client<T: Transport> {
    protocol: Protocol<T>,
}

impl<T: Transport> Client<T> {
    pub fn builder(transport: T) -> ClientBuilder<T> {
        ClientBuilder::new(transport)
    }

    pub async fn initialize(&self, client_info: Implementation) -> Result<InitializeResponse> {
        let request = InitializeRequest {
            protocol_version: LATEST_PROTOCOL_VERSION.to_string(),
            capabilities: ClientCapabilities::default(),
            client_info,
        };
        let response = self
            .request(
                "initialize",
                Some(serde_json::to_value(request)?),
                RequestOptions::default(),
            )
            .await?;
        let response: InitializeResponse = serde_json::from_value(response)
            .map_err(|e| anyhow::anyhow!("Failed to parse response: {}", e))?;

        if response.protocol_version != LATEST_PROTOCOL_VERSION {
            return Err(anyhow::anyhow!(
                "Unsupported protocol version: {}",
                response.protocol_version
            ));
        }

        debug!(
            "Initialized with protocol version: {}",
            response.protocol_version
        );
        self.protocol
            .notify("notifications/initialized", None)
            .await?;
        Ok(response)
    }

    pub async fn request(
        &self,
        method: &str,
        params: Option<serde_json::Value>,
        options: RequestOptions,
    ) -> Result<serde_json::Value> {
        let response = self.protocol.request(method, params, options).await?;
        response
            .result
            .ok_or_else(|| anyhow::anyhow!("Request failed: {:?}", response.error))
    }

    pub async fn start(&self) -> Result<()> {
        self.protocol.listen().await
    }
}

pub struct ClientBuilder<T: Transport> {
    protocol: ProtocolBuilder<T>,
}

impl<T: Transport> ClientBuilder<T> {
    pub fn new(transport: T) -> Self {
        Self {
            protocol: ProtocolBuilder::new(transport),
        }
    }

    pub fn build(self) -> Client<T> {
        Client {
            protocol: self.protocol.build(),
        }
    }
}