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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! Tool operations for MCP client
//!
//! This module provides tool-related functionality including listing tools,
//! calling tools, and processing tool results.
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use turbomcp_protocol::types::{
CallToolRequest, CallToolResult, CreateTaskResult, Cursor, ListToolsRequest, ListToolsResult,
TaskMetadata, Tool,
};
use turbomcp_protocol::{Error, Result};
/// Maximum number of pagination pages to prevent infinite loops from misbehaving servers.
const MAX_PAGINATION_PAGES: usize = 1000;
/// Response shape for `tools/call`.
#[derive(Debug, Clone)]
pub enum CallToolResponse {
/// Immediate tool result.
Result(CallToolResult),
/// Task handle for task-augmented execution.
Task(CreateTaskResult),
}
impl<T: turbomcp_transport::Transport + 'static> super::super::core::Client<T> {
/// List all available tools from the MCP server
///
/// Returns complete tool definitions with schemas that can be used
/// for form generation, validation, and documentation. Tools represent
/// executable functions provided by the server.
///
/// # Returns
///
/// Returns a vector of Tool objects with complete metadata including names,
/// descriptions, and input schemas. These schemas can be used to generate
/// user interfaces for tool invocation.
///
/// # Examples
///
/// ```rust,no_run
/// # use turbomcp_client::Client;
/// # use turbomcp_transport::stdio::StdioTransport;
/// # async fn example() -> turbomcp_protocol::Result<()> {
/// let mut client = Client::new(StdioTransport::new());
/// client.initialize().await?;
///
/// let tools = client.list_tools().await?;
/// for tool in tools {
/// println!("Tool: {} - {}", tool.name, tool.description.as_deref().unwrap_or("No description"));
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list_tools(&self) -> Result<Vec<Tool>> {
if !self.inner.initialized.load(Ordering::Relaxed) {
return Err(Error::invalid_request("Client not initialized"));
}
let mut all_tools = Vec::new();
let mut cursor = None;
for _ in 0..MAX_PAGINATION_PAGES {
let result = self.list_tools_paginated(cursor).await?;
let page_empty = result.tools.is_empty();
all_tools.extend(result.tools);
match result.next_cursor {
Some(c) if !page_empty => cursor = Some(c),
_ => break,
}
}
Ok(all_tools)
}
/// List tools with pagination support
///
/// Returns the full `ListToolsResult` including `next_cursor` for manual
/// pagination control. Use `list_tools()` for automatic pagination.
///
/// # Arguments
///
/// * `cursor` - Optional cursor from a previous `ListToolsResult::next_cursor`
pub async fn list_tools_paginated(&self, cursor: Option<Cursor>) -> Result<ListToolsResult> {
if !self.inner.initialized.load(Ordering::Relaxed) {
return Err(Error::invalid_request("Client not initialized"));
}
let request = ListToolsRequest {
cursor,
_meta: None,
};
let params = if request.cursor.is_some() {
Some(serde_json::to_value(&request)?)
} else {
None
};
self.inner.protocol.request("tools/list", params).await
}
/// List available tool names from the MCP server
///
/// Returns only the tool names for cases where full schemas are not needed.
/// For most use cases, prefer `list_tools()` which provides complete tool definitions.
///
/// # Returns
///
/// Returns a vector of tool names available on the server.
///
/// # Examples
///
/// ```rust,no_run
/// # use turbomcp_client::Client;
/// # use turbomcp_transport::stdio::StdioTransport;
/// # async fn example() -> turbomcp_protocol::Result<()> {
/// let mut client = Client::new(StdioTransport::new());
/// client.initialize().await?;
///
/// let tool_names = client.list_tool_names().await?;
/// for name in tool_names {
/// println!("Available tool: {}", name);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list_tool_names(&self) -> Result<Vec<String>> {
let tools = self.list_tools().await?;
Ok(tools.into_iter().map(|tool| tool.name).collect())
}
/// Call a tool on the server
///
/// Executes a tool on the server with the provided arguments and returns
/// the complete MCP `CallToolResult`.
///
/// # Arguments
///
/// * `name` - The name of the tool to call
/// * `arguments` - Optional arguments to pass to the tool
/// * `task` - Must be `None`; task-augmented calls return `CreateTaskResult`.
/// Use [`Self::call_tool_task`] or [`Self::call_tool_response`] for task
/// execution.
///
/// # Returns
///
/// Returns the complete `CallToolResult` with:
/// - `content: Vec<ContentBlock>` - All content blocks (text, image, resource, audio, etc.)
/// - `is_error: Option<bool>` - Whether the tool execution resulted in an error
/// - `structured_content: Option<serde_json::Value>` - Schema-validated structured output
/// - `_meta: Option<serde_json::Value>` - Metadata for client applications (not exposed to LLMs)
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// # use turbomcp_client::Client;
/// # use turbomcp_transport::stdio::StdioTransport;
/// # use turbomcp_protocol::types::ContentBlock;
/// # use std::collections::HashMap;
/// # async fn example() -> turbomcp_protocol::Result<()> {
/// let mut client = Client::new(StdioTransport::new());
/// client.initialize().await?;
///
/// let mut args = HashMap::new();
/// args.insert("input".to_string(), serde_json::json!("test"));
///
/// let result = client.call_tool("my_tool", Some(args), None).await?;
/// # Ok(())
/// # }
/// ```
pub async fn call_tool(
&self,
name: &str,
arguments: Option<HashMap<String, serde_json::Value>>,
task: Option<TaskMetadata>,
) -> Result<CallToolResult> {
if task.is_some() {
return Err(Error::invalid_request(
"task-augmented tools/call returns CreateTaskResult; use call_tool_task or call_tool_response",
));
}
match self.call_tool_response(name, arguments, None).await? {
CallToolResponse::Result(result) => Ok(result),
CallToolResponse::Task(_) => Err(Error::invalid_request(
"task-augmented tools/call returned CreateTaskResult; use call_tool_task or call_tool_response",
)),
}
}
/// Call a tool and preserve the spec-level response variant.
///
/// MCP 2025-11-25 task-augmented `tools/call` returns `CreateTaskResult`
/// immediately. Non-task calls return `CallToolResult`.
pub async fn call_tool_response(
&self,
name: &str,
arguments: Option<HashMap<String, serde_json::Value>>,
task: Option<TaskMetadata>,
) -> Result<CallToolResponse> {
if !self.inner.initialized.load(Ordering::Relaxed) {
return Err(Error::invalid_request("Client not initialized"));
}
let is_task_augmented = task.is_some();
let request_data = CallToolRequest {
name: name.to_string(),
arguments: Some(arguments.unwrap_or_default()),
task,
_meta: None,
};
let raw_result: serde_json::Value = self
.inner
.protocol
.request("tools/call", Some(serde_json::to_value(&request_data)?))
.await?;
if is_task_augmented {
serde_json::from_value(raw_result)
.map(CallToolResponse::Task)
.map_err(|e| {
Error::internal(format!("Failed to deserialize CreateTaskResult: {e}"))
})
} else {
serde_json::from_value(raw_result)
.map(CallToolResponse::Result)
.map_err(|e| Error::internal(format!("Failed to deserialize CallToolResult: {e}")))
}
}
/// Call a tool using MCP task-augmented execution.
///
/// Returns the created task handle. Retrieve the final result with the
/// Tasks API once the server reports completion.
pub async fn call_tool_task(
&self,
name: &str,
arguments: Option<HashMap<String, serde_json::Value>>,
task: TaskMetadata,
) -> Result<CreateTaskResult> {
match self.call_tool_response(name, arguments, Some(task)).await? {
CallToolResponse::Task(result) => Ok(result),
CallToolResponse::Result(_) => Err(Error::invalid_request(
"task-augmented tools/call returned CallToolResult instead of CreateTaskResult",
)),
}
}
}