Skip to main content

systemprompt_cli/commands/shared/
mcp_tools.rs

1//! MCP tool probing shared by `admin agents tools` and `plugins mcp tools`.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use anyhow::{Context, Result};
7use rmcp::ServiceExt;
8use rmcp::model::{ClientCapabilities, ClientInfo, Implementation};
9use rmcp::transport::streamable_http_client::{
10    StreamableHttpClientTransport, StreamableHttpClientTransportConfig,
11};
12use std::time::Duration;
13use systemprompt_identifiers::{
14    Actor, AgentName, ContextId, JwtToken, McpServerId, SessionId, SessionToken, TraceId, UserId,
15};
16use systemprompt_mcp::McpServerConfig;
17use systemprompt_mcp::services::SpawnTarget;
18use systemprompt_mcp::services::client::HttpClientWithContext;
19use systemprompt_models::execution::context::RequestContext;
20use tokio::time::timeout;
21use tracing::debug;
22
23fn probe_context(server_name: &McpServerId) -> RequestContext {
24    RequestContext::new(
25        SessionId::new(format!("cli-{server_name}")),
26        TraceId::generate(),
27        ContextId::derived_from_cli_probe(server_name),
28        AgentName::system(),
29        Actor::anonymous(UserId::generate()),
30    )
31}
32
33#[derive(Debug)]
34pub struct ToolInfo {
35    pub name: String,
36    pub description: Option<String>,
37    pub parameters_count: usize,
38    pub input_schema: Option<serde_json::Value>,
39    pub output_schema: Option<serde_json::Value>,
40}
41
42// Why: an internal server is spawned on a local port and reached there
43// directly; an external one is never spawned and is reached at its endpoint.
44pub fn direct_url(server: &McpServerConfig) -> Result<String> {
45    if server.is_external() {
46        return Ok(server.remote_endpoint.clone());
47    }
48    Ok(format!("http://127.0.0.1:{}/mcp", server.spawn_port()?))
49}
50
51pub async fn list_tools_unauthenticated(
52    server_name: &McpServerId,
53    url: &str,
54    timeout_secs: u64,
55) -> Result<Vec<ToolInfo>> {
56    let config = StreamableHttpClientTransportConfig::with_uri(url);
57    let transport = StreamableHttpClientTransport::with_client(
58        HttpClientWithContext::new(probe_context(server_name))?,
59        config,
60    );
61
62    let client_info = ClientInfo::new(
63        ClientCapabilities::default(),
64        Implementation::new(format!("systemprompt-cli-{}", server_name), "1.0.0"),
65    );
66
67    let client = timeout(
68        Duration::from_secs(timeout_secs),
69        client_info.serve(transport),
70    )
71    .await
72    .context("Connection timeout")?
73    .context("Failed to connect to MCP server")?;
74
75    let tools_response = client
76        // Why: rmcp serialises a `None` params as `"params": null`, which a
77        // strict server (Google's MCP) refuses with -32602; send `{}`.
78        .list_tools(Some(rmcp::model::PaginatedRequestParams::default()))
79        .await
80        .context("Failed to list tools")?;
81
82    let tools: Vec<ToolInfo> = tools_response
83        .tools
84        .into_iter()
85        .map(convert_tool_info)
86        .collect();
87
88    client.cancel().await?;
89    Ok(tools)
90}
91
92pub async fn list_tools_authenticated(
93    server_name: &McpServerId,
94    url: &str,
95    token: &SessionToken,
96    timeout_secs: u64,
97) -> Result<Vec<ToolInfo>> {
98    let config =
99        StreamableHttpClientTransportConfig::with_uri(url).auth_header(token.as_str().to_owned());
100    let context = probe_context(server_name).with_auth_token(JwtToken::new(token.as_str()));
101    let transport =
102        StreamableHttpClientTransport::with_client(HttpClientWithContext::new(context)?, config);
103
104    let client_info = ClientInfo::new(
105        ClientCapabilities::default(),
106        Implementation::new(format!("systemprompt-cli-{}", server_name), "1.0.0"),
107    );
108
109    let client = timeout(
110        Duration::from_secs(timeout_secs),
111        client_info.serve(transport),
112    )
113    .await
114    .context("Connection timeout")?
115    .context("Failed to connect to MCP server")?;
116
117    let tools_response = client
118        // Why: rmcp serialises a `None` params as `"params": null`, which a
119        // strict server (Google's MCP) refuses with -32602; send `{}`.
120        .list_tools(Some(rmcp::model::PaginatedRequestParams::default()))
121        .await
122        .context("Failed to list tools")?;
123
124    let tools: Vec<ToolInfo> = tools_response
125        .tools
126        .into_iter()
127        .map(convert_tool_info)
128        .collect();
129
130    client.cancel().await?;
131    Ok(tools)
132}
133
134fn convert_tool_info(tool: rmcp::model::Tool) -> ToolInfo {
135    let input_schema = match serde_json::to_value(&tool.input_schema) {
136        Ok(schema) => Some(schema),
137        Err(e) => {
138            debug!(tool = %tool.name, error = %e, "Failed to serialize input schema");
139            None
140        },
141    };
142    let output_schema =
143        tool.output_schema
144            .as_ref()
145            .and_then(|s| match serde_json::to_value(s.as_ref()) {
146                Ok(schema) => Some(schema),
147                Err(e) => {
148                    debug!(tool = %tool.name, error = %e, "Failed to serialize output schema");
149                    None
150                },
151            });
152    let parameters_count = input_schema
153        .as_ref()
154        .and_then(|s| s.get("properties"))
155        .and_then(|p| p.as_object())
156        .map_or(0, serde_json::Map::len);
157
158    ToolInfo {
159        name: tool.name.to_string(),
160        description: tool.description.map(|d| d.to_string()),
161        parameters_count,
162        input_schema,
163        output_schema,
164    }
165}