BlueGit

ict rusty-teams

Files

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

remote.rs

remote.rs 2.6 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 arguments = if arguments.trim().is_empty() {
51 Map::new()
52 } else {
53 serde_json::from_str::<Value>(arguments)
54 .ok()
55 .and_then(|parsed| parsed.as_object().cloned())
56 .ok_or_else(|| "arguments are not a JSON object".to_owned())?
57 };
58 let params = CallToolRequestParams::new(name.to_owned()).with_arguments(arguments);
59 let result = self
60 .client
61 .call_tool(params)
62 .await
63 .map_err(|error| error.to_string())?;
64 let text = result
65 .content
66 .iter()
67 .filter_map(|content| content.as_text().map(|text| text.text.clone()))
68 .collect::<Vec<_>>()
69 .join("\n");
70 if result.is_error == Some(true) {
71 return Err(if text.is_empty() {
72 format!("{name} failed")
73 } else {
74 text
75 });
76 }
77 Ok(text)
78 }
79}