BlueGit

ict rusty-teams

Files

rusty-teams / crates / mcp / src / remote.rs

remote.rs

remote.rs 2.4 KiB Download Raw
1use rmcp::ServiceExt;
2use rmcp::model::{CallToolRequestParams, ClientConfig};
3use rmcp::transport::StreamableHttpClientTransport;
4use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
5use serde_json::{Map, Value};
6
7use crate::McpEndpoint;
8
9#[derive(Clone, Debug, PartialEq)]
10pub struct ListedTool {
11 pub name: String,
12 pub description: String,
13 pub parameters: Value,
14}
15
16pub struct ToolSession {
17 client: rmcp::service::RunningService<rmcp::RoleClient, ClientConfig>,
18}
19
20impl ToolSession {
21 pub async fn connect(endpoint: &McpEndpoint) -> Result<Self, String> {
22 let transport = StreamableHttpClientTransport::from_config(
23 StreamableHttpClientTransportConfig::with_uri(endpoint.url.clone())
24 .auth_header(endpoint.token.clone()),
25 );
26 let client = ClientConfig::default()
27 .serve(transport)
28 .await
29 .map_err(|error| error.to_string())?;
30 Ok(Self { client })
31 }
32
33 pub async fn tools(&self) -> Result<Vec<ListedTool>, String> {
34 let tools = self
35 .client
36 .list_all_tools()
37 .await
38 .map_err(|error| error.to_string())?;
39 Ok(tools
40 .into_iter()
41 .map(|tool| ListedTool {
42 name: tool.name.to_string(),
43 description: tool.description.unwrap_or_default().to_string(),
44 parameters: Value::Object(tool.input_schema.as_ref().clone()),
45 })
46 .collect())
47 }
48
49 pub async fn call(&self, name: &str, arguments: &str) -> Result<String, String> {
50 let parsed: Value = serde_json::from_str(arguments).unwrap_or(Value::Object(Map::new()));
51 let arguments = parsed.as_object().cloned().unwrap_or_default();
52 let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);
53 let result = self
54 .client
55 .call_tool(params)
56 .await
57 .map_err(|error| error.to_string())?;
58 let text = result
59 .content
60 .iter()
61 .filter_map(|content| content.as_text().map(|text| text.text.clone()))
62 .collect::<Vec<_>>()
63 .join("\n");
64 if result.is_error == Some(true) {
65 return Err(if text.is_empty() {
66 format!("{name} failed")
67 } else {
68 text
69 });
70 }
71 Ok(text)
72 }
73}